id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,695
That Hey Guys Welcome And Welcome Back To My Channel Suggestion After This Informative Video On Problem Please Like Subscribe My Channel Hai So Absolutely Beauties Notified When Ever Posting Video Songs 2018 Latest Started Problem Is Maximum Erasure Value So In This Problem Yagya One End Area Positive Teachers And Want To Erase Tha Very Difficult Containing A Unique Elements * * * * * * Containing A Unique Elements * * * * * * Containing A Unique Elements * * * * * * Remover Saver Expert Limit So You Get It By Pressing Saver It Is Equal To Include Elements To Motivate Saver Will Remove Right Vitamin E K Elements Which Will Remove The Saver 10 Which Will Get Will Be The Sum Of All Elements Considered In The Survey Report To An Elderly Maximum They Can Get By Exam Clear Removing One Morning OK What Is The Question Is C Which Giveth Which Take Care Limited To Only Source E The Vine to remove a sware first form remove was back in me nine knots sware should have unique element elements that mince no same element that target her no same agreement for example letter this sware can they change survey no right white vikas for revisiting sanjay so is Savere Aa Hain Yasmin Ticket Fare In Remove This Savere 10 Who Will Get Will Be Content Elements From This Survey Two Plus 5 By Votes Of Dentists Eleventh Weekend Tourism Can Remove The Way Also Wished Away The Also Have All The Unique Elements To 10 Of Way Will get history will get a free mode in the morning fifty plus five plus 610 votes that judge classes it can be shown so what we can do it is for more options to think what we can do you can also removed this morning I So free mode morning is directly sauguni element so two plus four plus five plus six a co even while sleeping Korbi 2011 and 608 so marriage to return voteview turn on the maximum co morning of removing exactly one morning-morning Brookings Orange morning one morning-morning Brookings Orange morning one morning-morning Brookings Orange morning withdraw from and element Serial More Relevant Na 100MB Left More Element Per Giver Mausam Needles Will Be Difficult Se Maximum Score Ko Ok No Problem Navlesh Ki Vote Vya-2 Basic Clear Winner To Find A Navlesh Ki Vote Vya-2 Basic Clear Winner To Find A Navlesh Ki Vote Vya-2 Basic Clear Winner To Find A Saver Ki And Desktop Are Password Have Maximum Number Of 210 Problem Which Reduced We Need To find maximum song i savere view to find maximum a survey without that this is the maximum savere a hai tu wherever you aap savere right essential condition that you find the maximum so you can solve this using approach college sliding window will consider all savere is But 1550 Attacking Responsibility Subject The Ko Maximum All Okay Hai A Solid Sequence Hai 200 Views Status For Two 4 5 6 Hai What We Do Basically Sliding Window 8 To Saavni Hai Comment Like Before After Watching This Video You Can Solve The Video Switch Of Baroda Volume Setting Hindu Sushil Poster For What Will You Will Take A Reason Jam And Real Life Which Will Tell Us What Are Under Current Sa Mix Yadav Indore The Fifth I Will Be The Starting Index Turn Off Window That And Will Have This Which Will Wither End Index Of the window and you can see the morning a day of separation answerable which means to all the maxims co initial 2004 ok election list software is yorkshire so they will first give me job but will not be and will the current element in to the current we sodium 4G Welcome Kiya Hai A Nerve Sales Way This To Itra Member Tariff One More Countries Where To Find Maximum Sham Savere And Jharkhand Dot Maximum Savere You Can Apply Card Inquiry This But You Can Not Apply For A Bigg Boss Service Application In Other Country And Shouted Have Unique Elements Aur Tu Bhi Aapko Tak Same Friends Paris Thoughts Unique Element A Now Suhaag Will Get To That Okay This Morning Johnny Element Person To Judgment Side View Of Two Bank Account And Something For Settlement For The Vinod These Elements Have Already Been Completed Before For the time being you will be doing this you can have taken this element in my window right before being considered old already so reason no You can see a small window till the reason even reason time reason probably the courtyard of the window itself width current elements the idea in love and current events in the window that said choice will go to cash fifty two is not interested meaning a unique element right now they are not Taken After Year Tubelight Is The Current Samachar Plus To Be Six And You Will Idea That All Side By Side Size Vipin Gautam Storing System Will Check What Ever Thought Currents Of Minutes Will Update Which Answer This Answer Also Maximum Of The Current Answer And Current If you like it then share answer earthquake six ball six hai naveen ko forward me suji kam this and will sit for this for polytechnic hai winterize normal twist sudeshwar it duplicate records for this world in our hearts and meaning were already taken out in window suggestion or To Shringaar Window Name Adulteration Prohibition Of That Link And Window 12 Board Will Move This Is Very Ballia Sonavar Window Should Be And Sudesh Window Should Be That From This Today Jasbir Vikalp Indore Shehzad Savere And Window Hai Wahi Hui Ke Limit Right Nau Friends With Remove Gift From window what will you try to remove from this set is a but I will again after record this also of the great soul will not completely want this difficult to avoid being removed from the co remove from head to remove From the state key and WhatsApp to all song yahan par reduce friend mix karenge hum is December 8th hai to audition zara to plus form 619 basically when you will remove this element it will surprise that from the current welcome to but since have a basis for all These tools for bhi whatsapp ok and main tujh se what you need to remove from his head and remove tan from the present from corruption from oo me knowledge cea knowledge me forward so five is not interested convenience and adding some serious 511 current respect service six and Mrs Birbal Update Answer Eleventh And Forgive But Now This Also Not In Hearts Virat 6 Share Karna And Window AC Power Window Is From This I2 Dij Me Ki Aapke Willard Siddh Hai Set Willard Singh Assam Tujhe 200 And Will Update An Answer Of Class Seventh And Travels dark sea and answer is sentence for this is the maximum number co maximum number main office deaf be a serving element right unique elements a figure of problem and approach and sun's uttarayan length skin is 412 then proven code is very simple if you try To Right Code Wife This Time Singh Narayan 250 Hours MP Old This Is The Current Summary One And Half Inch Okay Bhaiya Travel Singh Inducted In The And What's Doing So Here Elements In The Wind Of Wine Year Because You Might Happen Responsibility Multiple Duplicates In Two Settings should be like this also in the hearts of witch undhiya finding duplicate unsatisfied defenders element president satellite already present subjects will return value like it will not be equal to the end so what we want to see is that element bloody to river from the current time i will increment Other Elements Who Will Give You Tomorrow Morning Bathing Dream Enter Correct Them And Will Update Dance On The Candidates Willing To Dance On Neighbors' Garden This Time Complexity Neighbors' Garden This Time Complexity Neighbors' Garden This Time Complexity Of Fun And Space Complexity Is Contest Se Over For Acid This One You Must Have Slept Them I quickly wrote my comments manuscript please like and subscribe my channel thank you
Maximum Erasure Value
maximum-sum-obtained-of-any-permutation
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by erasing **exactly one** subarray._ An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`. **Example 1:** **Input:** nums = \[4,2,4,5,6\] **Output:** 17 **Explanation:** The optimal subarray here is \[2,4,5,6\]. **Example 2:** **Input:** nums = \[5,2,1,2,5,2,1,2,5\] **Output:** 8 **Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\]. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104`
Indexes with higher frequencies should be bound with larger values
Array,Greedy,Sorting,Prefix Sum
Medium
null
39
leak code 39 combination sum they'll be very chill are you ready given an array of distinct integers candidates and a Target integer Target return a list of all unique combinations of candidates where the chosen number sums to Target you may return the combinations in any order the same number may be chosen from candidates an unlimited number of times the test Cas is generated such that the number of unique com Okay blah look we have candidates 2 3 6 and 7even and our Target is seven so we just need to find ways to create seven out of these numbers and we are allowed to reuse numbers that is very important to note here so we have 2 two three and we have seven and these three will make seven and this alone will make seven so therefore we return both combinations our input is 2 3 6 7 and our Target is 7 and we're going to make a decision tree so we have an empty list and we want to try to go down each and every path so we have 2 3 6 7 and if it's below seven then we want to keep going if it equals seven we want to add it to our list and if it's greater than seven we want to get rid of that branch and not continue down that path so we go two we can go two again we can go three we go six and we can go seven now when we do this we can just analyze really quickly what this looks like 2 is less than seven 2 and seven together make nine so we don't want to continue going down this path two and six make eight don't want to continue going down this path two and three is five and two is four so we want to continue to go down these two paths let's look at the other numbers when we look at our first level we notice immediately that seven will get us our Target so we actually want to add this into our list this is good okay going back all of these other ones because they are less than seven we want to continue down so how do we do this we could do two again here but you might quickly realize that if we go down this path 3 and two is the same thing as 2 and three they will make the same path at the end of the day with the same numbers so we cannot have that happen so this Branch cannot exist so therefore we should only start three out at three and we can continue on with the remainder of the list because every number that we do with two will already have all of the 3 two combinations in it we do three we do six and we do seven and the same can be said for six and 3 and three and six if we put three here that will give us the same combinations as 3 six so we can't do that we have to just do six and seven okay great now we can also Mark out three and three gives us six so we can continue down that path this gives us 9 this gives us 10 6 and 6 gives us 12 6 and 7 gives us 13 we don't want to continue down those so for these three paths we can keep going we can say 2 3 6 7 and again if we go and do two here it will give us the same as 22 3 or yeah 22 3 because it'll be 2 32 so we only want to start at three here so we do 3 6 7 and 3 6 7 here great um we'll quickly realize 3 33 is 9 too much 3 36 is 15 and 337 is uh 16 it's too much 2 33 gives us 8 too much and so we know all of these are too much as well now when we look at this we know 6 and 7 will be too much and 2 22 we can keep going on this level we see that 223 is equal to 7 so we add that to our list now we keep going for two and we can go 2 3 6 7 but we already know that all of these are out of range here we go we have a final list that we are going to return what the heck final list that we're going to return we have our backtrack function we have a current path which will be current path is like it could be equal to 22 and then continuing on or otherwise then we have our current list that we're looking at which will be the sliced list that we're going to create from having to do this where we don't want to repeat numbers and then we have our total sum which we're going to call sum one now I want to say if sum one is equal to Target then we want to add to our final list. append we want to add current path and then we can return then we can say else if someone is greater than Target we don't want to continue down that path so we can just return and then we have else which is when it is less than Target so this is less than Target okay so we want to iterate through our current list for I and range length of current list we want to add to our sum one we'll add sum one plus equals current list I okay so we grab the current value that we're at and then we can start to backtrack and for our backtrack we want to add current path plus current list I and then from there we do current list and this is where we slice starting from the current index that we're at as you can see we always start from the current index that we're at when we're backtracking down so when we go down three we only at three instead of going back to two Okay and then we add in some one and for the backtracking aspect of it we remove the element that we just put in great so we can call backtrack we can start with an empty list for current path we have our candidates list as our current list and our sumone is zero and we can return final list let's run it excellent perfect let me know what other questions you might want to see
Combination Sum
combination-sum
Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**. The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different. The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input. **Example 1:** **Input:** candidates = \[2,3,6,7\], target = 7 **Output:** \[\[2,2,3\],\[7\]\] **Explanation:** 2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times. 7 is a candidate, and 7 = 7. These are the only two combinations. **Example 2:** **Input:** candidates = \[2,3,5\], target = 8 **Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\] **Example 3:** **Input:** candidates = \[2\], target = 1 **Output:** \[\] **Constraints:** * `1 <= candidates.length <= 30` * `2 <= candidates[i] <= 40` * All elements of `candidates` are **distinct**. * `1 <= target <= 40`
null
Array,Backtracking
Medium
17,40,77,216,254,377
820
Hello hello everyone welcome to desktop owner 40 inch test questions protest in coding of course you will read this description different cities and motivated and look at what ever remember to understand with example of specified in soil and sandal volume music on equation in this example in Time and Energy to String and You Need to Tell the Length of the subscribe for Live Video Noted That a Time Already Covers Minute Difficult Me Valve Will Android Time Will Be Introduced subscribe The Video then subscribe to the Page if you liked The Video then Sixteen Andhadhun Dacoit Your Time Is Style A Next Mediation Novel In It's An Avoid A's Stance Perfectly Fine List Oxford University Time And All Subscribe Question Me Already Subscribe Veer Va Subscribe To Ki Demon Who Want To The Example Slightly Pimple So Let's Get Good Shoulder But Contact Marriage Time Marriage Prohibition That Auspicious Time Is The Longest Word In Research Meena Minute Subscribe Channel Subscribe Hai So IF You Are Able To Understand Second Gram Plus Give Wealth Like Life In President Dr Ko Shuddh Problem Reducer To Identified With Limits Of Elements from the covered boy double from the covered boy double from the covered boy double Meets with a rebuff Times what we are interested in mid day meal subscribe The Video then subscribe to the Video then subscribe to Did not end with both ends with time so that will return forms I hope this Method so to you show me the art and craft with time set valuable time and with me tweet want to listen with logic will have two point element in a day will compete with every element no input se withdrawal check every element person with you the police tried To solve that show time apps element that media note and time I am did not end with time table date and time president the world loot time and within there way through so acid it means that will come into some time with jimmy na ho ki A Time Date and Well So They Can Move Ahead and They Will Get Se Entry Video subscribe to the Video then subscribe to subscribe our Subscribe Quantize and Input Word List for What Means Difficult Entries Patience Click on the Video then subscribe to the Page if you liked The Video then subscribe to the Page I'll Simply Torch Light Rate Over 20 and How We Can Hydrate Words for Using Indexes Rajput Vikram Slightly Track Year So Let's Create a List Using This Word List Lemon Juice Quality Award Set Alarm Just Write Word List New Arm rests on loot sex dipped knowledge used in taxes to operate upon the word limit is loot eye plus point pimples that are juice garlic award list size that decided specific this is not equal to z a that he dominated to now jack was just the word list That dot set a bird whatsapp and the raid 2 the word list for get me doctor se case mintu art that dj in to-do list set lemon juice create set in to-do list set lemon juice create set in to-do list set lemon juice create set for strength and toilet in the duplicate list play list new fasted for a day Cigarettes at Least Possible Because It's Political Matters Should Board Political Matters Should Board That Contract or Money Videsh Vihar Plants Limit Possible Covered By If Elements in Arvind Set E Want Lemon Juice Create Available On County Camps for String Word to Word List Shifting Loot Board Don Here A Loot Only Vote List Contents 0 Word Was That Three Do Plessis That Contents Award Dam Midwinter Ignore That Otherwise Will Art Updater Account Variable And Will Update Account Variable What Length Plus One Dead To 8 Plus One For The Answer Please Don't Account From It's A Prem Mishra With Loot Looks Chord Animesh Amazed That Akshay Date Portfolio Time Complexity Updates Approach The Time Complexity Dubai Limited By 20 For Second Fully To And Off And Square And Time For The Number Of String Seventh Haar Hai The Sun-God SPS Complexity Space The Sun-God SPS Complexity Space The Sun-God SPS Complexity Space Complexity Video Fear of N Gautam Marks Doob Set Contain Contents Order of Elements and Went Against Phone Number of Elements in Not Important Thanks for Watching Video Pooja Bhatt
Short Encoding of Words
find-eventual-safe-states
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not including) the next `'#'` character is equal to `words[i]`. Given an array of `words`, return _the **length of the shortest reference string**_ `s` _possible of any **valid encoding** of_ `words`_._ **Example 1:** **Input:** words = \[ "time ", "me ", "bell "\] **Output:** 10 **Explanation:** A valid encoding would be s = ` "time#bell# " and indices = [0, 2, 5`\]. words\[0\] = "time ", the substring of s starting from indices\[0\] = 0 to the next '#' is underlined in "time#bell# " words\[1\] = "me ", the substring of s starting from indices\[1\] = 2 to the next '#' is underlined in "time#bell# " words\[2\] = "bell ", the substring of s starting from indices\[2\] = 5 to the next '#' is underlined in "time#bell\# " **Example 2:** **Input:** words = \[ "t "\] **Output:** 2 **Explanation:** A valid encoding would be s = "t# " and indices = \[0\]. **Constraints:** * `1 <= words.length <= 2000` * `1 <= words[i].length <= 7` * `words[i]` consists of only lowercase letters.
null
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
null
2
another day another problem so let's Solve IT hello beautiful people I hope you are all doing well the last time I posted a solution to this problem the sound was so bad so I decided to re-upload it with a better sound and re-upload it with a better sound and re-upload it with a better sound and better explanations and joy so in this video I will show you how to solve the problem add few numbers let's get started by reading the problem after that start solving it so I are given two non-empty like let's representing two non-empty like let's representing two non-empty like let's representing two non-negative integers the digits are non-negative integers the digits are non-negative integers the digits are stored in reverse order and each of their nodes contain a single digits add the two numbers and return the sum as a linked list you may assume the two numbers do not contain any latent zero except the number zero itself after reading the problem we can get the information we need to solve the problem from the details given in the problem description the first thing is that we can have two non empty linked lists or the linked list is representing non-negative integers the last piece of non-negative integers the last piece of non-negative integers the last piece of information is the most important thing the digits are stored in reverse order so we can use this last piece of information to our advantage because it can help us work with the curry that we need when adding two integers together so to solve this problem we need to set up three variables the first will hold the curry over from step to step the second will be a liquid list that represents the final result and the third will be our pointer that we will use to move to the next node at each iteration since both variables share the same object reference and pointer updates immediately affect outcome you may need to remember how python handle shared references and after that we'll iterate throughout the first and second blanket list until there are no more nodes and no more units to carry over then we must get the digits from each node because we must additionally handle scenarios when the nodes value is known as the linked list may have different sizes or even reach the end of world places but still carry over a unit as then we sum up the two numbers plus the curry then we need to calculate the next digit of the solution by taking the model between the sum and number 10. for example if we have 17 we will take the number seven so and the one going to be the curry so update the curry by performing a floor division between the sum and the number 10 then we save the result to the pointer which will also update the result as these two variables are sharing the same object and shift the pointer to the next node and we update the tool anchored list to start at the next node but if there is no notes in the next we just give it the non-values finally we return the result non-values finally we return the result non-values finally we return the result next because at the start we initialize the linked list with a dummy not that's equal to zero so for the time complexity is going to be off Max M and N where m is the link at less 1 and N is the second linked list and we iterate throughout the one that has more node for the space complexity it's going to be also of Max M and N because we are storing our result in a new linked list which is considered an auxiliary data structure thanks for watching see you in the next video
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,356
Hello hello friends today in this video and destroys all the problems from the weekly contest pandit yaavun adhura contact for this problem definition of video all problems because solid in the contest which stopped midway today so let's start the forest officer shot dead in tears are number one developed The Amazing How To Find Out On Thursday Standing Order Of The Number To The Number Check Number Give Most Use Of In Bed Function Is Called The End Split And Spot Video Malik Schezwan Sauce Maker Map For Which Element You Use Is To 2.5 Number Of Birth Element You Use Is To 2.5 Number Of Birth Element You Use Is To 2.5 Number Of Birth So Now Don't Forget To Subscribe Screen And Subscribe And The Number Subscribe To The Page If You Liked The App That Indra Patti Wrap In That Think What Will U Will Make A Reply Letter To The Editor Of The Particular Order With Native With Subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page Start This Hair Oil The Second Jobs Apply Discount Everyday And Orders Will Just Give In More Discount Supermarket System In Which Every Day Through Customer This subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to The Amazing spider-man Fact Should Observe How To Make Up Dance Simple Sea Tiffin Festival Function Which Will Give You A Number Of What Is Mean That After Which Number subscribe The Channel Please subscribe and subscribe the Video then subscribe to The Amazing Vridha How Much Time Does Water Portal Item Mother And The Total Price Sunn Dhan You Can Find Every Person The Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe to the state can stop all state which cannot release that point in counter-insurgency release that point in counter-insurgency release that point in counter-insurgency normal subscribe The Channel subscribe and subscribe this All there is to subscribe our ki show ki aaj cancel due Toe Large Hai 140 Color Ki Film The President Security Points Barf Se 0.5 Subscribe Kar Do Se 0.5 Subscribe Kar Do Se 0.5 Subscribe Kar Do MP3 Pimps E Want Who Defied This Point Moving From Left To Right Choice Effective 1751 subscribe this Video Please subscribe And subscribe The Amazing This Point I Total Subscribe To Ka Development you object in the self-controlled account statement for self-controlled account statement for self-controlled account statement for three days before subset seen from effect one in the starting point s to edit 12314 diff president starting handsfree 3.95 diff president starting handsfree 3.95 diff president starting handsfree 3.95 why this point to the second position name critical issue just flip a travel agency in a studio Noida and Yamuna Ji Point Duck Tales Appoint Have All the Three Idiot 127 Benefits Point No Evidence Against a Good Buy Subscribe Now in Which of This at This Point All Subscribe and Use This Will Be Coming a Positive Step in the Bullet 350 500 Dash Loot Mike Tyson Vs The Surplus ₹3000 Loot Mike Tyson Vs The Surplus ₹3000 Loot Mike Tyson Vs The Surplus ₹3000 Anil Deposit Winters Co Family By Big Boss Vodafone Tower At Most Runs From Left To Right So It's Just Moving Over 240 2.0 Movie Income Tax Raids And Id 240 2.0 Movie Income Tax Raids And Id 240 2.0 Movie Income Tax Raids And Id Admission Notification For The Benefit Of All Subscribe Button More Flash Light On This is the meaning of this ABC that I need electric ok dam water Maithili Senior is this phase 02009 this point to take medicine total length - no what do we call the na religion loot machi the injustice chatting delete records for office collection loss system of angels will Bless Both Eyes Reflect Too Amazon Not Completed It's Something Is Safe What Do You Make Me Write The Name Of The 100 Solid And Liquid Liner Wash And Shingles And Avoid Your Energy And Whenever Fun Stops Admission At This Point You Install A B C And Witnesses And Will Cause It's Quite Amazing To Subscribe To R Records They've Lost All Its Positions Having A B C The Thing Which Is A Tragic Incident In Example This Way When The BBC Took DC Subscribe Like This Point To Point Ko This Point Subscribe And subscribe the that there is no exact neck point in a dress one this point to all festival is formed at something consisting of all subs but are equal to one inexact point to do something in the storm district cut middle east and west continue in the state are also Have instructed me to point to the left right hand side Next question for which it is a point to point for example of luck for yours which is you and problem exam list meeting at all the way delivery pick up and telling you how to Play Find the Total Number of Different Sequences and Points Yorkers Dowry Pain Due to Make Different Orders The Pick Up Delivery Video then subscribe to the Page if you liked The Video then subscribe to the Page That Aaj Se 15 Min Option A Toe of Motivation In The Soil Water And Boys Ka Seven Videos For Kids Have Always 9 When You Add This Type Of Functions 2.1 Incomplete Subscribe Destroyed During A Function Of Multiplication And Will Not Distract Problems Subscribe To Have So What Is Volume Decide You Have A I Myself 30 And day improve n order in the middle of a ho remember this to end short summary turn on nfc i own basic short but 3600 pickup and the city one delivery jcb this pickup in this country pickup ok n shampoo contract points 172 The soldiers can sleep by making candy today can speak notification ific option for delivery - 2 ki aapke notification tips hair pack f9 after two of my sun positions for the delivery half of the fuel surcharge acid factory - 302 ki and more i watch your shows like bishop dewan * i watch your shows like bishop dewan * i watch your shows like bishop dewan * Election 2014 and its intelligence agency * and its intelligence agency * and its intelligence agency * I am one minus two students - 12327 Every I am one minus two students - 12327 Every I am one minus two students - 12327 Every Point Dravya subscribe to the Video then subscribe to the Page if you liked The Video then that Shoaib Scooter is Problem This Flag Final Transport Point This Channel Subscribe Must Subscribe करे if you liked The Video then subscribe to the Page if you liked The Video then 121 Miles 112 Students and Systematic Particular Answer Multiplication and Use This is equal to take off the students of logic and order problems as commission Adheen recording android app
Sort Integers by The Number of 1 Bits
minimum-number-of-moves-to-make-palindrome
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr = \[0,1,2,3,4,5,6,7,8\] **Output:** \[0,1,2,4,8,3,5,6,7\] **Explantion:** \[0\] is the only integer with 0 bits. \[1,2,4,8\] all have 1 bit. \[3,5,6\] have 2 bits. \[7\] has 3 bits. The sorted array by bits is \[0,1,2,4,8,3,5,6,7\] **Example 2:** **Input:** arr = \[1024,512,256,128,64,32,16,8,4,2,1\] **Output:** \[1,2,4,8,16,32,64,128,256,512,1024\] **Explantion:** All integers have 1 bit in the binary representation, you should just sort them in ascending order. **Constraints:** * `1 <= arr.length <= 500` * `0 <= arr[i] <= 104`
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Two Pointers,String,Greedy,Binary Indexed Tree
Hard
1437
834
Hello hello friends today we are going to discuss liquid problem some of the distance in ok problem main aap kya aapko under secretary Divya Gupta and number from Jio connection sal - number from Jio connection sal - number from Jio connection sal - manager diya ok subscribe our channel for sexual and everywhere. Subscribe to the channel and subscribe as many times as you can, like the distance is 02111 inches, now the distance between George and Subscribe and subscribe I entered or spit out again I completed this trick entered for 1 Then back I did all the tourist attractions and for traversal the best teacher is the best chakli has refill so you can use me anything We can do it, okay, so we have used the edifice here, we are the people, why do we appoint its president here? Okay, so we have made every note, like we have noted its size and all the notes are 2001, so this is the problem. Do something, okay and definitely take out time during this time. The answer is that this is the difference of all your notes. You have taken your distributor and this means stand benefit, you have made the agreement, traveled all the alarms and all his children, if they are the same. If you have a pistol, then you have done it so that you can definitely like it from here. If it is for the entry for the districts at the first level, it is the first year, then you will do OnePlus One and how many 345 for the gym, Colonel Bainsla would have used among himself. If you do, where are you at that time, if there is a broom, then FIR against it means, in this, you turn on the cross mode on the base side, select the trend and time limit coming from the office, what all of you have to do here is this. Now scooter like this before now or I remove it that okay whose addiction you saw that you can have sex every day okay this I cut this is love that if you note any particular then it is okay by taking an example If you have to remove it with the notes, then what will you do? Well, if you believe that there is no train above the note, you can do the same without any structure and there is so much anti-oxidant sitting there, then anti-oxidant sitting there, then anti-oxidant sitting there, then how will you remove the notification color? And believe that all its children will be its children A Three Four Five, their time will be answered for me, okay, till then, what about the children of 345, so what has become of my answer, how much has your lachki lasted, the criminal distance, then what has become of us, okay? If there are so many things, we will see that according to you, it is okay and now if you see these three arthritis, now zero, how should I go, SIM, I do n't want to see us above, just search for juice, my relative, Sunidhi, then for zero, its ego and above are few days. Someone, if you are above, then you have considered the upper toe, how could the object be below modern, isn't it better? Now if the tigers will come, then you will do this zero, let's celebrate his birthday, the whole process is going on in this, so see the answer for zero, yes sir. What is happening, what is the distance from 102, that is okay, what is the distance from 345 of the creatures, two plus two tier, so I for 10, if you withdraw so much money, then for this separately, J7 plus one is equal to two plus one. You can subscribe this channel for just Rs 4000, if you are okay with doing so much and this number two, you subscribe, dip it for 80 sacrifices, give me how the pimples are coming, then if this third and Gulhad, how much is it between 90 number two. That's why this world is not ours, how much strength is the distance between Ajmer and 110 012, between all the subjects of sorrow to you, from all the chapter notes from one note to the other, are we for them, this is the number zero for them, how much will the distance of zero go? You will put the lineage like 2% distance and go? You will put the lineage like 2% distance and go? You will put the lineage like 2% distance and how far will you be from zero, if you have only one spread one distance regarding zero, then the distance that the people of the states or one plus one activists had from your face will be Lakshman, you will get from zero to yours. There will be a distance between the faces, okay, so how much distance is the distance of the Trishul G-20 from okay, so how much distance is the distance of the Trishul G-20 from okay, so how much distance is the distance of the Trishul G-20 from you, 4.205, and also, by doing this, 4.205, and also, by doing this, 4.205, and also, by doing this, what will you get, this means, you will get the answer of its children, okay. And what is the difference between zero and 272 Mr. Related Articles A simple thing, you have kept the answer side for you in your friend, you have added all the notes of unbroken number of two, why did you leave the replace because see two. All the children's days of all of you, the distance to which I have already updated, okay, I have already updated, if you convert them into children's, then our distance will come to them, right? Remedies one excellent prediction three four five six seven eight and donated for and we have already added Swift in the Indian cricket team just for you, so what are we doing? We are shedding tears for zero. So for the districts, take out the raw in respect of five sets, it is okay and for you, number-1 of 12345 is already ready, and for you, number-1 of 12345 is already ready, and for you, number-1 of 12345 is already ready, so here we have given one for 350, in the middle of 1012, you have made this world, so what should we do? -Kya you have made this world, so what should we do? -Kya you have made this world, so what should we do? -Kya three plus famous plus four three plus prev acid hai three iska answer with respect to do a free slideshow with respect robert to and jo phone hai iske account of the software chapter note in defiance done ok this jo this answer with respect Toe to 4 this account of notes subscribe if you this against Forest Act 2009 if you can take it out for any note if on any okay then if you from this and which is children its gh A plus account of the account of most in this app child, then you can write like this if it is okay to download from you, here we have discussed what is above, which is what we discuss in the empty subri. Okay, whoever talked to me about the particular situation, colleague Shahzada has liked it. Now see the importance of the biggest one, start moving from the bottom. Okay, I am going to tell you that our Tubelight will increase, that it will grow the account and those on the side. She must have spread by noting and answer with respect to particular and particular node is in quality. Now what I am talking about is that we now call it in half as much space as the woman's 30. Click on continue on the double whole face of its Supreme Court. Have these 4K lines and Africa is marked One is six chapter account One is fine Similarly because how much is FD account Thrill 12323 Lucky in life How many in Morena district How many Africa Tata In the city of white districts Note is astonished That is 12345 70's leave Experiment Or now we can try to write the answer but I am okay, below the methods in the report, I am talking about some great download action, right now I am on any torn note, so I am talking about the download action with this. Okay, now as it is dependent here, so put this as much as it is, what his wife does above, then Reliance's Jio is zero, this is nothing about flowers, so this is zero, if this is nothing, then this will go to zero. There is nothing in the chest. 20. Okay. If whatever node is in, what will be the answer? Okay, let's move ahead. Now you are up. Okay, you can come tomorrow. And what is the distance from Thukral? What is the distance from One to Cash? Have one I set this over and over again I just have any note of her I'm looking at that puree under it Why don't you give up on 0134 It's all her other so far It's all but his wife download less than home one After talking about it, we will put it later, okay, if on the side the tattoo of classical, the breath of medical experts, your gun, the beginning will be one person or not two, now we could have written it from back, we know what you could have written it like this, see this relative like this My a, this is my children's account of 525. 145 Babu, how much is it from the superintendent from whom I have done Zero Planets, Amrit Vriddhi, okay, you have been removed from here, Simdega and the trainer Yayavar have been removed, okay, now we also go to Seven. 75 How from the government? You will find out that the children who have fought on the declared one are three and how much should I find from the last one, okay, Aditya, what is the next child, okay, how much is his price, free and how much is his answer, so what will be the answer, it is tons and tons. Okay, okay, I am repeating the same thing again and again. Like a bookish person, we are repeating the same thing again and again. What is the thing that we repeat again and again that any particular note, if you explain, then he has the answer at home, your children's bike, then for this. Like his download children, come out from there in the report, here on his service, some children brother and dust numbers, not any specific hunter brother, keep adding, okay here, the work is going on as an example, you can see that if you were taking it out here, then eight What effect was zero having in the forest area? Three plus two is the account of victory for children. All these are dear fans. Respective virginity test from here in cricket. Strange Batu Caves taken out in the plate. In the chapter of Udaipur, a chapter is called and the answer of two is how much tunic and judge. If you have sex against, what is it you have to download in action and mean download nipr 15 minutes I thing here you believe that from where this incident of Jio has got the money if you strengthen the note you will come out from here note number of districts Remove the uterus, wake up 100, where will the tan be done and take out this technique medicine on the strange thing, 2462 phase distance to take a distance 2017 tension one and them distance one to two and your 1000's stop at the not gate only, in the report then you cancer and this from the whole That if you are in zero, then you have to go down, then you have to go somewhere, this is from zero, push it up, find someone from zero, there is a track on them too, if not, then it is time to go to zero, then welcome to 1968, now this is the answer of the cricketers. This is our channel, this is our channel, because if we take it out in this way, then our technical officer will understand what we have to do, okay, so now such things, what is yours for yours, which can be known in the download action for yours. So you already know, right? Direction transfer, you already know, okay, tu ki root traction, where from the book, the decision to form soon, the distance of the distic is on the answer for you, how much to draw, this is this, which is zero to three, the answer to this is this. Reached the report, removed chilli 200, take these three and then this paste, it is okay that you subscribe to the to-do list and if you subscribe anyone, now this thing has to be removed and the appointment of this disgusting Meghnad was account options Reliance Industries loot. In this and how many children in this, tell me from there in 1972 and 1977, if you turn it towards - then you are please subscribed, then what is this, how do you extract hard work from us, subscribe, then this has to be subscribed, first subscribe, please channel cash. Withdrawal of cash to the tourist from here, so we will have to do this answer - right, you just take the - right, you just take the report of the one who is our note and the one who is my friend, we have got ourselves a consideration night, if you must do it here. If you are doing it from here then the distance of your two is totally different 2.5 feet from here is here then the distance of your two is totally different 2.5 feet from here is here then the distance of your two is totally different 2.5 feet from here is 282 but in the districts, is the forest kept in zero at this time as per the farmer's three plus 2 and ₹2 answer base plate, then you will ₹2 answer base plate, then you will ₹2 answer base plate, then you will have to do it from here - right? So you will have to do three plus two have to do it from here - right? So you will have to do three plus two have to do it from here - right? So you will have to do three plus two from here - because see, from here - because see, from here - because see, breast cancer is in zero, so if you do this from here - - SIM Laga Amit Thriller Two, you will have to do this - this from here - - SIM Laga Amit Thriller Two, you will have to do this - this from here - - SIM Laga Amit Thriller Two, you will have to do this - then your a zero will be made carefully in the farmer, there were 80 plus. Hour 8 - 5th Image Kitna Bacha Not To Mirzapur To K 8 - 5th Image Kitna Bacha Not To Mirzapur To K 8 - 5th Image Kitna Bacha Not To Mirzapur To K Here Se Kitna Aana Laa Hai Tu A Plus Sexual Saliva 11:00 K City Ko Shop On 211 Sexual Saliva 11:00 K City Ko Shop On 211 Sexual Saliva 11:00 K City Ko Shop On 211 Subscribe How Will It Come Okay Here By Verification On The Table Can Come Subscribe 12123 Can 1234 okay and subscribe now two three subscribe 169 in this way and then see this is all do here first of all what will you do half transmission why will reverse child content answer with respect to child okay child will ask on dance service okay See here, the authorized appointment committee will do it, in which it is okay. Whatever means I will tell you whatever is hidden, it is only through the code that you will get the foreigners' reaction. The get the foreigners' reaction. The first one is about the speed of youth, children and writers and okay then don't worry about this, I am here, we write for our career okay this player episode 569 caravan 0 account is one and how much is zero from us okay so here But it is okay for us to do this thing, the reaction you called will give the biggest benefit that if you are asking for intestine for pimples, then half of all the children here have cross 409 treatment, this message was written that not cycle for cycle but that I am If it saves you from getting cycle for, then thank you, that account statement will do the rights of the specified, you will stop child on the answer option that we were doing for a particular note, what was the answer to it, stop child on the answer channel in Krishna Paksha. C See what was there here which we had written from dress us so first of all dip in it stops method is different from ram of 143 zero is allotted for four one is the answer account for 045 from this time zero is ok so How much fun will it take for two? Friends, if the plus account statement is fine, then what are you pimp's children? Now the answer to all these is 2000 servi and plus account statement of 1234, how much dot reel is fine, then this. The entire channel for the hatred account, subscribe and share and subscribe, MP Azhar is for Gautam Buddha, I have written this thing here, you will definitely get it on the copy, then it is very good, find the account source code to you, I have written this record of children in juice. We will do it, okay, do you have any note? How many children have you got in cricket? Do an account of his children. There will be children from two districts. Compete well with him. How many children do I have in zero? Today I work for Chintu, then I feel like having children. Okay, one and plus, how many Buddha buffaloes will he take, how many will he want in the districts, six, so this is the answer to this, now what happened is that we have decorated ours through download action, okay, like you can download and install it from here. Collected what happened to you production airport this frill we you have to select your for this us this for this what are you going to do for this experts 712 cricket reviewer parents this you will do you person cycle for during this time only cigarette on the channel what Will you see the answer Child is already ready for the studio Tubelight Step Plus What will you do Answer of advance Who was the majority 0 Answers of Parental You are right Asaf Khan has taken the size What is the size Apne Debit Total Number of Notes Play Store Keep this yours Size apne code number portal note hai end size - account of child karoge ok end size - account of child karoge ok end size - account of child karoge ok - account chahiye size k tube lights - account chahiye size k tube lights - account chahiye size k tube lights 57 - used to do apne ka child account 57 - used to do apne ka child account 57 - used to do apne ka child account so I total number of children industry now zero exploring two to two cash surplus is there Text me, how many children will there be in that? Children of shoes and slippers of previously arrested people - shoes and slippers of previously arrested people - shoes and slippers of previously arrested people - do it. How many districts do you want in the dreams? The minister took the same size - move to Africa. Scandal - do minister took the same size - move to Africa. Scandal - do minister took the same size - move to Africa. Scandal - do this thing here. Size - this thing here. Size - this thing here. Size - Countess's children. This Do 2 - - Answer site - Countess's children. This Do 2 - - Answer site - Countess's children. This Do 2 - - Answer site - Aa Shukra - After conduct child This thing Shukra - After conduct child This thing Shukra - After conduct child This thing was given to us - 3 This is what you have written This is what you have was given to us - 3 This is what you have written This is what you have was given to us - 3 This is what you have written This thing is visible behind Should - written This thing is visible behind Should - written This thing is visible behind Should - Hee - To mistake is - Ri - 2 - Treatment Hee - To mistake is - Ri - 2 - Treatment Hee - To mistake is - Ri - 2 - Treatment because In the answer of creatures in zero, Mitthu's lesson was also considered, what happened to it, how was zero made from five, the answer of one was made from ki and it was definitely time to comment on cancer, but you already know this chapter note from the shop. Well, where is the secretary below, I already know brother, that's why in the answer which is zero in it because of the audition of Zone-2 - If you have to do it answer which is zero in it because of the audition of Zone-2 - If you have to do it answer which is zero in it because of the audition of Zone-2 - If you have to do it and what happens because of any notification, hit the account of account for children in the third. And the answer is not a particular one, then you mash it, peel the answer of Children Against will be given importance, where do you belong from and make it difficult, okay piece and it has its own complexity which is not difficult, whereas the plus seat is o Seat to O seat, you have this footage of complexity in it, what is going to happen over places and this is the difficult war of plus, so keeping this example Mataram, so keeping all your tips Paswan Shankar, then you understand this problem, you have extra problem, aspirations position, both. I am coming first and tweeted that if we have any doubt regarding this or that type of problem, then you can ask it in the comment section, I will try to tell you this easily. End placement for you guys. Bringing the officer in easy language My boy my forget If you liked me then please like this video Subscribe to the channel Share it with friends of Saathiya If there are any of my services then take very light care of you Topics If you want a video then you Please do let me know friends after watching this video thank you see you soon in the next video plane take care by thank you friends
Sum of Distances in Tree
ambiguous-coordinates
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
String,Backtracking
Medium
null
1,047
Hello everyone welcome back to my channel we are going to discuss the health problem the problem in Digit June challenge is remover of all ads in duplicate infection so what to do in this problem let us find extra in it Rakhe Singh latest and if anyone like us There is more here and till then, let's see how it is meant to be. Okay, so first of all, the wife is the same, so if we remove her, what will be left, if we go to TVpur, that is, if it is removed from here, then here is a This method is fine, we will get out of it after that, but this is fine with us, so we will remove them, so our answer should be done, so if we take this echo, then this will be the difference in our last one, okay, so let's see how we will approach this problem. To solve this problem, let Meghnad do an interview. Okay, 2.8 Yadav, you Okay, 2.8 Yadav, you Okay, 2.8 Yadav, you can use it. Okay, I will tell you the 2.5 approach can use it. Okay, I will tell you the 2.5 approach can use it. Okay, I will tell you the 2.5 approach and we will do it with tax. Okay, this is also our input. Eid directly, okay. Well, first of all, we will take one that will start and we will take A. Okay, now here we will compare whether what is on I, what is on ID, is it medium here, otherwise we will move forward, okay, so our which is That Maharaja here and here see here this gives us this meaning then we will take this and whatever else we will use which is a CA so we will make this will be our PK and I point then that is ours The current that comes here will go to the one behind, that is, which space, then again a loop will go here, it will always come on I plus one, okay, Yoga will always be on Peterson, so this is how we will compare. And the team process will be repeated. Okay, so this was our two point one. If you want an angle, then tell me in the comment section, I will also share the link of the crackers. I had also done the angle for the officers, it is much easier than this, so see that. Let's take it, by the way, this is easy but tech wali was going like this is so in the chart, what will we do for this, we need an approach, what should we do, we have taken a chat, okay, this is Ishq ko support review. So, we will start from here, we will get our points, we will run one, okay till the rank of the pin, we will add the first element which comes on it, okay, earlier it was Champion, before adding this, neither Champcash nor When the temple is there, the statue of ours is against us, then we just do n't want to do anything, so you can ask simply, what should I do, just ask, okay, so I asked one thing, after this, come ahead of us, come here, whatever is there now, We will check whether this element is not equal to the top of the style, if not then we can also put this from B.Tech. Okay, so this was the first one, when the from B.Tech. Okay, so this was the first one, when the from B.Tech. Okay, so this was the first one, when the check is MT then ask and if the peaks are SFI. It is not equal from the top of our tank, it is okay that if not total, then you can have freedom, there is no doubt about that, okay, then after that, I will move ahead, now we have to see here from ours, maybe he gave another big topic. So what do we have to do, so we have to do this from here, are you okay, that is, when we are coming towards cleaning, okay, then what will we do is the photo, because that element has to be removed, right, remove this also. Years will pass, so from here, when I and my brother move ahead on this photo, whatever is there, now we should keep in mind that it is white and if you tap on the top, we will turn on this condition, so this is our treatment. And the CO will go, now the step is the interior and when the tech is MT, and Saif Ali, what can he do wrong, can he do something, then C will ask and then we will go, whatever is here, now we need a tractor top and not another one. If it is, then we will come in the second condition and if we do that, then it will ask that what will we do after that, chicken, we will test me, we will top me, we have done all the spring travels, if we will pop, then I will earn money or will we hit this heavy vomit on the seats, Singh Arya. Look, it should be for six days because it is Tuesday so she is vomiting, so in the end we will make it a day once or if we make it a day then our CBI has just set these three conditions for the day, it is very simple. That if it is a star camp then push the selfie, there will be no problem, if the current Singh element and drop style top is not called then we can do something and if it is opened then we will have to crop it. Okay, so if you are using point approach. If you need a code, I will do that also. The approach with Share button was a little, so I did it on this one. Let's take a look once. Take the approach and look at the ACP record. The flame of the pattern I have shared in the description. Given this is confirmed, so first of all, we have taken black by typing the character because our stuffing is a character. Okay, after that, what we have to do is take one answer lion in it and after typing the answers toe, we have written on each character. City character go to Pinky and Star if this is our first condition in the first condition what is the cast at MTV so here four of four is seven four zero means there is an exception so do something okay if whatever in ID testing if that set Do toxic waste, then tomorrow I will have the form, which are my heartbeat tips, if not, then I will ask here, okay, this is the loop of runs, after that we will have our answer, the butter in the set will be upside down, which means it is okay. So what we will do is, first you will grow whatever you want, till the time we typed, it would come in the soil and people will put it in the answer sign and then two okay and in the last we will reverse the answer symbol like what we had here, we till from the chart. When I popped it, your butt was becoming like this, if it should come, then what did we do, we forced it, how to reverse it, we will return the answer and after submitting this to ours, we will see if it is accepted, so come, I liked the video of the ghost. If you liked the video please like and subscribe the channel and message me for the next video.
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
967
everybody welcome to my channel let's solve the problem numbers with same consecutive difference so in this problem it is given as a n which is like represent the number of digit in our number and k is represent like every pair of consecutive digits in our number should have absolute difference k and also the number should not be contain any leading digit 0. so here for n equal to 3 and k equal to 7. so for all possible numbers which has length 3 so these are the 5 numbers which satisfy this absolute difference between any two pair of consecutive number is 7 how see 1 8 has a difference 7 8 1 has absolute difference 7 similarly 2 9 has 7 and 9 2 seven here we have 7 0 7 which is satisfying the one but we don't have 0 7 0 because 0 7 0 is valid but it is invalid because it is has a leading zero so we should not return this in the result so let us understand how we will solve this problem let us say if we have n one so for all the digit possible digit we have for n equal to 1 0 1 up to 9 so this doesn't matter whatever k this has the absolute difference any k is k so we can say that if n is 1 this is the answer but if n is not 1 in case let us say n equal to 2 and k equals to 1 how we will solve so first we will start so all the leading digit possible leading digit are from 1 to 9 then we will build based step by step go depth and build the number based on this k so first let's say we initialize our number let's exam for example from any first digit one then b will have two options we can go one zero and we can go 1 2 so if we see here this absolute difference between these two digit is 1 satisfying the property so how we will go these two direction so for going we will check first the digit last digit basically the last digit of our number so far so the last digit of num y using the modulo in the tan so num modulo 10 this is our last digit then we will check if we add k in our last digit plus k it should be in a single digit number like belongs 0 to 9 it only so we will check it should be less than 10 so if it is then our next number will become so the next num will become the number then we will multiply by number by 10 so that we can accommodate this new digit plus the last digit plus k similarly for this side we will take the so last digit is same but another possible case is if last digit minus k greater than equal to 0 which means this is also possible so we can take this as well so the next our another next digit next number will be num into 10 plus last digit minus k but there is also one more condition we need to take care if k is 0 in that case this last digit minus k as well as last digit plus k both are same it doesn't matter so we will put another condition check here k should be in so that in case of k 0 we should use only one number so this is how we will go through so let us understand for another digit so if we start from let us say 5 and we are building n equal to 3 and the difference absolute difference is let's say k is 4 so in case of this let's say first we pick the 5 so in case of 5 we will go to the 5 plus 4 which is 5 minus 4 let's say so this will become 5 minus 4 which will be 1 similarly this side this will be 5 and 9 then we will go further one more down we can have another option five one but if we do minus k we cannot do because the large is one minus nine it go negative so we can take only this option five and 5 and similarly from here we can take 5 9 so the absolute difference should be 4 so 9 minus 5 is 5 and we can go the further right so this is the case another case let's take another example for n equal to 3 and k equals to 2 so in that case let's we started from 3 so we can go to 3 and then one similarly from here we can go to three five from here we can go three one and three again only because the negative the other case will be negative so we will not here we can go three five three or three five seven so these are the three possible number which is starting from the d three and length three and that is has the absolute difference between the consecutive numbers is 2. so this is the way we can solve so how we will write the code so this is very simple dfs recursive code we will write so first we will start for all the digit from i equals to let's say or num is equal to 1 to 9 then we will call the dfs method and every time when we call dfs we will pass the i as in like we will reduce the num because we already initialize this one and then i passes her i and the k for the checking the conditions and the list that list will store all the numbers that we have to return the answer once we run how we will write the dfs so for dfs here we will check in dfs first base condition is this if n becomes equals to 0 which means we exacerate the length in that case we will add this number so this is let it call num so we will add this num in our list so list is let's say the result dot add the num and from once we reach this we will return from here otherwise we will check these two cases as this like this one and this one so here is a code i have written over here so this is the base case when n equal to 1 we will return the answer as all those digits 0 to 9 otherwise we will create a result set reference object which will be pass into the dfs call here and we are looping the dfs call for all the digit from 1 to 9 then in this dfs method we are checking the base case if n equals 0 which means the termination condition we will add that number in our result and return from here otherwise we will get the tail digit and this we will compare this tail digit plus k if it is less than 10 we will add this and another condition if tail digit minus k greater than equal to 0 and this one more condition we need to add here which is k greater than 0 as discussed because uh to avoid the case when k equals to 0 the duplicate case so the tail digit plus k and minus will be same if k is 10 so we will add another condition and with this and this will call recursively so here is i added this condition k equals to 10 and if we submit this code this will be accepted so what is the time complexity of this solution so every time we have two choices and for each number we are running an n length number we have two choices so the we can have 2 k power n recursive calls n minus one recursive call like first we are choosing and here it is a nine digit for nine digit we are running so this is our time complexity so it's roughly we can say and to the power and time complexity so that's it if you like my solution press the like button and subscribe to my channel thanks for watching
Numbers With Same Consecutive Differences
minimum-falling-path-sum
Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**. Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed. **Example 1:** **Input:** n = 3, k = 7 **Output:** \[181,292,707,818,929\] **Explanation:** Note that 070 is not a valid number, because it has leading zeroes. **Example 2:** **Input:** n = 2, k = 1 **Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\] **Constraints:** * `2 <= n <= 9` * `0 <= k <= 9`
null
Array,Dynamic Programming,Matrix
Medium
1224
64
hello and welcome today we are doing a question from lee code called minimum path sum it is a medium let's get right into it so given a m by n grid filled with non-negative numbers find a path with non-negative numbers find a path with non-negative numbers find a path from top left to bottom right which minimizes the sum of all numbers along its path note you can only move either down or right at any point in time so this note is actually going to make the problem so much simpler um and we'll see why in a little bit so example one we have the input grid one three one five one four two one and here we output seven because the minimum path would be one to three to one and any other path that we take would only give us an output greater than seven example two we have grade one two three four five six to visualize this a little bit better we would go from one to three from one to two to three and finally to six giving us an output of 12. and these are just some constraints here so how do we solve this well to see this let's look at example one again here we have the same grid and what's sort of the first thing that comes to mind well we could go through every single path find the minimum and simply return that and if we do that we'll have a total of six parts we would have one three one outputting seven one three five one eleven one three five two one twelve one five one nine one five two one ten and finally one four two one which outputs nine and here we can see that the smallest one was what we output seven but what do we notice here the first thing we notice is that well we always start with one and end with one and that's only because that's what's given right we have to stop from the top left and end at the bottom right so there's sort of only one option one origin and one ending point right but something else the only way we can get to the end we can get to one is either through a one or a two and the only way we can reach a one or a two is through one five or four which in turn can only stem from either a three or a one and this is because we can only move down and to the right that means we can only come from a cell that's to the top of us or to the left this means that if we somehow know the minimum path to get to three and to one well now we have all our options and can branch out to four five one because we have all the origin points to get to those three these are the only two cells that will get us to four five for one but we know that so let's say to get to three we know the minimum path that would just be one plus the cell we're on so four and to get to one this cell over here would be one plus one two now all we have to do is take the minimum of either four or two plus the cell we are on that's the minimum path to either four five or one so let's go ahead and do that well the cell over here the minimum path to get over here would either be from the top or its left and the top doesn't exist so here we can only get to it from the one to the left of us so four plus one it would take five to get to this upper right corner now what's the minimum path to get to this middle cell again we can only come here from either four or two the smallest is two so two plus five is seven the smallest path to get to this middle cell would be seven and for four we can only come here from the top so six so now we have the minimum pads to get to this middle diagonal over here now we can see what's next well if we're looking at the cell over here again either from the top or the left so we know the minimum path to get to the top is five and the minimum for the left is seven either one will lead us to the cell we're on so all we have to do is take the minimum and add the value of our current cell so this would be six and here we would go with the left which is six so six plus two is eight and for this final cell we would just go from the top so six plus one is seven and if we see that is exactly what we output seven so this is exactly how we're gonna solve this we're gonna go through this entire grid top down left to right and as we loop through find the minimum between the top and the left if they exist and add that to the value of our current cell so what we need is the minimum path of either what's on top or the left and once we know that we can now construct the rest of the grid and finally what we would do is return the value in the bottom right so let's go ahead and code all of this up the very first thing we want to do is loop through the entire grid so four row in range blend grid four column in range blend grid zero what do we do now well now we're gonna have three conditions the first one is if we are in this first row because if that's the case we can only get our minimum path for whatever cell we are on by looking to the left and adding what's currently in our cell we can't really look to the top and if we are in this very first column we can only look to the top we don't have anything to the left so in order to address that um if rho equal zero and column not equal to zero and this is because we don't really want to do anything with this first index it's our starting point there's no need to touch that so if we're in this first row and not in this first element then we know grade row column will equal whatever is in there right now plus whatever is to the left of it so grid row column minus one elif column equal to zero and row not equal to zero this means we're in this first column but not in this first top part of the column then grid row column is going to equal whatever's in there right now plus whatever is to the top so grid row minus one column and if none of these are true that means we know we are in index one or onward then all we have to do is make our check right see what's to the top and to the left find that minimum add that to our current cell to get the minimum path of where we are so l if row not equal to zero and a column not equal to zero then we are in index one and on then grid row column plus equals the minimum of what's to the top so row minus one column or grade row column minus one so whatever is in there right now plus the minimum of what's at the top or to the left and once that is done all we have to do is return what's in this very bottom most corner the bottom right most corner so return grid row column and we can just use row and column variables again because after they loop through they are going to actually store two they finished looping through and that's the bottom index we want anyway so return grid row column let's run code accepted and submit and it is accepted as well so talking about space and time complexity over here we loop through the entire grid once so given a m by n grid our time complexity would be o of m times n and for space we are only modifying the input grid that we're given so that's constant space of one if you have any questions at all let me know down below otherwise i'll see you next time
Minimum Path Sum
minimum-path-sum
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\] **Output:** 7 **Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum. **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\]\] **Output:** 12 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `0 <= grid[i][j] <= 100`
null
Array,Dynamic Programming,Matrix
Medium
62,174,741,2067,2192
79
foreign called word search it is a medium let's get right into it given an M by n creative characters board and a string word return true if word exists in the grid a word can be constructed from letters of sequentially adjacent cells where adjacent cells are horizontally or vertically neighboring the same cell may not be used more than once example one we have the following board and we're looking forward a b c e d and we do see a path for that where we are not reusing any words and where we're using adjacent cells horizontally or vertically so no diagonals we see this so we return true example two we want to see the word see which we do and so we return true here as well and example three we have the following board we want to look for a b c d we see a b c but we don't see that fourth B right we only make it as far as three characters and at this cell we want to look for that fourth B that is either horizontally or vertically adjacent we see the one to the left but we've already used that getting 2C and of course we can't reuse anything and no other combination no other path really forms so we output false so we want to code up an actual word search how do we do that well like always let's first take a look at an example say I have the following board and this is the word that I am looking for now in a real word search sometimes when you're looking at the board you can right away see the word but if that doesn't always work you know there is a formulaic way to actually solve real word searches right you want to scan through your entire board looking for that first letter in your word say you find it well now you want to check all around yourself for that second letter and in a real word search obviously you can also use diagonals but here we want to just use horizontal or vertically neighboring it's also just left right top bottom so in this case for example I see my first letter well now I want to check all my sides and if there are multiple choices for my second letter I see that second letter present in more than one cell I'm going to arbitrarily pick one cell and see if I can continue forming my word say I start from this middle cell right here now I move on to my right well I now want to perform the same search again I want to check top bottom left and right looking for my third letter and I can't actually reuse any of the letters that I have already been on so I'm going to go ahead and sort of nuke these out make them empty just so we can keep track of what we've already seen so we've seen the first letter the second letter and now I want to look for my third letter either at the top bottom left or right and I want to see if it actually matches the letter that I'm looking for well in this example if I look on my right it is out of bounds if I look on top it's not matching the letter I want same with bottom and the same with left it the letter does not match the one I'm looking for and that is because we purposely changed it to make sure we can't reuse it so if we run into the set end that means we actually haven't found our forward this means that the choice we picked was right so what we're going to do is bring this back to what it was before we picked this letter and instead pick another one from some of our other options so obviously we can't use the first one we started with so that's going to stay blanked out and now we can potentially search on the top or left so we go left well now first thing I'm going to do is make sure I can't reuse it and now I want to look for my third letter here I do see it is that b and I have found it so if I do find it I return true if I don't I would return false say I hadn't actually seen it this was also c um in which case I would again go back reset my board we're pretending this is C and go back into my first letter now a check on the top because that second letter is here and say even here I don't find whatever it is that I'm looking for my b so I'm going to reset this again and just try to find that first letter again so reset my board to the original and look for that first letter again that first a so now that I find my first date I'm going to do the same thing repeating that formula Now searching for my second then my third all the way down if I don't find it then I backtrack and try again in a different location if I go through the entire board not being able to find my letter then I return false if at any point I do find the word then I stop searching exit and return true so that's all there is to the word search now let's go ahead and code it up and then use our code to actually perform a word search all right the first thing that I want to do is look for that first letter in my board so for that I'm going to iterate through my entire board and I want to go through all my rows and columns so how many rows and columns are in the board if so rows and columns are length of the board and length board at index 0. so that first row how many columns does it have and I'm going to be looping through so for Row in range rows in the range of the number of rows I have and say with column for column and arrange columns I want to check every single cell so a word of row column so whatever index I am on we start off with 0 so that first cell if this equals that first character in my word so word of neck zero so if these are equal then I want to check for the remaining letters so we want to go down and it's called a depth first search so we want to go all the way down looking for our remain words and I'm actually going to make a helper function to do this so I'm going to call this DFS and what is this going to take in I want to pass in my board because we're going to be changing our board based on how many letters we found I want to pass in what my word is um what index I am on in the cell so my row and column and finally what index of the word I'm looking for so index how this helper function is going to work we're going to be calling this over and over searching top bottom left right and each time we're going to be passing in an incremented index number so we're always going to be looking for that next to letter and we're going to be making four checks so you know row plus one row minus one call plus one column minus one and as soon as we find the word we're going to be returning true so if we do return true so if self.dfs of forward word row column and self.dfs of forward word row column and self.dfs of forward word row column and that person next we start with is zero so if this is true then I return true and these are two if conditions we can sort of merge these together so if I find that first letter and I find my entire words when the end of this entire depth first search we return true I will return true I have found my word if not I continue going back into my for Loop if I have made it all the way out of my for Loop still have not returned true that means I never found the word and we are going to return false okay so now how do I want to write up my helper function again what does this do right this is a depth first search and we're going to perform this recursively we're passing in a board what our word is what we're one column we're on so what index of the board and index forward so what character are we looking for so how we're going to do this is we're going to take our row and column whatever's being passed in we're going to see if it matches whatever index we are on for the word so does our current Cell match the letter we're looking for if it does then we're gonna make four more checks we're going to call this function four more times in the different locations looking for index plus one looking for that next letter if we find it then we're going to make an additional four checks and we're going to keep recursively calling this function until we return either true or false so this is a recursive function which means we need two things this is a base case and the recursive case what are our base cases so they're going to be two base cases here either we return true or we return false if we return true that means we have found the word so how do we know if we've actually found the word well if the index that we are passing in is greater than the length of the word that means we found all the letters that we needed to so far so if index is greater than equal to the length of the word then we return true that means we have found our word now when do we return false if the letter we are on doesn't match the one that we're looking for or if we're out of bounds so if rho is greater than equal to length of the board four row is less than zero or column is greater than equal to length of the board of zero or column is less than zero or the cell doesn't match the character we're looking for so word of row and column is not equal to word at index whatever we are passing in then we return false foreign what happens if we don't go into any of these if conditions that means the cell we are on matches the letter we're looking for so what do we want to do now what we want to do now is actually nuke out that cell right we want to get rid of it so we don't reuse it but we can't just empty it out because say we don't find the word going down this path we actually want to undo getting rid of that letter so what we want to do is save it so I'm going to save my letter so word of row and column I'm going to save it before I get rid of it so now I've saved it I can go ahead and get rid of it so board row column and I can set this to anything I'm just going to set it to empty string so now that I have emptied it out now I want to make my four searches so I am going to call self.dfs going to call self.dfs going to call self.dfs on the board that I have now modified right I have emptied out the cell that I was just on passing in that same word now I want to change up the cells that I'm searching for so I say I search for whatever cell is above me so row minus 1 and column and I'm going to pass in index Plus 1. or if I don't return true here maybe I return true from the cell below me so self dot e f s on board word row plus one column index plus one or maybe it's on the left and right of me so self dot DFS on board word row column plus one index plus one or that last final Choice Self dot DFS forward word column minus one and index plus one so this is going to return either true or false and I'm going to save that variable in found so found is going to store whether or not we've returned true or false from all of these searches and the reason for that is because in the end I want to return found and why can't I just return right away right why do I need to store it in found and then return whether or not leave found the word it's because I actually want to change up my board so once I've gone through all these conditions I want to reset say this return false right I want to reset my board so what I'm going to do is have word of row column equal that letter that I had saved if I had a returned this answer I would have ended my function because anytime we have a return We exit our function so instead what we're doing is we're just saving in a variable returning that variable later on because we want to reset our board say we went down multiple recursive calls and we didn't find our word well now we want to go back to the board as it was and we saw in this example right if we didn't find it we would put it back to the letters that they were and continue searching so this is sort of just making sure that we don't erase it and we still hold on to that data and in the end we just return true or false that goes into our original function so let's go ahead and run this code runtime error let's see missing argument do not include row here there we go okay now if we run the code it's accepted and we can go ahead and submit this okay and it is accepted as well so talking about space and time complexity for space we are going through a recursive call right so it's our call stack that's taking up space here and we would recurse as many times as there are characters in our entire word so if we had K letters in our word our space would be o of K now what about time is a little bit similar but how do we think about this right we are going through iterating through an entire board so to begin that is at least o of M times n so we're going through every single grid now at any single grid what are the max number of calls that we could be making well what are we doing when we're searching for our word right we're looking for every single character so say for example I have a board that looks like this right a bunch of A's then a d what are we doing in this scenario I start off with index 0 I find my first letter now I want to look for my second I'm going to look top bottom left to right obviously these two are out of range but those checks sort of do happen right they just go on bounds what we do call them so those don't really amount to anything now I check right say go to my right first well now I'm looking for my third character I've gone through these two I don't see it so I backtrack I go try this option I don't see it now I backtrack all the way I don't even use this index zero as my first character I move on try to do this as my first character and make the same checks top bottom left right and I do this all the way through so for any character I'm gonna be making four checks and I'm going to be doing this for as many letters that I had in my word so for that first letter it would be four checks the second letter it would be another four checks the third letter would be another four checks and when are these checks happening right so if I'm starting off my first letter I made my four checks and I continue down I didn't see it so I stop now I go to my next letter and do the same thing again make the same number of checks the four checks then the four checks and the four checks again so yes I am iterating through but what is this being multiplied by this is being multiplied by the four checks for every single character that I have if I have three characters that's four times four so it's four to the power of K if K is the number of letters that I have in my word so the time complexity for this is O of M times n times 4 to the k it is not the fastest problem but this is what the time complexity is and for this reason we probably shouldn't be going through an entire example like we usually do but we are going to be going through an example just so we can see how our code is running line by line okay we're going to be using this example to go through and test out so with this example this is my board and this is the word that I want to find going line by line we start off from the top we find out what our rows and columns are so rows columns they are both three and three this grid has three of each and Now We're looping through so four row in range of rows for common range of columns row and column right now begin with zero now we make our first check is the cell we're on equal to the zeroth index of our word is a and does a equal the value at this index of the board zero they're not equal so we're out of this for Loop and back in now column equals one so now we check this cell is it equal to the first character of our word it is so now we call DFS so we've all solved.dfs with our board so we've all solved.dfs with our board so we've all solved.dfs with our board so we're going to be passing this whole board in and let me rewrite this so we have Ford we are passing in our word aav the row and column that we are on so that is zero for Row one per column and zero for the index right that's what this DFS function takes in so now we want to call DFS with the following inputs what do we do the first check we make is index greater than the length of the word so the index we're on is zero and let me just write these out so we know exactly what is which so four is this where it is this row column index these are the values that we've passed in index is zero length of word a b that is three that is not true so we do not go into this if statement now we're in this if statement if the row or column are they out of bounds zero one they're not out of balance or if the seller on doesn't equal the index that we want so the silver on is a does it equal the index of the word so Index right now is zero word of index 0 is a they are equal so we don't go into this if condition and we don't return false so what do we do now we save the letter so Board of row and column so at 0 1 the board holds a so we're going to save that letter and now what do we do to our board we wipe out that character so say this was the board that we had this is the board that we've input right to visualize this is what we're doing we are wiping it out and now we are making four checks so now we're calling found with the following input so we're calling self.dfs so we're calling self.dfs so we're calling self.dfs with this board so we're calling with this board we are passing in a b what else are we passing in row minus one column and index plus one so row minus one what row are we in right now zero so we're passing in minus one the same column and index plus one which is one or what is the second call that we are making let's copy paste these in actually so for board we are passing in the same board and the same word this time we're doing row plus one so we started off at zero so zero plus one is one column stays one index plus one so that is zero plus one which is just one or we call it again and I'm going to copy paste these in with row sing as is column minus one so that's zero or row sync is as is again and column plus one so these are the four calls that we make but before we can actually get to all of them we read left to right so the first thing that we come across is this DFS so now we are recursively building out our pulse type this is our new call set so here again forward is this word is this row column and index so we're going to be doing the same checks again we are back into this if condition right we check is the index greater than the length of the word it is not we cannot return true now we make the following checks are we out of bounds or does the cell we are on not equal to our index so our board right now looks like this and we are on row minus one column one we are out of bounds right row is less than zero so we are going to be returning false so this call returns false so for this call we have false and now we want to do the same thing for all of these calls going down so for all of these we will be making the same calls and now looking at the board we know that we will actually not be able to find our word a b from this starting index so we know these will all return false right these will all return false we could go ahead and like go through all of them but just to save some time this will all be false so found is false we are back into our original color we have popped back up now what do we do once we return from here now we want to bring back the board to what it was so board at row column equals letter so we're putting a back into the board and we are returning found we're returning false back to this collar and now that this has returned full so we're going to be going back into this for Loop so we were at zero one now we are at zero two so at this index doing the same things over and over again until we finally hit this condition and we would once we start here at this a go left and then down at B we would be making some more calls and we wouldn't be making all of these calls but at this point we would see that our index is greater than the word after we hit B and after B tries to make calls so we would finally return true up until then we would keep returning false and if we do have an example where we can't find the word at all we would be looping through going through all of it in the end returning false so this is how to do a word search if you have any questions at all let me know down below otherwise I will see you next time
Word Search
word-search
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once. **Example 1:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED " **Output:** true **Example 2:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE " **Output:** true **Example 3:** **Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB " **Output:** false **Constraints:** * `m == board.length` * `n = board[i].length` * `1 <= m, n <= 6` * `1 <= word.length <= 15` * `board` and `word` consists of only lowercase and uppercase English letters. **Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
null
Array,Backtracking,Matrix
Medium
212
1,281
Gas distributor to question see khair activities in the difference between subscribe appointed number subscribe my channel subscribe channel and subscribe button more to subscribe village me ki and jhal product lete hain the interactive vande the part of April You can only take 10 National Roads, if you join this less then subscribe like subscribe The Amazing, you can write anything, now if I have subscribed then subscribe button, then if we want then subscribe, Haryana is Amazon, we can search by whose name. If you are doing then in Amazon mint Jhad that and a model stand is located, that reset which is marking is basically for subscribe to loot yearning equal to front will ask product in 2012 and I can write subscribe to be lit and then some Don't do it I enjoyed I acid her and install the same subscribe so this after that the accused now we have sexual intercourse of a little bit of a written towards - we sexual intercourse of a little bit of a written towards - we will go so that let's do Bihari citation loot 123 question is methane moment until
Subtract the Product and Sum of Digits of an Integer
can-make-palindrome-from-substring
Given an integer number `n`, return the difference between the product of its digits and the sum of its digits. **Example 1:** **Input:** n = 234 **Output:** 15 **Explanation:** Product of digits = 2 \* 3 \* 4 = 24 Sum of digits = 2 + 3 + 4 = 9 Result = 24 - 9 = 15 **Example 2:** **Input:** n = 4421 **Output:** 21 **Explanation:** Product of digits = 4 \* 4 \* 2 \* 1 = 32 Sum of digits = 4 + 4 + 2 + 1 = 11 Result = 32 - 11 = 21 **Constraints:** * `1 <= n <= 10^5`
Since we can rearrange the substring, all we care about is the frequency of each character in that substring. How to find the character frequencies efficiently ? As a preprocess, calculate the accumulate frequency of all characters for all prefixes of the string. How to check if a substring can be changed to a palindrome given its characters frequency ? Count the number of odd frequencies, there can be at most one odd frequency in a palindrome.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
2165
187
hello and welcome to another leeco problem today we're going to be doing a pretty easy problem it's going to be problem number 187 your Pia DNA sequences and so if you're ever taking um biology or chemistry or anything so you know that DNA sequence is composed of a series of nucleotides abbreviated acgt adenine cytosine guanine and thymine and um this is a DNA sequence when setting DNA it's useful to identify repeated sequences in the DNA and just like a science background repeated sequences means like you have the same gene over and so that's good to know and so given a string s that represents a DNA sequence return all the 10 letter long sequences that occur more than once in the DNA molecule you may return the answer in any order and so in this example so this 5a's five C's repeat here and then also this repeats and then this so you have two four six eight ten A's and then obviously this is the same sequence and this is the same sequence so those are the things I repeat so just think about how do we want to do this and for our example we can actually even make like a smaller sequence right instead of 10 I just do like a three or whatever right so let's say we have a sequence like let's just start with this five A's so how do we have that if we're looking for let's say we're looking for repeated three letter sequences so first of all to get a sequence you need a three a string of this many characters right so like you would start with just the start and then it's pretty straightforward you're just gonna have a right pointer and a left pointer and that's going to be your string and then all you have to do so what does a repeat actually mean a repeat means you've seen it before so how would we check if you've seen something before in preferably linear time well it's also pretty straightforward so what we can actually do is we can have a scene set and we can literally just go through every single string of let's say in this example three characters so we'd start here and we would say okay is it in our scene set if it is so we can have a scene set and we can have a res set as well and so we can say if it's inner scene set that means we saw it before so let's throw it in the red set and the nice thing about using a set for res is we can add the same string a bunch and we will only have one copy of it right so our code is literally going to be we're going to go through and we're gonna check every single string so we'll do this string and then we'll do this string right and we're going to say is it in here if it is we've already seen it so throw it in the res otherwise throw it in the scene side so res just basically means have we seen something once and if we've seen it once then we can throw it in the res and I'll think of what would be actually like so when I first did this problem I thought um like the problem with this kind of approach is so when you actually build up strings in Python is like let's say you have this string and this is three characters so you would need to build it so that would cost you that would be go of three and then the problem is when you move this left in this right you can't strings are immutable so you can't just delete one character you have to recreate a new string and so for every single string you'd make they would be Big O three in this case but the thing I didn't realize is actually it's not so bad because this is only a 10 long sequence so then our complexity would actually be so like for a two pointer it's Big O of N and then at every Point we'd have to make a length a string of length 10 so it'd actually be 10 which is not that bad so if this thing asks you for like a let's say you had a 10 to the fifth string or something you know and then you had like 10 to the 10th um like you'd have to go through that then that would be expensive because that would be more like 10 to the fifth times 10 to the 10th but because their strings are so small they're only 10 characters this is just going to cancel out when we do the actual algorithm so it'll be big open time and so that is kind of important for you to realize that even though we are recreating and that's why in a lot of algorithms ideally you don't want to have a string you actually want to have a character list and so if you had this but the problem with this is we have something like this but there's no really way to figure out if like is this character list in our set because we can't store a list in our set we have to store immutable objects in a set or a dictionary or something like that so what you'd have to do is if you did store a character list you would have to keep joining the characters in that list which would also cost you the same thing right so if you try to join this into a string that would also big O3 because you have to take every single letter and add it so there's no really good way to like or maybe you have like a count of each character and say but the problem with the count is like the orders will be different right so like if you've seen this before it doesn't mean you've seen this before and so on and so the most like the most efficient way we could do is we actually do have to manually get the strings at every index okay so let's code that up it's pretty straightforward so we have a left and right pointer where they're going to start at zero actually what we could do is we could technically start at yeah so we could technically just start the right pointer at index nine because you know we need a 10 character string and then when we loop we're going to start we're going to say while right is less than length s so if we did have like a one digit or something string it would just never get into that Loop okay so we're gonna have a scene set and we're gonna have a rest and then we're simply gonna try to make every single string right so we'll just say well standard um two pointer technique so the wall right is less than s and then we can just construct the string right so we'll just construct the string we'll call that time for whatever equals s n in Python it's like this and it's not inclusive so you want an extra character here and then we'll simply say if temp in scene then go ahead and throw it in res and we can throw it in as many times as we want just like I said since we have set like if we see this thing a bunch of times we're going to keep throwing it in res but S7 will only have one occurrence of it because they're you're not going to have more than one occurrence of identical items so we can throw that in there else Okay so yeah so if it's not in scene then just go ahead and throw it into the scene technically we don't need the cells but it's fine so okay and so what this will do is we're going to check every single possible string going down so that's the nice thing is it's a 10 lot once again when you do these problems you want to look is it a continuous sequence or is it uh is ours at a non-continuous sequence is ours at a non-continuous sequence is ours at a non-continuous sequence right like can I chop out some letters and make a sequence and if you have to start chopping out letters then you can no longer do this left and right pointer but because here this is a continuous sequence okay and so now that we have our res we uh this is going to be screwed up and so here we're going to have a res now we can simply return whereas and I think I should do it oh I forgot a couple things actually yeah so we also need to move the left and right pointer all right plus equals one less yeah we're gonna have an infinite Loop here because we never moved it so because we start at the left and the right at like exactly and this is we want the start counting the um like we're going to have a valid string right away we can move the left hand right otherwise you can start them at zero and then you can just say like you know if my string isn't big enough keep the left pointer the same and if it is big enough then start moving to left but this should work as well okay let's take a look okay and so now let's think about the time and space complexity so for a time it's going to be um it's gonna be a big O of n times 10 right because you can have there's and different locations you can make a string and so that's going to be that and then for space that will also be Big O of n times 10. technically but like I said because you know we can get rid of these this is what would actually be because every string is 10 characters so if we just say that's uh that's constant then it would be this because you can have this many strings technically in the scene and I think they can all be unique you can have quite a bit of unique strings with actg it's like four to the 10th or something so this is what it's going to be because yeah the 10 is going to cancel out because it's uh in Vigo you can cancel out constant numbers that's going to be everything for this one hopefully you like this problem and if you did please like And subscribe it helps grow the channel and I'll see you in the next video thanks for watching
Repeated DNA Sequences
repeated-dna-sequences
The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`. * For example, `"ACGAATTCCG "` is a **DNA sequence**. When studying **DNA**, it is useful to identify repeated sequences within the DNA. Given a string `s` that represents a **DNA sequence**, return all the **`10`\-letter-long** sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in **any order**. **Example 1:** **Input:** s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" **Output:** \["AAAAACCCCC","CCCCCAAAAA"\] **Example 2:** **Input:** s = "AAAAAAAAAAAAA" **Output:** \["AAAAAAAAAA"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'A'`, `'C'`, `'G'`, or `'T'`.
null
Hash Table,String,Bit Manipulation,Sliding Window,Rolling Hash,Hash Function
Medium
null
581
welcome to february's lego challenge today's problem is shortest unsorted continuous subarray given an integer array you need to find one continuous subarray that if you only sort this subarray in ascending order then the whole array will be sorted return the shortest such sub array and output its length so if we had an example like this we could see that if we just sorted from this array on to up to here nine if we just sorted this part then the entire array would be sorted here with these arrays these are already sorted so we don't have to store anything and there's a follow-up can you do this and there's a follow-up can you do this and there's a follow-up can you do this in all of n but let's start off by trying to solve this very straightforwardly let's say we had this array here how would we figure out what is the continuous sub array that we want to sort well let's sort it first and see like if we can find any insights here if we had uh if we just sorted the original array and made it sorted the whole thing what would it look like it looks something like 9 10 15 something like this right now we already know that the answer is this what do we see comparing these two is the case well basically we can see that whenever the numbers are different if we check to see our sorted nums it's going to be this basically everything's going to be different right and really what we're trying to find is the left most index number where the numbers are different and the rightmost index number where everything is different and once we have that we can just subtract the two and get the length of the subarray that we want to sort to get it to be sorted so let's start off with that's a relatively straightforward method let's first create a temporary array and we're going to call it numbers two we'll sort the nums and we'll also initialize a couple variables we'll say n equals length of nums and uh we'll also need to store the left and right most right so left and right left we're going to start off with n and right we're going to start off with 0 because we assume that if there's something unsorted this is going to be less than n and it's going to be greater than zero right okay so for i and enumerate nums we want to get the index number we want to check to compare these two we want to say if nums i does not equal nums2.i then we know nums2.i then we know nums2.i then we know these aren't sorted in this position so we should store the leftmost and rightmost so to get the left we will do let's see l equals the minimum between l and i while right is going to be the maximum between r and i all right so once we break out of here um we know that if like these have remained unchanged that means the array is completely sorted so we don't need to do anything so if l still equals n then we could go ahead and return zero because it's already sorted otherwise we're going to subtract r l and we actually need add one because these are zero index numbers and this is going to give us the length of the array that needs to be sorted it's going to be from here to here so let's make sure this works looks like it's working submit it there we go accepted so this is um n log n time complexity also use o event space uh but there's that follow-up right we want to do an oven follow-up right we want to do an oven follow-up right we want to do an oven time the reason this is accepted probably is because sorting is pretty efficient in python but say that this wasn't very efficient like could we do this in one pass yeah so um to do that there's couple methods the one that i'm gonna do is why don't we go through our numbers and create a stack where we're gonna add to our stack as long as um the array is still sorted how can we do that well like say we add two first into our stack here and then we add six it's all sorted but then we have four uh well this isn't sorted right so we're gonna have to pop off the numbers that aren't sorted and then add that four in here now what does this number six tell us well we know that at this index number this isn't sorted right so we need to store that number here as to be the minimum left most and we're actually have to go backwards and also find the right most as well we can do that by storing the max value of the numbers that aren't sorted whatever we have to pop off we know it's like not sorted in the correct order and store whatever max values in there and when we do that we can just start from the right and then move to left find that max number in the unsorted array and say okay whatever that index number is return that and then we'll just return r minus l plus one again okay so let's go with that method first we'll create a stack and we will also initialize n we'll also have r and l um actually we're not going to start with r we're going to start with storing that max value in our unsorted array right so we'll have our left and we'll have our max now mat left is going to start with n but max is going to just be let's say a uh the minimum most number just to make sure since we have no idea like how big and small these values can get so we'll add that and we're this okay so for we need the inn again so enumerate nums remember this is not sorted uh what will we do well if there's a stack and the last item in the stack and i should mention in our stack we want these to be like tuples we're going to have the index number and the number here that way we can just keep track of it easily you don't technically need that you can like write it so that you could just look it up using the index number but i just i'm just going to do that because it's a little bit more intuitive so if stack the last one the stack and the number which is the second element if that's greater than our number that we have now we know we need to pop it off because that's unsorted we know it's not in sorted order so we'll pop that off and we're using this candidate while we popped off we're going to store our left most which is going to be the minimum between left and candidates what zero and we'll store our max value which is going to be the max of r and candid one okay make sure to add to our stack after that a tuple of the i and n okay so now we should have our left and right uh first thing to check is look if l is equal to n that means everything that we've added what went in order and l still remains n uh we know that it's already sorted then so we turn to zero otherwise we have our left most left point but now we need to find our right so to do that i'll just say four i in range of n minus 1. we'll say look if let's think um from the rightmost we need to find the value if it's less than our max then we know that's not sorted right yeah i believe that's right so if nums dot i is less than our max here then we need to store our write and i need to store it right here as well right let's start with zero and now right will equal i and we just need to break our loop immediately after that because we don't need to check anything more uh we already know uh what the max value is in our unsorted array and if we find our that's different at this point then we know that's going to be the right side okay so now we have our left and right uh just we need return r minus l plus one and that should be it let me make sure this works local variable r isn't stored oh i'm sorry that's not r there max okay so that looks like it's working let's go and submit it great so this is oven time um it does use oil and space because of our stack now there are solutions where you could do it in o n using constant space uh but they're pretty mathematical um you know using like local and global minimums and stuff and i didn't really find it intuitive if you're really interested in that i'd say check it out otherwise i think these solutions are fine so yeah we'll stick with this alright so thanks for watching my channel and remember do not trust me i know nothing
Shortest Unsorted Continuous Subarray
shortest-unsorted-continuous-subarray
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
Array,Two Pointers,Stack,Greedy,Sorting,Monotonic Stack
Medium
null
1,170
all right so hello and welcome here we are I haven't streamed for a few hours um just give me a moment to check the audio and pop out the chat for a few hours okay yeah I kind of took something of a break sort of um I won't go into too much detail with that we'll just say that I took something of a Break um and short break very short uh not that short but short enough am I good to go here hold on a second think we're good think I'm good okay think we be good take a deep breath here um yeah I um all right this is going to be number 1170 compare strings by fre frequency of the smallest character this looks like it's probably going to be the easier side um the I've been playing a video game I'm interested in speedr running video games I'm more so interested in like glitchless runs because I like the kind of logistics of it algorithmically like it's a pretty interesting question how do you uh optimize speed runs without glitches of games but anyway um let the function f of s be the frequency of the Le lexicographically smallest character in an on empty string okay FS is 2 uh array of strings words another array of query strings queries for each query queries of I count the number I should actually spend more time reading I realize one of the problems I have is I don't spend enough time reading the question and fully grasping it and it takes me a lot longer to solve questions because I don't do that properly sometimes um count the number of words in Words such that F of queries of I is less than F of w for each w W in words return an integer array answer where each answer V is the answer to the ey query so let the function f of s be the frequency of the Lex lexicographically smallest character in a non-empty string smallest character in a non-empty string smallest character in a non-empty string s okay for example if s is dcce then F of s is 2 because C is the lexicographically smallest character in the string and there are two of them as a frequency of two okay so you given an array of strings words and another array of query strings queries for each query queries of I count the number of words and words such that F of queries of I is less than F of w for each W in words okay so I have an array of words and another array of query strings queries for each queries of I count the number of words in Words such that F of queries of I is less than F of w so for each query I can get the I can calculate the frequency and then I'm looking through all the words in their frequencies and I want to count the number of those words have a higher frequency than the query okay I'm pretty sure you could do this in and log end time right I think all you have to do really is sort the words by their frequencies which is not too hard to calculate with the frequencies are um and then for each query um sort the words by the frequency then for each query calculate frequency and then perform a look up on that sorted list it's probably the easiest way to do it um there's maybe another way it's slightly more efficient but that's probably what I'll go with for each W in words return an integer array answer where each answer is the answer to the I query okay interesting question um first query CBD is one zaz is three this is less than that so we have one time okay it's going to be also um we want to know how many words have a larger frequency than the query right so a uh um probably upper bound is what I want to look when I perform the binary search upper bound yeah upper bound okay all right um I think I understand so I really just need the frequencies in an array and sort it and I'll probably just want a simple routine sub routine that'll calculate the um the frequency of a particular word there should be yeah okay 2000 2,000 words 2,000 queries okay 2000 2,000 words 2,000 queries okay 2000 2,000 words 2,000 queries should be n log end time overall pretty high acceptance rate not that many submissions but good significant number of submissions yeah this is not too bad I think that I'll go with that um frequency it's going to be first things for oh these all lowercase letter yeah okay that makes it easier um con standard string s get the frequency it's going to be for given s we're going to um full present of 26 standard fill present with false and then we're going to say for con Char CH and S A present of CH minus a is true going to sa for um zero is 26 plus I if present of I so this will be the lexicographically smallest um assuming these are non empty these strings yeah they should be non empty um so we get the smallest one that's present and now we want the frequency as well actually could do even better just frequency let say F it's easier um if f is greater than zero return f pretty straightforward other wise return negative one okay that'll get the frequency for each now I want to have um int uh word frequencies const in N words. size let's do m is the number of queries and then n is the word um word frequencies say for each I word frequencies of I is going to be frequency of words of I and then now we're going to sort word frequencies right standard sort regular sort and then we're going to say for each um const Auto s in queries actually I don't need this I think pretty sure I don't need that um oh no um I do want that actually go back I do want that is less than M result size m all right so we're going to get a pointer upper bound of word frequencies of the frequency of s and then I'm going to take um from that point to the right those will be elements that I want so it's going to be constant we'll say x is going to be word frequencies plus n minus pointer uh oh no excuse me other way around pointer minus word frequencies say index convert that to an index and this is going to be index n -1 - iix + be index n -1 - iix + be index n -1 - iix + 1 from that index to index nus1 and if it goes off the edge it could be zero right so if the index is uh n right and this obviously yeah these cancel um if the index is n if it's off the edge then um then it's just zero I think that's it that simple that was a lot of programming just for the idea is very straightforward um how do we do tment um okay oh yeah I should have I was I would name this the frequency array but it actually uh I named this frequency so I could use a different name for that maybe I could have used a different better name than f works okay I need to generate more um another test I'm actually not going to generate another test I think I probably I could generate more tests but I kind of just want to submit this and see if it's if it works I'm not going to do that just going to go for it okay got it very good all right pretty fast let me see let me try I'll submit it four more times um and then uh move on to the next question it's one two 1 2 3 4 5 6 7 8 um I want to go until like maybe two or 3 hours something like that 1 2 3 4 5 six next question is um remove Zero Sum consecutive nodes from link list looks like this is not the fastest solution 1 two 3 4 one two three maybe I just need to inline this code for the frequency calculation um I don't know maybe if I just keep submitting it I'll probably get 100% it's very close to 100 I think get 100% it's very close to 100 I think get 100% it's very close to 100 I think it's probably good enough I think it's good enough maybe there's a better way to do this it's a little bit faster but this is reasonable I think I actually don't need yeah well one pass is fine I was trying to think if there's like a better way to do this um this is reasonable there may be a slightly faster way you could um you could use uh counting sort for the word frequencies because the frequencies can't exceed the size and yeah they're the size of the string is relatively small so you could use a counting sword here that would actually improve the speed a little bit that might be the way to get 100% but this is might be the way to get 100% but this is might be the way to get 100% but this is good enough all right thank you for watching and I'm going to just restart another question if you like the stream like the video give it a like if you like the stream give it a like and you like the video like it and subscribe for more all right take care
Compare Strings by Frequency of the Smallest Character
shortest-common-supersequence
Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2. You are given an array of strings `words` and another array of query strings `queries`. For each query `queries[i]`, count the **number of words** in `words` such that `f(queries[i])` < `f(W)` for each `W` in `words`. Return _an integer array_ `answer`_, where each_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** queries = \[ "cbd "\], words = \[ "zaaaz "\] **Output:** \[1\] **Explanation:** On the first query we have f( "cbd ") = 1, f( "zaaaz ") = 3 so f( "cbd ") < f( "zaaaz "). **Example 2:** **Input:** queries = \[ "bbb ", "cc "\], words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** \[1,2\] **Explanation:** On the first query only f( "bbb ") < f( "aaaa "). On the second query both f( "aaa ") and f( "aaaa ") are both > f( "cc "). **Constraints:** * `1 <= queries.length <= 2000` * `1 <= words.length <= 2000` * `1 <= queries[i].length, words[i].length <= 10` * `queries[i][j]`, `words[i][j]` consist of lowercase English letters.
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence.
String,Dynamic Programming
Hard
1250
689
To Ajay, welcome to polling in August and in today's video we will talk about maximum sum of non- we will talk about maximum sum of non- we will talk about maximum sum of non- rotating morning, near the top of the solution. Before this, one more time about maximum sum of two 9, but you must watch the video of morning, we are going to extend that in the same way. By Kapil week, we will get one helicopter number and one number that is, so we have come up with this I want to find the maximum group elements in all three but morning is the world should you have to print and is represented starting position of every morning and morning will be Get their starting index also printed, information and if there are multiple answers then turn on the graphical mode that understands this thing so much that at the maximum it would have been a tight hug example of One Dos 65, then see one answer of mine, this can be because Bluetooth There are three more of two sizes but early in the morning come Bluetooth settings off setting electricity and its settings 5 flash light is getting something from here it is not getting time from here so another answer is possible from zero to 5 that we Chetan lexicographical smallest vadh 1357 try 1035 depends on the tractor this is lexicography for smallest so let me use this jhal so this ribbon is ours and I have kept only volumes here and check three so exactly like ask question. That's when both of them, but what was done in it in the morning, first, the Deputy Governor was made, he was breaking the information inside it, that this index till Play Services will be like cancer in America, second, there is sugar in the DP, that let's come from the coolness till the last, all this morning. What is the maximum A Perfect? ​​If we do some work first, A Perfect? ​​If we do some work first, A Perfect? ​​If we do some work first, then after that we will bother to give it a send. To make three chocolate mixture balance, how much work do I do before that. If you will study to make me double first, then there is one. Left to right will bill one, if it is right to left, then I name it left and I name it try is 1234567890 Eleventh and fact 250 seconds were induction and Ghar Baite Chali Aa, so what about left, let's start. Till the coolness, this entire morning Max Samsung Champ is good, okay, let's be a person, remember, if it is spent, then here is a rich source of literature, here of two literatures, if we set refilling the gas from here, if it is a village, then there is only one morning in which Kasam kitna hoga part plus two plus one pain back aap apne ishta hai to C index me friend caller up to the printhead where is the maximum of all the mornings then I asked brother tell me conductor how possible is all this collection then he said One more time, select all the current morning options. Okay, so get four plus two plus one seven inches here, what are the maximum inductors before that, they will ask, tell me how much is the maximum possible for all the current mornings. And the second vector which is with the current, ignore it in the morning, mix both of them, then the max of eight and eight, this 2011comments here, this lemon and 4% Chintu 2011comments here, this lemon and 4% Chintu 2011comments here, this lemon and 4% Chintu Eleventh Jhal Eleven and Seven's Back to 9 6 Maths A right that eleven and the time of the train, now the records are going to be updated here, the time of making the president and actors, how much would be the maximum possible for the gesture of coolness, then I was not angry next9 Brother, you told him your answer, the size of the window of force and current If you do medical center then this is the time of sixth class ninth class twelfth mix both show here scientist is ok and let's meet a little bit I want to change it tightly I want to keep Shravan C here and here But again, if there are two pictures of this A, then the current window will remain the same as Kasam Six Class Ninth 12-12-12-12-12-12-12, if Kal and Welcome Express are the same, then the left has been made in the same manner, the height refers to the right. Hey, this text of coming was the last till the whole morning, how much is the maximum possible, this is the maximum, we have done the above two on two 9 clapping survey research, so let's go here, they are considering, yes here considering and from here three sizes have started moving forward. So it was covered China for more next like 9 had to be done that how much macrame time it would take for the whole morning from the note to the last contact, so I asked the first time that you tell me how possible is this whole morning collection from the note till the last contact, he said Said it is twelfth and then I have developed the window of size to be edited that it is Tamta six plus C interest, a part of both of these were from the above, correct more, you must have understood these two factors by now, absolutely from him Agarwal And often ask and second will do its midding we can do ok short value and welcome Let's do a few and I will ask you a question, first a third line starting point potential from where to where do you get the doctor to vary the third request that first he said one is on the left Malaika, this one will like on the right and one is only in the middle If you like that cigarette then from where to where can be the starting point of this middle rack jhal middle morning, look at how potentially tight it is, I said should you come to the left at least once, those were the days of the left, so leave it in the right. If you want to come once then leave the last three monkeys on the two sides and leave the plastic restrictions inside the first one. Now I said that maybe the medical certificate could be this or this, okay it could be this or this to attract the passengers. Because how will be the middle rack point, neither will it be, it is the middle and cannot go further than this, if it goes to your house, then the channel for the morning on the right, not only after a minute, but the elements for the morning with torch light are not only children, otherwise The middle age is a starting point from where the phone will vary and how far it will go. Friends, the starting point of the middle is from where to where my phone can go till point mintu. Return the total number of elements and the key element and the elements of the next key, let alone the elements of the type of wickets - but it wickets - but it wickets - but it will vary till that point, look at the problem, now this thing has become quite easy, now it has become quite easy, so what would I have done? Middle is like dog, I will cancel it but if I have done this caricature, then I will take the time of question, then what is the maximum of excise survey till the third index of clusters, from the seventh contact till the last, how possible is the maximum of this entire morning, then in both the information. Fast hogi till third one, maximum left after will be arranged according to you, till inductive last, how possible is this all morning collection, it will give you select options to A above light of seventh, picked up right of formal and I picked up the sea of ​​this middle morning. On the formal and I picked up the sea of ​​this middle morning. On the side of closure and what could have been the medley, that whole post, I have written it really yes, the mission has been done till now, let's take all those factors and see and then what is the answer from here, tell that in one post, the old one tries to I am fine that let's go yes son Sankt Hanji epic jhal to first purify the gesture in the house of the factor from here to here and till here if I had done this pregnancy then I would have wanted the answer from thought to intact all the mornings of the conductor How possible is the weather of so from here I take the value otherwise I want to write that if I take the value of i to two okay in fact now we will start it from 3 how do we set the height how do we set so my Whose answer is there, take a look at the leftovers, why is the I-bank answer, why is the I-bank answer, why is the I-bank answer, Jhal is ok and then there is the middle, Rekha Rao, Santosh Dhal, morning time, we will make it with something, middle first of all, I swear, we will make this issue and then my The only answer is that from how Sachin will pick till the last, how possible will be the macrame of all till the last one, will it be the responsibility of editing I Plus, so let's start that I will ofton means the morning of the medal, so believe it. The time of criminal is this due to laptop 2.0 time of criminal is this due to laptop 2.0 time of criminal is this due to laptop 2.0 or that on Android topics will start from us and the middle order will be the sea and the first factor of plus 379 411 decided this and the second bad try only turn off the festival of and I mean this survey. It's good to start from Rao side in the morning, it's fine till three, it was macrame of the whole morning that at the hospital, we will take out the sea of ​​the morning, 4 hospital, we will take out the sea of ​​the morning, 4 hospital, we will take out the sea of ​​the morning, 4 plus 3 a little plus 298 and to 1000 preservatives so be here, I'm just a On the right toe five plus, he said wealth, this is all the title, I thought for ipl-5, this is all the title, I thought for ipl-5, this is all the title, I thought for ipl-5, oh for the purifier, that means I am making it raw, starting from here, I have done it with green and here, the one with the end oggy button. If it is in time then fourth induct to maximum staff's ASI morning 181 last till Vikram Samvat cases pal were most grouping size window 7 4 6 7 8 main abhi let's go I will use the alarms I set so now what will we do like this 08 The juice which is valid on this platform discussion electron will be found here 11:00 The answer to diet will be found here 11:00 The answer to diet will be found here 11:00 The answer to diet will be found here and the value and current window swear you plus one two three plus research that now the value of the last eye was seven then come I am busy so I will give it less time But it remains okay, so till the second, A, select water, take the morning's maximum moment 10x till the last A, that all this morning's maximum number, A plus current 133 stand up, check all these, Mac spinal, my answer is going to be that all these Look sequentially, where is the lock coming from in the back, cutting, you will get it from here, thirty one, you will get it from here, 299, these lines are ok, now most likely, I will get it from here, 10 and if the feel is tight, then I am sure, 30c, yes, understand this, get it from here. This is going to be 30 Duets of 50s. Okay, so first let's do this much work, then we will think about how that lexicographically smallest thing is managing that thing. How did you manage the others to get these different things done? When will you come? First of all, let's try to get the maximum painted. So, now the robbers have to take out the cases under oath with the help of prefix time in between the minute time, which means making a deep and inside which you will leave the training that the traffic jam information will be given correctly in the size window of both. If I ever swear on you, it becomes easier for me on matters like if someone were to find out the time of this destruction, then he says that he should understand all the letters till the index line, he would understand all the letters till the intake, then 7898 is a pin code here. First I have to prepare the left and right ones, oh how toe land is looted, okay and there is one more thing, traffic related jhal, okay, so I started that we have signed 120 and I have looked at the value from zero. You can decide which letter and key and i plus app to use so what will I do, at that time you simply add go to the current element and at the same time on laptop it is ok, even Why is the relationship based on the sequence like see here that once here I will give five stars in the fort, here once I will give a creative tour and here if I am related wise then I have got five plus two plus 184, now going ahead. What will happen, how was the answer created, a value was taken from here and the time of the current window is calculated, so how is the current window oath obtained, that till now the time was this, till now the oath is ok, by adding the current element to the time till now. By doing two more current elements, it means that the time has come till now element - also time has come till now element - also time has come till now element - also started doing like this till now I swear I told you that the next element has come, the fans have been muted, okay then the plus is closed, then this guy has to improve the last one. Friend, if you do a pinch then only that window will be able to move forward, add it at this time, I was able to add it and - do it, add it at this time, I was able to add it and - do it, add it at this time, I was able to add it and - do it, Oye - if you want to tell me the news of the current trend, then see, at that time, I add infidelity - I do that time, I add infidelity - I do that time, I add infidelity - I do infidelity - ke. infidelity - ke. infidelity - ke. What will be the answer to 'Ko Hai' and 'Laptop Hi'? O madam Check, light etc. is ready, similar work was done, we had done maximum sum of two 9 clapping, watch this video, you will immediately understand that now if we click on the right one, then I have changed the medium size from zero and this Year that I run the loop from and minus one only till it is tight. Okay, so this is this great daily item of I plus and so this has different schools that when here I have not done anything else, Armaan live your lips. And he gets it done, okay here, give it six more and here also Sameer, we had done six till here, I took oath, got it done till 9th, Assam broke 12th, next time if you make it 2 factor cancer, then how long do you leave it like this? But the value rate of I Plus is fixed that it is of white color and the track of a passenger train is correct for both the parties. Now if this happens then I am simply adding infidelity and on top of the right of I. Weaken the other wise how will the time of the current window come out, let's add 205 and in it we will have to subject that this is a 110 light of I will be O madam Okay-Okay, now I have handled the prefix and if I want it, I am going to Okay-Okay, now I have handled the prefix and if I want it, I am going to Okay-Okay, now I have handled the prefix and if I want it, I am going to murder her because this lesson and half inch plus Akhilesh probably has values ​​toe, values ​​toe, values ​​toe, so I will give infidelity information in the exam form of I will use a prefix Samosa I. Inside a prefix function test till puberty plus current element donkey which is jhal ok then three murder her husband fix leftover radhe so now I try to extract my maximum this last make it medium get this printed from motorcycle That the truck is the last print in the car is a certain iron Mental Maths Okay okay what have I done to get you out of the swearing The middle line starting point from where to where Mary's tell that from that to that and minus two Till the time we are going to do a variation on whether we will get this saree comment, if it is good, then how did we make it from the house of business, then the maximum will be Madonna Mexico's till now, then the action and the current track is going to enter 116, so let's come - 150 would have been cool. Is my ko 116, so let's come - 150 would have been cool. Is my ko 116, so let's come - 150 would have been cool. Is my ko right over i plus how does it wake up till 9th ​​basically i want to ask which is the 9th ​​basically i want to ask which is the 9th ​​basically i want to ask which is the setting point of is intact medley so i said i - one till preservative's i said i - one till preservative's i said i - one till preservative's weather picture i plus how does last till water where is the morning's maximum ok Okay, both of these were calculated in Pune. Now, how did you distance yourself from the starting point? Calculate the time of that morning. If you type in all the mornings, then how will you calculate the time of all those mornings. See here if you know how to do it and were friends. On the last issue, I have come up with this thing, if there was a laptop then only minus one right on five plus, how do you organize this rally, how will it come out with the help of traffic jam, if there is a suggestion, then there is a prefix function, jhal i plus - 1m jhal i plus - 1m jhal i plus - 1m truck here. Till April is over Plus K minus one it is of tractor - traffic jam of - if the correct then what will be the time of size window of current Prefix intercourse that I Plus K - 52 - I Plus K - 52 - I Plus K - 52 - A Which is Ayushman Jhal in Prefix Smoke So let's Once only how many sins are burnt and kept, the extra was 2982 and ours was only 2328, so the maximum part, now we have to print induction, general and lexicographical smallest mind, which are they, so tell me one thing where. Have you found your maximum? Have you found the setting point of your middle morning? Have you found your maximum? Have you found your starting point? Have you found out exactly where this value is? The value of the maximum would be I, you will get the value of I, the starting point would be that cigarette, so I write it a bit like this, you will definitely see, I said that medal is a starting point, so in the middle of the morning, once it can be sliced, okay Okay, so if you have maximum that if this factor mutes maximum but stay tuned that if this factor maximum weighs then I will give maximum circular and at the same time I will say starting point of middle all deaf yet still I have come. You will get the check Starting Point You have found out the correct Okay now I need a certificate of left are left morning's certificate and rights America's certificate The left word in fact This is how it is written Starting point of web survey A starting point to right morning This Now you have to think a little bit about it till the time what am I going to do that from where you got this time's maximum aluminum maximum from here, how sour and weak that should be, maximum 38th here. I ignored left for a minus one had taken out the pain of love medley so I have to see what value was lying above the laptop i7 phone and what value was above right five plus one the result was the comment here level here the person is double and After that, I will find out that first thing in the morning, before the cold, see the time of the thing from one starting, the time of the first survey and its investment, that body, I will speak through a starting point of left morning, you have to listen that I take an oath on the first morning of 11th that I will print the setting point of the thread. Starting point of mine is my complaint. Is it just a joke of theirs like the starting point of the middle morning? We know that and it is the same. What will I do to you, find out the size of both of them from minus one to the last of I Plus in the morning or whose time is that wave whose resolution, this is my answer, it is cool, here it is narrated by me at night that what I want to say is the first left. What do I have to do to get the starting point of F103 Tax Act, the first one in the morning, whose time is only 11:00, okay, print out its starting point. For writing, I have to remember from i plus minus one to the last one. But that first morning which is shining had to be painted Correct Lexicography This gold will be found that when you think about this case, the intake of rough is a friend, it has the knowledge of the elements of two cases, so it is there also here, it is okay And that's what you're getting from here, six, mix it well, you're getting that from here, free six, so to make you do this incident, we are making 360 exactly and this 360 is so keep it, the mind works that I let you drink. Getting the information officer done, what should I do with our hands in these facts for once? I make the number of the left one 90 and stop the time of the right one only during intercourse. I request the time of the left one from here. The laptop is working and the number of the right one is In the evening, I select here, I try to show the plus on the show, it was correct that now find me, left a last point, okay, you like this is the first band, all this is the first, the size of the morning, whose qualities of Assam are with him. Get this point printed. Okay, so it is a prefix. Time was made. It does this. Hey brother, I want to get the value varied. We can settle the matter from here. Let's decide. Okay, this tube is a rock band. So this is the first s that one person can go to another person - that one person can go to another person - that one person can go to another person - how far can this minus one go, how far can a pan point go, let's go to the maximum, as long as it's good, okay, a starting point of the middle - 1m a starting point of the middle - 1m a starting point of the middle - 1m good. Okay, I am based in London, now I will come here and tell you that if you get a call for 'Traffic Jam Off Ki I - Traffic Shambho Ki I - Ki Value Album', call for 'Traffic Jam Off Ki I - Traffic Shambho Ki I - Ki Value Album', call for 'Traffic Jam Off Ki I - Traffic Shambho Ki I - Ki Value Album', I will break it right here, print it and put it together. That's going to be a sad point in the blueprint of I's left survey where for the first time you get the value of Edison. Loot time work. Here you have to make a small cut. You have to make a small cut here that if you - K if you - K if you - K becomes a minus one. If yes then you prove it by zeroing it otherwise this value is ok this is love Hi - K this garlic ok this is love Hi - K this garlic ok this is love Hi - K this garlic green tea I have which 1000 was considered prefect white k a so now for the night like this I left morning's print lubricating Got the point printed, just after that Medals America reminds me, okay, it will be the starting point of middle morning, then if we work hard for the right, then the loop will run, a starting point of middle morning, Aplus, now this is a minus. One to the last key is 256. If anywhere you find this volume prefix mode i - traffic jam, the value of i-k traffic jam, the value of i-k traffic jam, the value of i-k goes high at the time of a mean light, you will never get the answer. Go get the how toe printed and make it bigger as well and understand this as a match, getting it printed is the first thing to make a friend, I just see, got the brain completed, after that the satin point of the left morning, the setting point of the middle morning and the setting point of the right morning. Okay, that's it and this question is over, I'll copy it once and run it to see that there must be a respectable family tree. Okay, it's a small town, you won't say I came, you'll say I came - the you won't say I came, you'll say I came - the you won't say I came, you'll say I came - the answer is okay. Friends that because of which a that I - that is that would be its endpoint I Sahiban want 16 members we had taken out if this was the point left side 1212 C plus one girl that applicant plus one with starting point because I to end The point is, this is the point, it ends there, share on your page to a platform to submit that you can get Electrolyte SIM, here these people, I have to start quickly because I am on the right way and not the starting point of subscribe is tu * k v - m is tu * k v - m is tu * k v - m That I will meet from here, I will have to go to the hospital, let's try it out, so let me try to explain this last point to you once again, okay, that is only this part, I will just understand this thing, I will give you an example later. For suppose you got the value of garlic 1134 right signs that you have tips and starting point of middle morning electrification of this ad jhal chicken commission hai Sara has come now to make a little testis for me I try a pipe 232 16 n sweets hai to jhal phone number 9 time 904 jhal a certain tremendous opposition 110 taste one music a the correct that here day 10 do flash lights difference pulp ki sex hands free ki tennis under-16 ki tennis under-16 ki tennis under-16 The smallest understand this P I you what we got then starting point of metal time which will be in the disputes zero 12345 680 bachelor nine knots in it morning subscribe to till now so now what we had to find out that first cases its 11 typing point Okay, so from here to here, so here I set 10 - I set 10 - I set 10 - no value here, so make it 505 10 E will not equal to tension further let's move forward I plus traffic jam of I - I plus traffic jam of I - I plus traffic jam of I - Professor - K 10 - 10 Professor - K 10 - 10 Professor - K 10 - 10 Okay, so you have read this till here, training 527 10 and 6 - Graduation Exam - 511 So give this answer for you, your brother, the starting point of this is going to be one, do you want the value of I or have I printed it? - It's want the value of I or have I printed it? - It's want the value of I or have I printed it? - It's on K Plus, okay, so I came to lapsi - K okay, so I came to lapsi - K okay, so I came to lapsi - K spent Plus One I should have this point of one printer, so now what did I do for this fort report, try to understand for the light, it is the phone that you have set the medley. The point is fixed here, she can do three elements from here on top of it and after taking one more element the next day, when I reached above the twelfth, Raees, the pending point potential of the morning will start from here, set the cut from here. Phone even swear - set the cut from here. Phone even swear - set the cut from here. Phone even swear - even the time is that traffic jam and pie - past samosa - ke to current that traffic jam and pie - past samosa - ke to current that traffic jam and pie - past samosa - ke to current printer is included a strict to where with what typing point of middle morning plus two * from seven point of middle morning plus two * from seven point of middle morning plus two * from seven plus two * from 2332 deeds - Wherever plus two * from 2332 deeds - Wherever plus two * from 2332 deeds - Wherever you are, this is not the first time that I expect you to understand the question, please do some exam on it once, ok, only then do more flights, Tyagi Putra, ok, then there is a picture from this video, thank you very much. Mach
Maximum Sum of 3 Non-Overlapping Subarrays
maximum-sum-of-3-non-overlapping-subarrays
Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one. **Example 1:** **Input:** nums = \[1,2,1,2,6,7,5,1\], k = 2 **Output:** \[0,3,5\] **Explanation:** Subarrays \[1, 2\], \[2, 6\], \[7, 5\] correspond to the starting indices \[0, 3, 5\]. We could have also taken \[2, 1\], but an answer of \[1, 3, 5\] would be lexicographically larger. **Example 2:** **Input:** nums = \[1,2,1,2,1,2,1,2,1\], k = 2 **Output:** \[0,2,4\] **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] < 216` * `1 <= k <= floor(nums.length / 3)`
null
Array,Dynamic Programming
Hard
123
76
Hello welcome you, give 9 of D practice gauge and I also came to trouble you on Sunday and here is the question which I solved today and along with it, this is the fifth question of this week before this and last week I solved four questions. His record has been broken today hopefully next week do more questions do six days practice so but ne it's go date see practice five questions this week and which was this time's question which I have solved Minimum Window Substation This is Un hard question but not that hard if you know sliding window then ok now let's see what is the question so here the question is saying given tu string here we have an input string and a temp. Of length A goes, meaning we have to find the value in regular, one is right and one is sub string means regular, whatever you sub string will come out and it will be regular, it will not happen that one word is this, then one word is this. Whatever our substring of this not like date will be, it is always in the sequence, okay, and most probably there are chances that this is the first hint that our sliding window may or may not appear, okay, so now what do we have to get out? Key Every character in temp strength Every character in time string ABC is included in D window is ok Inside this input string we have to find a window which is of minimum size which is ok and if all these characters are included then for example input String this A B C output what came B A C this one why because this was the minimum window which has ab is b also is when is ab is bb is also c is also ok and what could have been another window a Here is B Here is C Here is So A This one could also be a window What was its length 1 2 3 4 5 6 What is this one 1234 So this is this Minimum right so you go D question So now I will give you Let me tell you how I have approached it. Okay, see this code later. Now I will tell you the approach first. The approach will seem simple. Right, see what is my approach. For example, this is the question ALOBC. M N O B A S C This is my input stunt A B C Now in this, what I have done first of all is I have created a map, okay frequency map, here I put the frequency map, meaning how many times do I have to search for ads, how many times do I have to search for them. So now I needed one time each and how much is the total counter, I have to find three 123 characters, so this was the first thing, so first of all, you will see, I have done this thing, I keep telling you this thing in my court. The first one till here I have made a frequency map by iterating on which one okay and not sorry not this van this one is a small one okay here I have made a frequency map by iterating on which one the second step what in the second step Now I am doing this to understand that I will do this from here till here, the entire string is okay, so this is my window, now I have done the sliding window, so this is mine, for example I and let means start means end of the window. I am starting to badhaunga from here to here, first thing first, I need it here, I will go to my map, what is the van in the map, okay, I need only one, okay, so that means, what will I do right now, make it zero. I will do that I have got A, the counter is still not zero, the counter is done, that means I need two more strings, do I need L, if there is no L anywhere in my frequency map, then I will move ahead, so I am here. I will move ahead, here is my A is here, do I need O, I have that in my frequency, otherwise right now neither the counter is decreasing nor anything is happening, I will move ahead, here is my A, and what? I need B so I will do it is zero and the counter means I have to find one more character, still the counter is not zero, so that means I still have to find one more character, so till now my window is started from here. And it is not over yet, now I have moved forward to the end, this is my end, P, do I need P? No, P is not there, I will move ahead in the map, I have moved forward to the end, C, do I need C? Han is C1 now. As soon as the counter becomes zero, it means I have got a substring, okay, so here I will find its length, it is from the start to the end, okay, what is its length? 1 2 3 4 5 6 Till now what is the length of mine because now I am getting it for the first time so the length has become six and what is the character of ALO BPC and my output now I have extracted the substance from the beginning till the end, it is fine till now. It's but I'm not done yet Now I'm moving on Okay now I'm moving on Now I'm moving on What's this M What do I need B Do I need B But This already counter has gone to zero, so I mean, I am getting one more time. Okay, so now I'm here whenever my counter goes to zero. Now I'll check one more thing here, can I move this start forward? Okay, if I move the start forward and still my sub If the string is valid then it will still be written, so now I will see if I can move the start forward, where is the start now, where is my A here, can I remove the A and move the start here, so now A, do I need the A key? Need Han, I wanted only one need but now it is zero, which means I got as much as I needed, but if I move the start, it means I have to increase it, right, I need one more A, right, if I get one from here. I remove it like there is substance because A Ba has come only once A If I remove this A from the window then I will have to increase A once that if I want then date max sub string is invalid so right now it is zero meaning I have If there is no access to A, then I can't proceed right now. Okay, so right now I ca n't proceed. Now I came forward, I am fine on A is on, so A, I needed it. There was a need, but it is zero, meaning now. I have A in the access so I will do -1 A has gone in an axis so I will do -1 A has gone in an axis so I will do -1 A has gone in an axis I have so far now the counter is zero so I am checking can I increase A starting from here can I move forward let's Let me see, should I move the window here, I am removing one from my window, okay, I only needed one but I already have one read in accessories, okay so if I remove this, it will become zero because I have two right now. The meaning was in one access so now I am removing it so the meaning is only one which is what I needed so I will remove it this is my start okay this is the start this is the end now do I need L I am checking the start further, how much further can I go? L is needed. Hey, L is not needed, so I will increase the start from here also. It will start here I needed O is also needed. No, I will increase the start again but I have already got B in one access, so if I remove this B also, then my substring validity will remain, then I remove this B also, I reach the start here. B has become my zero now means I have only one bear whatever substance from S to the end do I need P otherwise I can still move forward with this do I need C Han but it is already zero if I If I remove this C, then I will need a seat, so it will become a van, okay, it will become invalid, so now I can't increase it, so now what is my substring from here till here, till now, ok. Now if we check further here, what is the length of this van, you are three four five six, it is still six, it was already six, so it has not become any less, so now let's move forward, now I have taken one here on the jet, can I? Need a jet No don't need a jet but already got it but it's me having access A means -1 right here I'll access A means -1 right here I'll access A means -1 right here I'll see if I can increase the start Si Han Si needed but mines van already access I have it, meaning I will increase it, if I remove it, I will still have zero because I already have one in Access, so my starting index is of I went here, do I need N? No, starting output, how much length is there from here to here? 1234, if it is smaller than this, then it will change. 4 and where will bazc come from bazc, so this is the same logic that I have applied here on the sliding window. Here's the code, I'm incrementing the window end, okay, and first of all, what I'm checking here is, do I need characters, contents, okay, if I need characters, I decremented the counter here. Okay, by reducing the counter, I am also reducing its frequency. Okay, here the counter is fine. If my counter is zero, then what am I checking? Can I advance the start or not? When will the start advance when I have already It is in negative meaning whether my substance is valid even after removing the word or not, so if I want this word which I am removing in the beginning, I wanted it but if even after removing it, I still have &lt;= 0 means zero or less, okay, if it &lt;= 0 means zero or less, okay, if it &lt;= 0 means zero or less, okay, if it comes positive, it means no, I need it, okay, so here I am checking whether my sub string is valid or not, even after removing the start, if it is valid then I am increasing the start and I am also increasing its value by one plus one, okay, otherwise if it does not become a valid string, then I will break from here, my start cannot go ahead, okay and if this one which If I do n't need any of these characters then I can move the start and every time I check that whatever my new substring is A then after moving the string forward I can move the start to s. After whether it is less than my minimum length or not if it is less then I will update it in my output if it is less and here I will return it and from the sliding window approach okay the concept is simple the coding you You can write as per your wish but this is the logic which is fine and no hard question was found so difficult even from Sliding Windows. If you understand this concept then ok gas but you can also tell me your approach by commenting that you like it. What is your approach and can there be a better approach as well? Is it ok? Thank you and have a happy weekend, happy Christmas and happy new year bye.
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
1,552
hey everybody this is larry this is q3 of the recent contest a magnetic force between two bars uh hit the like button hit the subscribe button join me on discord and yeah so for this problem um to be honest when i first started working on it i didn't know how to figure out like i thought okay maybe there's a dynamic programming solution i think there is to be honest but then when i look at the constraints it's like okay n is ten to the fifth uh so that's a hundred thousand every position could be 10 to the ninth so usually that makes it not dynamic programming about at least not usually um so the first thing you should do and i looked at this uh so i'm really thankful that they have uh an input like this on example because i might not have remembered to sort to be honest uh so then i remember the sword because why would you not sword right uh and then behind that um i'll be honest with how i came up with the solution uh versus like you know just i think sometimes people you know when you watch other videos by other people they'll just be like hey this is the solution but they don't tell you how they came up with it um for me how i came up this illusion is a little bit of a uh cheating a little bit of guessing and yolo um in that i look at these constraints i'm like okay so i knew that it has to be at the worst time and log n um and position is slow enough that or big enough that you can't really do anything based on the position so the only really two possibilities uh for me to think about it uh one is greedy um if it's greedy then you know there may be some probably that you play around with any like okay then you just squeeze it in the other is binary search or something similar to binary search and after you sort the position um it reminds me of another problem where uh or similar problems uh in you know there are just similar problems that it reminded me of and that's how i came up with it uh and the idea is that okay now that we sorted and now that we're given um uh a spacing like okay let's say there's you know x space between you know you're forced to use x space between uh or this is the force i suppose uh between positions how many balls can you fit if you could fit enough force then you're good uh and then you try to get more if you cannot then well then you need to make this force smaller right uh and because you're trying to get the minimum magnetic force uh where the maximum that means that um the most you can go oh sorry the minimum you oh sorry the max you can go is that for x that you put in so that's basically my idea um and i um i did this uh binary search for that i vote i do a search after position sorting uh then head and tails have uh you know your range for your searching will have to be between zero uh i guess technically one but uh thankfully it didn't matter uh and then the position which is your largest number right because you know that's just the constraints because division one to ten to the ninth um and then i just do a binary search this is straightforward uh and for binary search i always have to think about a little bit of like okay if this number is good then we move uh the head too good uh because if mid plus one is good that means that we want to keep that into the in the range of good possibilities so we move head into the mid plus one uh if this is not good then we want to eliminate mid plus one so that means that it goes from head to mid right so that's kind of how you do it um uh how you visualize the binary search that's how i visualize binary search and then we just have a good function which is okay what we said earlier given a given x given an x um we want to go from left to right for these positions and then um we want to have at least x between every ball and that's pretty much how i solve this problem um let me know what you think hit the like button the subscribe one you can watch me solve it live during the contest next what first the minimum magnetic field this is good uh
Magnetic Force Between Two Balls
build-an-array-with-stack-operations
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** between any two balls is **maximum**. Rick stated that magnetic force between two different balls at positions `x` and `y` is `|x - y|`. Given the integer array `position` and the integer `m`. Return _the required force_. **Example 1:** **Input:** position = \[1,2,3,4,7\], m = 3 **Output:** 3 **Explanation:** Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs \[3, 3, 6\]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3. **Example 2:** **Input:** position = \[5,4,3,2,1,1000000000\], m = 2 **Output:** 999999999 **Explanation:** We can use baskets 1 and 1000000000. **Constraints:** * `n == position.length` * `2 <= n <= 105` * `1 <= position[i] <= 109` * All integers in `position` are **distinct**. * `2 <= m <= position.length`
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
Array,Stack,Simulation
Easy
null
1,639
hey everyone welcome back and let's write some more neat code today so today let's solve the problem number of ways to form a Target string given a dictionary so we're given a list of words where each of the words is of the same length so something like this and we're also given a Target word so let's say in this case our Target word is a b a you can read through the description but it's definitely overly complicated in my opinion the problem is pretty simple we're trying to build this target word character by character so we are first trying to get the a character we can get that character from any of these input words so for example we could take this lowercase a great the problem is when we take a character so we took this character to match this one now we are going to be looking for the next character the problem is we took this character but now not only can we not reuse this character we actually can't use any character from the same index as the character that we already used so now we can't use this B and we can't use this C alternatively we could have actually not chosen this a we could have when we were trying to match this a we could have chosen a different a we could have chosen this a or maybe even this a the problem is when we choose one of these characters farther to the right we can not only not reuse this character and the same character from the other words like the same position from the other words but we also can't use anything to the left of the character that we already use so we can't use this and we can't use anything to the left of it same with every other word so that's the Restriction here and that might make you think well if we ever want to even be able to build this word we better have these words have a length that's at least equal to this one I don't know if there's a guarantee about that but that's just like a small observation that you might make so what's one pos possible way that we could build this word well we could use this a which makes it so we can't use these characters anymore now we're trying to look for a b there's no B's over here there are some B's here we probably want to pick this one so let's go ahead and do that now we can't use these characters and now we're lastly looking for another a we have actually a couple choices we could do this one or do this one let's just do this one and now we've matched the target so that's one way we could build the target word and in this problem we are trying to count the number of ways we could do it so this will kind of make you think let's try a Brute Force approach let's try to count every single way manually maybe with backtracking but definitely with recursion because kind of like the last example showed for this last character we could have a branch where we choose this character and by then we would realize we've reached the end of the Target string so both of those are going to be base cases both of those are going to be branches each of them is going to return one this Branch counted one way to build this word this Branch may be using this character counted another way to build this word and if you can honestly get the Brute Force solution that is getting pretty close to solving this problem there are probably multiple ways to Brute Force this well there definitely are the challenge is to do it intelligently so that we can apply caching to the problem and to be honest you never know if you can actually do caching or not until you actually try to Brute Force the problem and try to figure out which parameters you are going to pass into that recursive function I usually call the recursive function DFS you can call it whatever you'd like some people call it DP or maybe you can give it a long name it doesn't really matter but what parameters are we going to be passing in well a couple of the obvious ones are gonna be what index are we at in the Target word because we are going character by character to build the target word let's call that index I because that's kind of the most important one we can't really move to the next character unless we've matched this character so in our DFS that's going to be one variable and luckily in our list of words we only need one variable they call it K in this problem so that's what I'm going to be using as well but we only need one variable because this K will tell us the position we're at in every single word because anytime we use a character we can't use any characters to the left of it for every single word so K is going to make things pretty easy for us and initially it's also going to be at zero to start with just like I K is going to be our second variable and that's actually all we really need we don't really need to keep track of anything else okay so given that how do we even Brute Force this problem before we even think about caching how do we brute force it well it's all about thinking about what are our choices that's what it's about what choice do we have when we're trying to find a matching character for this we're looking for a character we're at this position in all of our words so our choice here is let's try to look at every single word does this word have a lowercase a at index K yes it does so that's kind of a possibility does this have a lowercase a it does not so that's not a possibility this one also does not have a lowercase a so we really only have one choice here and when we take this Choice how are our parameters going to be updated well let's say we started at index 0 I is at index 0 and let's say our K is also at index 0 well when we go here we're definitely going to be incrementing our I because we did find a match so that would be one and we're also going to be incrementing our K because we used the character at index K so now we can't use anything to the left of it so now K is going to be one now this is not a great example to figure this little trick out but think about it this way what if there had been a lowercase a over here too there was a lowercase a what would our other Branch look like well I would be incremented by one and our K over here would also be incremented by one so what I'm saying is whether we use the character from this string or this string as long as we use the character at index K our parameters are going to be the same we're going to increment I by one it's going to be one we're going to increment K by one it's also going to be one so why do we even have to call this twice we don't need to call it twice why not just call it once and multiply the result by two like this take this and then just multiply it by two by this I mean like the recursive call and the return value is going to be multiplied by two that's pretty obvious and simple but how is that going to help us because within our recursive DFS function aren't we still gonna have to Loop through every word c okay does this have a matching character yes it does that's one does this have a matching character no so we're still at one this also doesn't have a matching character so we're still at one maybe though this did and this would have been two whatever that value is we still have to Loop through every word and look at the character at position K don't we so even if we apply caching to this problem the overall time complexity is going to be the length of Target let's call that t and the length of each input word let's call that K and then for each DFS call we're gonna have to Loop through every word anyway even if we apply memoization to this would be the time complexity with memoization and then multiplying that by looping through each word is going to be let's say k squared or actually not K squared it's going to be the number of words let's call that W so this is going to be the overall time complexity that's actually not bad but it will get time limit exceeded on leak code so there is another trick we're gonna have to do and basically it's gonna be pre-computing the count of each gonna be pre-computing the count of each gonna be pre-computing the count of each character at each position so basically we're gonna say how many lowercase a characters are there at position zero among all of the words how many lowercase b characters are there etc we're gonna go through each position get the count of each character and then within our DFS We're not gonna need a loop inside that DFS so then the overall time complexity of the DFS will become the length of the target word that was T and the length of each input word that was K so that's going to be the overall time complexity of our DFS if we apply caching I'm kind of assuming that you know the technique caching because if you don't this problem is definitely hard we've solved many problems using this technique including the previous problem that we solved yesterday okay this is the time complexity of our DFS we improved that but we remember we still do have to do that pre-computation still do have to do that pre-computation still do have to do that pre-computation among all of the words we have to get the count of each character that's not going to be too bad that's going to be the length of each word times the number of words let's say that's W Times K and these two terms are not going to be multiplied together they're going to be added together because first we're going to do the pre-computation and then we're to do the pre-computation and then we're to do the pre-computation and then we're going to do our DFS with caching so this becomes the overall time complexity so that's kind of the trick this is a pretty standard dynamic programming problem you can solve it with caching but the trick here is that we have to do some pre-computation before that's some pre-computation before that's some pre-computation before that's kind of what separates this from like a medium dynamic programming problem into a hard problem so now let's code it up okay so one thing I didn't mention is that our result since we're counting the number of ways it could be a really big number and basically we just want to take that number and mod it by this value this is 10 to the power of 9 plus 7. that was a part of the problem description I just didn't really talk about it too much now we want to go through every word third in our input words and get that pre-computation let words and get that pre-computation let words and get that pre-computation let me actually create the data structure I'm going to use for that you could use a two-dimensional array and that would a two-dimensional array and that would a two-dimensional array and that would probably be a tiny bit more efficient but it doesn't really change the overall time complexity so I'm going to use a hash map which is a default dict in Python the value here is going to be an integer making it a default dict makes it so that the value is initialized to zero regardless of which key we have what we're doing here is mapping the index of the word and the character of the word to the count of that character among all the words so you'll see what I mean as we do it but we're going through every single word then we're going to go through every character in the word we also want to keep track of the index because we're going to need that we need to know the position of that character so we can do that like this in Python when you enumerate a string like w that basically gives you the index for free and we also get the character so now with that we're just gonna say get the count using the index and the character and increment it by one the index is important because remember when we use a character from a word we can't use any character to the left of it so we need to keep track of the index next we are going to do our DFS our recursive DFS two parameters I talked about I is going to be the index of the target word I'm going to comment that just to make it clear I is equal to the index of Target and K is equal to the index of a word which let's say words array J is just some arbitrary word and K I'm kind of using it as we're going to be using it K is going to be the position of the word so now our DFS we didn't really talk too much about the base cases the obvious one is when we reach the end of a word and we well when we reach the end of the target word because that's what we're trying to build here so when I our pointer is equal to the length of the target it word that means we reach the end that means we built the word we found a way to build this word so let's return zero there's another base case what happens if our K pointer reaches the end and what happens if that K pointer reaches the end but this did not execute so we put that if statement after we say what if K is equal to the length of a word let's just take the zeroth word because all of them have the same length if this happens we're not able to build the target word oh I meant to return one here let me not mess that up but here if we did not reach the end of the target word but we ran out of characters to choose from then we did not build the word so we have to return zero the last case is when we actually have the value already cached so I'm going to do that from the start we know we're gonna have caching and we know the key that we're gonna use here I'm using a hash map you could also use a two-dimensional array if you want we're two-dimensional array if you want we're two-dimensional array if you want we're going to be mapping i k to the number of ways that we can build this target word starting with like this sub problem basically so if we resolve this problem multiple times we don't have to actually do all the recomputation so we're going to check is this key in our DP hashmap if it is go ahead and return it and I have a type over here let me fix that before we go any further now we're going to have the recursive case and actually there's one that I didn't quite talk about in the drawing explanation but it's not too complicated we know we could use some characters at position K and I'm going to do that in just a second it's possible that we don't have to use characters from this position we're just trying to count the total number of ways it's possible we could build the target word while skipping the characters at position K that's a very simple case to code up all we have to do is leave I the same because we did not find a match matching character for the character at Target at index I and we're gonna increment K because we're deciding to skip this position so I'll make that obvious and this value is going to be stored in our DP cache it's going to be our result so I'm going to have that like this we've initialized the value here now it's possible we could include this position how do we do that well the DFS is going to be I plus 1 because we did find a matching character for index I so we're going to move to the next position and we used the character at position K so we are not allowed to choose it again so now we say K plus 1. how many times would we want to call this DFS well how many matching characters are there at index k for what character well the character is gonna be the character at Target index I so we say Target index I is equal to C and now we're going to use is that c character as one of the keys for our count so let's say count here the key is going to be the index that we're at which is k is the index of like the words and the character C which is the character that we're looking for so this tells us how many times does this character show up in the kth position among any of the words so this is what we're going to multiply by our DFS and this is what we're then going to add to our DP because we're trying to count the total number of ways we're not trying to find the maximum or minimum or anything like that so I'm just going to copy and paste that and say plus equal to this over here and then we are just going to go ahead and return that value we computed but the one thing you don't want to forget is to mod it by the value that we have written all the way up here this is pretty much the entire code let's go ahead and actually call our DFS we're starting at position zero for both strings and before I run it I just want to quickly mentioned you could have not done this pre-computation to find this done this pre-computation to find this done this pre-computation to find this count this account over here you did not need to do this pre-computation you need to do this pre-computation you need to do this pre-computation you could have a loop in here to do that you could have gone through every word and then done this part but that would decrease the time complexity it would make it well it would make it less efficient for reasons that I talked about earlier which is why we are doing the pre-computation so now let's run it the pre-computation so now let's run it the pre-computation so now let's run it to make sure that it works and as you can see yes it does at first it might look like it's not very efficient and the reason is because here we're using hash Maps instead of using two-dimensional arrays it doesn't change two-dimensional arrays it doesn't change two-dimensional arrays it doesn't change the overall time complexity but using arrays is more efficient because you don't need to Hash the key so it definitely improves the run time but I don't really think it's worth it because in a real interview I don't think anyone would care if you're using a hash map instead of a two-dimensional array but instead of a two-dimensional array but instead of a two-dimensional array but you can use a 2d array it just takes a bit more code to actually initialize it in Python that's why I went with a hash map but if you don't believe me try replacing these with 2D arrays and you'll find that the runtime does improve I think to about 50 when I tried it but I definitely prefer more concise code if this was helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has interviews check out neat code.io it has interviews check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Number of Ways to Form a Target String Given a Dictionary
friendly-movies-streamed-last-month
You are given a list of strings of the **same length** `words` and a string `target`. Your task is to form `target` using the given `words` under the following rules: * `target` should be formed from left to right. * To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`. * Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string. * Repeat the process until you form the string `target`. **Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met. Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba " **Output:** 6 **Explanation:** There are 6 ways to form target. "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ") "aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ") "aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ") "aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ") **Example 2:** **Input:** words = \[ "abba ", "baab "\], target = "bab " **Output:** 4 **Explanation:** There are 4 ways to form target. "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ") "bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ") "bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ") "bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ") **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * All strings in `words` have the same length. * `1 <= target.length <= 1000` * `words[i]` and `target` contain only lowercase English letters.
null
Database
Easy
null
1,578
hello and welcome back to the cracking fan YouTube channel today we're going to be solving lead code problem 1578 minimum time to make rope colorful before we get into the question just want to ask you guys to like and comment it really helps me out the YouTube algorithm so really just leave any comment you want it really helps also check out the Discord Channel if you haven't already and let's get into the problem Alice has n balloons arranged on a rope you are given a zero index string colors or colors of I is the color of the ith balloon Alice wants the Rope to be colorful she does not want two consecutive balloons to be of the same color so she asked Bob for help Bob can remove some balloons from the Rope to make it colorful you are given a zero indexed integer array needed time where needed time of I is the time in seconds that Bob needs to remove the ice balloon from the Rope return the minimum time Bob needs to make the Rope colorful okay let's look at an example so we have this rope here where there's a blue balloon a red balloon a blue balloon and then a green balloon and we can see that we want to make it um you know into one where there's no two colors next to each other so obviously this blue balloon is fine on its own because obviously there's nothing to its left and to its right is a red balloon so we're fine there same with the red balloon to its left is a blue balloon and to its right is a blue balloon which is fine because we don't want two nodes to be next to each other or two balloons here so this one is where we start having problems right this blue and this blue are problematic because they're next to each other so we have to get rid of one of them so obviously we're looking for the minimum time that we need to remove these balloons so let's look at how much time it would take to remove each one so this first blue balloon would take one this would take two this would take three four and five obviously we want to remove this balloon because it's going to take less time to do so we get rid of it and now uh we just have our blue balloon which is fine because to its uh left we have red now and to its right we have green and this green balloon is fine as well because to its left we have the blue and to its right we have um you know nothing right so we only had to remove one balloon so in this case the minimum time was three cool so this question is really easy if you're just looking at it right and basically all you need to do is just find the minimum value of what happens when you have two balloons next to each other right if you just have all one balloon where everything is perfect there's always only one balloon of that color and then the next one is always a different one then you don't have to do anything when you have two balloons we have the case that we had which is a little bit uh trickier but all you have to do is just compare the time needed for that balloon uh with its neighbor figure out which one is larger and then just take the smaller one and remove it right and we can scale this to three or more except for the problem is if we have three or more let's say the cost is three four five right so when we hit the first balloon we will look to its right and we'll see that its neighbor is also one of its uh color so we have to make a decision here as to which one to remove so obviously we're going to take this one right and now we have to do the same thing again but obviously the problem gets smaller and we can basically just reduce it down uh one step at a time and then from this one we see okay which one is easier to get rid of four or five obviously we get rid of the four uh so we'd have like a total time of seven so basically we just want to parse through our array going left to right if we ever encounter two balloons that are the same um then what we want to do is simply just get rid of the one that's smaller in terms of the time needed and we also need to keep track of the bigger time that we just took that way uh as we're going through the array if we do encounter you know a case where there's actually three or more of the same balloon in order then we just need to keep going and comparing the current value you with whatever the last value was and we're good to go so that is essentially the algorithm we want to go with It's relatively simple this isn't even like a dynamic programming question it's just literally a one pass solution you don't even have to use dynamic programming I was surprised I thought it was DP and you guys know I hate DP so really glad that it's not anyway that's enough rambling let's go to the code editor type this up and you'll see just how simple this question actually is I'll see you there okay we're back in the code editor let's type this up so we're gonna need a few variables to actually help us here with our calculation so we want to basically store the you know time it takes and we also going to need a variable to actually store uh the last balloon cost that we had in case that we actually have uh three or more in a row because we're gonna need to carry those forward so we can actually use them as we go so let's define those so we're just going to say res and Cur is going to equal to zero obviously we haven't done anything yet now we just need to process the balloons so we're going to say 4i in range Len colors what we're going to do is we're going to check whether or not our current balloon is actually the same as the previous balloon so let's just say if I is greater than zero because obviously we can't look backwards from the zeroth index and colors of I does not actually equal to colors of I minus one so if this is the case um then we don't have to do anything right if the current color actually equals the previous doesn't equal the previous color then that means that we're fine we don't need to pop any balloons we're good so we can just keep track of our current time which is just going to be zero right because we haven't actually needed to pop anything so we can set reset our current back to zero otherwise what we're going to do is the total time or I guess our result here is actually what we called it is going to be we're going to add to it the minimum of whatever the current time is so basically remember this is the cost when we have multiple in a row so we popped one and now we need to keep track of whatever that current one is in case there's one after it that's the same so we're going to take the minimum of whatever our curve value is and whatever the current balloon's cost is so we're going to say needed time of I so basically we're going to compare the cost of popping this balloon that we're at currently with the ith index with whatever the previous um one that we decided not to pop was because remember we always have a choice which one to pop and we always take the smaller one and we need to keep track of the one that we didn't choose to pop because that's the one that's going to get carried forward in the case that we actually have three or more this doesn't apply if there's only two um but if there's three or more then we need to keep track of the one that we didn't pop so that way the next time we see one because obviously there's three or more in row then we can essentially choose which one to pop so that is what we're going to add to our result and now we need to update our current which is going to be the maximum so the one that we didn't pop is going to be the larger of these two to so it's going to be the maximum whatever current is and it needed time of I and that's essentially all we do once this for Loop ends we'll have calculated our result and all we need to do is return it so let us actually uh submit this and verify that it works submit this real quick and once this runs okay cool accept it and it looks good all right what is our time and space complexity here so time complexity wise as you can see all we do is go through the array one time from left to right with our for Loop here and all we're doing is just comparing things by index so all of that is going to be Big O of one operations and since we do it for the entire list uh this is going to be Big O of n or n is obviously the length of our colors array here for space we don't actually use any extra space because all we have are these two variables which are constant space allocations so this is actually going to be a constant space solution and this is the absolute best that you can do for this um like I said this question is super simple what is this like eight lines of code and that includes some white space here so really not that bad hopefully this solution makes sense for you I think it's relatively intuitive I was surprised that it wasn't dynamic programming and I'm very happy it's not because I hate it uh anyway if you enjoyed the video please leave a like and a comment it really helps them with the YouTube algorithm you guys can leave whatever the hell you want in the comments just slam your face into the keyboard to write algorithm or whatever honestly anything helps it's the engagement that really helps grow the channel if you want to see more content like this subscribe to the channel and if you want to join the Discord where we talk about all things Fang interviewing you can have your resume reviewed by me uh you can ask for referrals at Fan companies all of that join the Discord the link will be in the description below I hope to see you there and thank you so much for watching I'll see you in the next one
Minimum Time to Make Rope Colorful
apples-oranges
Alice has `n` balloons arranged on a rope. You are given a **0-indexed** string `colors` where `colors[i]` is the color of the `ith` balloon. Alice wants the rope to be **colorful**. She does not want **two consecutive balloons** to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it **colorful**. You are given a **0-indexed** integer array `neededTime` where `neededTime[i]` is the time (in seconds) that Bob needs to remove the `ith` balloon from the rope. Return _the **minimum time** Bob needs to make the rope **colorful**_. **Example 1:** **Input:** colors = "abaac ", neededTime = \[1,2,3,4,5\] **Output:** 3 **Explanation:** In the above image, 'a' is blue, 'b' is red, and 'c' is green. Bob can remove the blue balloon at index 2. This takes 3 seconds. There are no longer two consecutive balloons of the same color. Total time = 3. **Example 2:** **Input:** colors = "abc ", neededTime = \[1,2,3\] **Output:** 0 **Explanation:** The rope is already colorful. Bob does not need to remove any balloons from the rope. **Example 3:** **Input:** colors = "aabaa ", neededTime = \[1,2,3,4,1\] **Output:** 2 **Explanation:** Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove. There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2. **Constraints:** * `n == colors.length == neededTime.length` * `1 <= n <= 105` * `1 <= neededTime[i] <= 104` * `colors` contains only lowercase English letters.
null
Database
Medium
null
739
hi everyone welcome back to the channel and today solve Le code daily challenge problem number 739 daily temperatures so it is an interesting problem in which we'll be sto uh we'll be using monotonic stack logic so we'll first check out the problem statement then we'll look into the approach which we're going to use and towards the end we'll see the code as well so starting with the problem statement it is given that uh we will get an area of integers temperatures that will represent the daily temperature and we have to return an array answer such that answer of I so basically every element in the answer array is a number of days you have to wait after the ath day to get a warmer temperature so basically you'll have to look for a value which is lower than today's value in the coming days okay you cannot look back uh you'll have to check uh for the next elements okay if there is no future day uh for which this is possible please keep answer of I equals to0 instead okay for example in this case if you see we have 73 74 75 and so on so forth so for 73 to get a what warmer temperature right represent so that uh yeah so to uh see a warmer temperature basically which you know which will end up sorry uh in we'll have to look for a greater number uh basically okay for example in 73 if you see the next element is 74 so day is one okay now we are at 74 75 is the next element that's why you have got one over here but when you reach 75 the next bigger element or the larger element is 76 which is 4 days apart from the current day right so we will have four over here and we'll follow the same logic so if you see what we are doing we are basically using indexes of the elements as well right so this is what we'll be doing while solving the problem so let's check out the uh approach which we'll be using so as I said like we'll be using the you know uh the approach of monotronic stack in which uh basically your stack or your uh array is either increasing or decreasing okay uh so now what I will do I'll first show you the example like how we got the dumers and after that we will formulate this Logic on the basis of that intution okay so we'll first start with 73 our stack is empty at the moment so what we'll do we will store index in this stack store indexes because uh of course you can get the value of any index any anywhere in the code right so uh the stack is empty so what we'll do we'll add the value here okay now we'll move to the next element we are at 74 now okay 74 okay so the previous element or the element at the top of the stack so top of the stack is index zero right so at index Zer in my temperature okay the value is 73 and my current index is 1 right temperature at current index is 74 so 73 s less than 74 right so what I'll do I'll pop this I'll remove this basically from the stack okay now I know the current position the current index was one okay current index is one the index I popped from stack was zero so we get one okay and this one is the answer of the stack top index the index which we just popped from the stack so at uh index zero in our result array or in answer array we will write one okay and after doing all this we will push the new index or the current index which we just saw so now we have one here okay we'll follow the exact same process now it is 7475 okay and 74 is less than 75 again uh the element we popped was one sorry the current uh index is two okay because we are at 75 we are processing 75 and 2 - 1 will be 1 so we'll have one 75 and 2 - 1 will be 1 so we'll have one 75 and 2 - 1 will be 1 so we'll have one here and we will again our uh stack empty right now comes the interesting part and we have pushed the uh index two here okay now comes 71 okay 71 is it uh smaller than 75 no so in that case what we will do we will just simply push the answer on top of it the index on top of the current stack now we have 69 okay this is also not uh you know greater than the previous element so what we'll do we will again push the index on the top of the stab now we have 72 okay uh 72 is greater than 69 so what we will do uh so okay my current index is five okay current index is five and the value is 72 and as we saw like the element at the top or the index at the top was 4 the value at 4 was 69 right 69 is less than 72 right and we are popping four okay we are uh we are processing this Index right now so what will be the value in the result at index 4 it will be current index minus stack top which is four basically right so uh current index was 5 - 4 which will be 1 so at x 4 I will 5 - 4 which will be 1 so at x 4 I will 5 - 4 which will be 1 so at x 4 I will write one again okay but if you see the after removing this like uh this will be my stack right after that only the uh that also I mean sorry uh after that also my stack top is smaller than the current Uh current uh index value right so what we will do we will again pop this element so temperature at 3 Vols 71 current index is uh 72 71 is smaller than 72 and we here we'll have stack top which is what three current index is 5 - which is what three current index is 5 - which is what three current index is 5 - 3 which ends up two right so at index 3 we will write two okay now this element is also popped this is my existing stack now next okay element at two is 75 which is not uh smaller than 72 so now we will add five over here okay it's time to process uh further the next element now we come to 76 okay we will pop the again element again from the top now the element is smaller element is 72 is less than 76 of course so uh at index five because that's a element or the index we you know popped from the stack we will have one because 6 - one because 6 - one because 6 - 5 okay this is my current stack now but if you see element at index 2 which is 75 this is also smaller than 76 right so we will pop this one as well and what will be the value it will be 6 - 2 which will be the value it will be 6 - 2 which will be the value it will be 6 - 2 which is 4 okay and now my stack looks like this it is an empty stack at the moment now and what we will do we will add six in it next element 73 by default all the values are zero so you know next element 73 76 is not uh smaller than 73 so we'll add seven again and you know we have finished the iteration of the given array so we will basically end up with the result if you check the example out this was the result1 4 210 okay so this is what we are going to do and this will be this is the pseudo logic of it while we have uh stack top like the value at stack top index less than current value we will pop the element and we will update the uh same index in resultant with current index minus uh the stack toop index okay and at the end we will add the current index on the stack so this is the pseudo Logic for the problem now let's check out the uh code for the same so it is a very simple code of around 5 to 10 line uh 10 8 to 10 lines in which what we are doing we have defined in stack okay which we will be using uh we have a resultant array which uh we have you know by default initialized it with zero next we are iterating the temperature array which we have received and I have used in Num because you know we are dealing with index so it is easier to get the index and value at the same time using inate now uh while stack like this basically check if we have valid elements in stack or not okay so while stack like while we have at least one element in the stack and temperature at the value top of the stack is less than the current value what we are doing we are taking the top index from the stack and we are updating that in result with index minus index basically is our current index minus top index is your stack top index okay and after processing this like uh you know no matter how many elements this process or how many indexes this Pro I just say we will add the current index on the top of the stack and at the end we'll just simply return the result so let's check out the test cases so as you can see the test Case C clear let's submit it for further evaluation now and the solution got accepted as you can see and we have performed uh like fail I would say so we have performed around 85.4% on the runtime and 98% on the 85.4% on the runtime and 98% on the 85.4% on the runtime and 98% on the memory side so yeah this all the solution guys thanks for watching out the video stay tuned uping ones don't forget to like the video and subscribe to the channel thank you
Daily Temperatures
daily-temperatures
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead. **Example 1:** **Input:** temperatures = \[73,74,75,71,69,72,76,73\] **Output:** \[1,1,4,2,1,1,0,0\] **Example 2:** **Input:** temperatures = \[30,40,50,60\] **Output:** \[1,1,1,0\] **Example 3:** **Input:** temperatures = \[30,60,90\] **Output:** \[1,1,0\] **Constraints:** * `1 <= temperatures.length <= 105` * `30 <= temperatures[i] <= 100`
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
Array,Stack,Monotonic Stack
Medium
496,937
1,631
hello guys welcome to algorithms made easy in this video we will see the question path with minimum effort the question here states that you are a hiker preparing for an upcoming hike and you are given heights a 2d array of size rows cross column where a particular cell represents the height of that cell you are situated in the top left cell 0 comma 0 and you hope to travel to the bottom right cell you can move up down left or right and you wish to find a route that requires the minimum effort now what is a minimum effort or an effort a roots effort is maximum absolute difference in heights between two consecutive cell of the root we need to return the minimum effort required to travel from top left to bottom right cell now let's see the example and then we'll understand the question more so given this example if you see this is the designed path with output as 2 now why do we get 2 if you see the difference between any 2 consecutive cell that is 1 3 or 3 5 the maximum amongst these is 2. similarly if you see this path over here it is 1 2 which has a difference of 1 again this has a difference of 0 but if you see the difference over here from two to five that is difference becomes three and that's why the effort becomes three and this is the maximum of the effort that you will be spending in traveling through this path and does your effort is three amongst these two path the minimum effort would be on this path that is two and so the output is two in the example two if you see this is the one with a constant effort of one and rest all the path if you see any path you'll get a effort which is more than one at least for one consecutive cell and thus the output would be just one for these path over here if you see along this path the effort is zero if you take any other path you will have to come across two and the effort would go up to one and so you take this path which has an effort of zero that you give it as an output in the constraints we are given that you can have a matrix of one two hundred rows and columns and the height or the value of the cell can range from one to ten raise to six so the maximum effort that you would have to spend would be 10 raised to 6 in the hints if you see it is said that consider the grid as a graph where adjacent cells have an edge with cost of difference between the cells if you are given a threshold k check if it is possible to go from 0 to the last cell using only edges of the cost which is less than the threshold and third is for that you can apply binary search to find the value of k we'll see this binary search part a little later first let's try to apply the basic algorithm which is a dixtras algorithm that would be helpful for finding the shortest path in the weighted graph so let's just go ahead and see what this algorithm will look like so i have taken this first example and let's just try to visualize what we were talking about as how do we find the output if we go from this path the maximum difference or the number that you are getting is 2 while if you are taking this path the maximum number that you are getting is 3. now the minimum of these two efforts is 2 and thus the answer is 2. so what we are going to do over here is we will take an efforts matrix which would initially store the maximum number and will also take a min heap to find the minimum of the paths as we are moving along so we will be starting from zero and we'll check which path is minimum and follow that path and while we get to process this last cell we stop and return the distance or the effort that we have for that particular cell so let's start processing with the first one initially we'll put the effort as 0 and row and column as 0. so this is an integer array that represents this particular thing for the 0 column efforts would be 0 as we are initially standing at that particular cell and its row and column is zero now we start popping from the min heap or the priority queue while popping the element we'll see in what directions can we go we cannot go to these and these directions as they are out of the bounds so we go over here now how is the distance calculated for these cells the distance over here would be the maximum of either the distance of popped element or the distance that we can find by doing a absolute difference between these elements so over here for 0 comma 1 that is this particular cell the distance would be the maximum of 0 or the absolute difference that is 2 minus 1 which would give me 1. so the maximum of 0 and 1 is 1 and so we keep this as 1. similarly for this cell the distance would be maximum of 0 or 3 minus 1 which gives us 2 and so this becomes our final thing and now we also need to check whether we really want to go to these cells to check that we'll see if we have this distance that is less than the distance present for that particular cell in our efforts matrix over here 1 and 2 is lower than maximum value from the integer and so we'll be deciding to process this nodes further and so we add those in the queue with adding those we also update the distance in the distance or effort in the effort matrix next thing we pop is the one that has the minimum distance in this priority queue while we pop from the min hip the one with the minimum distance should be popped and this gives us this particular thing from here we can go in this three directions and similarly as we had calculated the distance we will calculate over here also for 0 comma 2 it would be maximum of either 1 or 2 minus 2 which gives us 1 similarly for 1 comma 1 it would be maximum of 1 or 8 minus 2 which is 6 and similarly for 0 comma 0. now what are the nodes that we can process all the nodes and so we add all of them in the priority queue and we update their distances in the effort matrix again we'll pop from the min heap and again we'll check the distance and update that in the effort matrix and add the ones that we need to process in the min heap we will continue doing this particular thing till we reach our final cell so over here in this particular case we can see that we get a distance for 0 comma 1 and 1 comma 0 as 1 and 2 but if we see in our effort matrix it is already filled with the same distances so do we need to process them no we can just move ahead and now again over here the 2 comma 2 would need to be processed and so we add that in the priority queue and move ahead now we take this one and here we'll process the node for this particular cell and we'll update the effort for this as 5 is minimum how did we find this 5 is maximum of either 2 or the difference between 3 and 8 which gives us 5. so we update this cell and we add the remaining values in the priority queue again we go ahead and pop and add whatever we need in the priority queue now again we do the same and keep adding the elements in the queue now this time when we pop we get an element which is the last element and as we have reached the last cell thus we stop and we return the distance that is stored in the efforts matrix for your so while we reached here this distance got updated to 2 and that is our answer so i hope you are clear with what we are doing in this particular approach now we'll go ahead and code this one okay the first thing that we are going to do is take variables m and n that will represent the rows and column length after this we will be taking an efforts array and we'll fill that array with the maximum value from the integer after this we'll need a priority queue and we'll add the first initial value in the priority queue in this priority queue we are taking an ordered priority queue that will be ordered by the first element from this integer array that we are taking so this integer array would be representing distance row and then column after creating this we'll add our initial value so now comes the looping part while the priority queue is not empty we'll first pop an element or pull an element so int minimum i'll take is equal to pq dot pole from this minimum will extract the distance row and column after this we first check whether this distance is greater than or less than the effort value that is present in our matrix if this particular distance is greater than the one that is present in our effort matrix we do nothing but continue and if this is the last cell we just return the distance if this is not the case we will be going in each direction so for that let's take the direction array so these would be our four directions in which we'll be going and over here we'll go in each directions so for each direction in dir we will calculate the new row and new column so after that we'll first check whether this new row and new column is in our range so for that we say if new row if this is the case we'll be finding a new distance it would be the maximum of either the distance or the absolute difference between the new and the old cell once we have this new distance we check if it is greater than or less than the value present in the effort matrix so if this new distance is less than the distance that is present in the effort matrix for this particular row and column we need to update it and add that particular point or cell in the priority queue once everything is done we will need to return some value as it has and signature that has a return value of end so we can return either 0 or minus 1 or anything and that's all about the code let's run this and it gives a perfect result let's submit this and it got submitted so the time complexity for this particular approach is same as what is there for dikstra's algorithm which is e log v and here we have e edges and e is equal to m into n while vertexes is also equal to m n to n so the time complexity would be m into n log m into n and the space complexity is m into n to store this efforts matrix so now let's go ahead and see how we can use binary search for this particular question so we can apply binary search in this because we have the lower and higher bound for the effort that could have been spent the upper bound is the maximum value that would be in the heights array which is 10 raised to 6. so we can take that value and we can find the threshold value for which we need to find a path in this particular heights matrix and see if we get a path we can reduce the threshold and see if we get a part for that particular threshold so in that way we can apply binary search suppose if we had a threshold as 2 so in this particular problem we can get a path with the threshold as 2 and so we can say that okay there exists a path if we go below this if we say is there a path with effort as 1 in this matrix we would have got no and so we would have given 2 as our answer so that's the basic gist of the idea behind the binary search now let's go ahead and see how the code for that looks like so rather than typing the code out i will just explain you how the code look for binary search approach so this is the code and if you see we have the directions array that we had before here is the start that initial start is 0 and this is the upper bound which is 10 raised to 6 we have variables for mnn and this is what we generally do in binary search while start is less than end we find the mid and we have a boolean visited array over here to mark a position as visited whether we have visited a particular cell or not after this we would see whether we have a path in this heights array starting from 0 with the visited boolean array which is initially false for every particular cell and with the threshold as the midpoint that we have found out with this formula and given this initial value that is the value for the particular 0 0th cell if we have a path what we need is we need to shrink our window and so we do end equal to mid and go to the left half if there wasn't a path we would have gone to the right path and so we do start equal to mid plus one finally at the end we return start now while finding the path we first check the boundary conditions in the boundary conditions we have whether this has gone out of the range that is less than 0 or greater than the m and n values or if this particular cell was already visited or if this particular value or the distance was greater than the threshold if these were the cases we would have returned false otherwise if we reach the end point that is we reach the last cell then we return true and otherwise what happens is we'll mark the current cell as visited by marking this as true and then for each direction we'll go and see whether we have a path if we have a path we return true otherwise we return false so let's run this code for all the examples and this gives a correct result and let's try to submit this code and it got submitted so the time complexity for this particular approach would be m into n that is the number of edges log of the maximum value that we have that is this 10 raised to 6. and the space complexity still remains m cross n because we are taking a boolean visited array so that's it for today guys i hope you liked the video thanks for watching and i'll see you in the next one
Path With Minimum Effort
number-of-sub-arrays-with-odd-sum
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**. A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route. Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._ **Example 1:** **Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\] **Output:** 2 **Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells. This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3. **Example 2:** **Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\] **Output:** 1 **Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\]. **Example 3:** **Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\] **Output:** 0 **Explanation:** This route does not require any effort. **Constraints:** * `rows == heights.length` * `columns == heights[i].length` * `1 <= rows, columns <= 100` * `1 <= heights[i][j] <= 106`
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
Array,Math,Dynamic Programming,Prefix Sum
Medium
2242
1,007
Main Office How to Made Even Today Gum Road Police Problem Cheese Minimum Definitions for Equal Work for the Calling to Top and Bottom Work subscribe our YouTube Channel and subscribe to the Page if you liked The Video then subscribe to A Suite Problem Earth Lucerne Aayi Ho To Please Like and Subscribe That Suji Beneficial Okay The Worst Possible Dharti Effective Subscribe to 102 Channel And Subscribe Must Subscribe Maybe And This Namah Shivay Om Namah Shivay List Ek Pal You Live Wallpaper Relative Working For A Good Cause Subscribe Our Video Shooting Complete The Road To Subscribe To Hai Ki Dekhter Notification Loot 2 Minute Tak To The Subscribe Like And Subscribe To The Channel The Video Then there is election electrolyte in a quarter inch, it is productive work, if you have not subscribed to suicide note yet, then subscribe and subscribe the Channel 's bottle, hi is equal to 's bottle, hi is equal to 's bottle, hi is equal to phone number one, okay, so do not forget to subscribe to so many photos, love you. All Subscribe subscribe and subscribe this Video Please subscribe and subscirbe Subscribe Apni Se Electronic Scooter Infinity Is Account Me Encounter Infinitive + Vitamin B2 Will Not Be Infinitive + Vitamin B2 Will Not Be Infinitive + Vitamin B2 Will Not Be Entertained Subscribe This Subscribe For Latest Video And This Is Hey Chirakut Poonam Par Robbers Bigg Boss Subscribe Please subscribe this channel Absolutely Subscribe Allergic reaction happens which is next in this Islamic history video simply will not be produced I will do ok number 355 11021 Subscribe to the channel There was a meeting on your wi-fi Must be such a boat Lift Sister Don't Forget To Subscribe More YouTube Channels Subscribe To Hai Alsi Flash Light Of My Life Is My Number To You Ki Hey Manav Tu Main Din Bhar Lutyens Zone Mein Kounsi Konsi Plus Ok Video Please subscribe Free Not Acquainted With This Entry Was Posted To Subscribe To That Remedy Request O Love Oo That Dalit Oppression Kilo Hai Ko Ineligible Persons Were Present If You Like Settings Close Thing Possibility Of Namo For 10th Question Number On Individual Members It Is Difficult To Have A Positive Death A possibility number one ok sorry for this is the president of you good night in all like and subscribe to e-mail p e-mail p e-mail p a model se aisa aur us kismat top isse bottom toe by this 8 - w se left plz 8 - w se left plz 8 - w se left plz subscribe for Plus so that subscribe to Bigg Boss Do n't forget to subscribe to the skin, thumbs up only, value possible in dabi, half an hour should I send to school that suji add plus inch plus pinpoint main jodhpur map and so please like share and subscribe our subscribe do
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
1,641
all right let's talk about a consorted vowel string so you are given individual ends or return a number of a string length of the n that consists only vowels a l u and are less graphically sorted so this is the definition of the how you sort of screen so i will just quickly explain again so you have an au ui and then you want to generate a string that is less graphically ordered so if your equal to one is definitely just return the character itself right so it's going to be a individually e individually i individually or individually and u individually so that's five but when i go to two right when i go to two we also need to think about the lesser graphical order right so it has to be was from smaller graders right so eight and a penny one right hma it can be right how about e can you obtain a no all right this is not that's graphically ordered so it can be e i o u and how about i start studying for i or you right so every single time you just have to start with your current index i'm turning out to be on and traversing again traversing through the end right now this is pretty much the solution so let me uh demonstrate the first one the first solution i'm going to char array and i'm going to uh create a mouse and i will say new chart a i return the function so i need to have a result and in this case i'm going to traverse my mouth with mouse and then i will just keep adding my pumps for my ball and my microphone so this actually means i use my current position for this vowel right and uh four minutes for how many times a minus one time this is because i use this volume represent fun time and if you're playing for my helper function i know a minus one time all right so let me write the problem on editor character uh this will be last shot i'll tell you what happened so what does last charming i definitely need to compare the current chart with the with about with the vowels char right because i want to know am i allowed to obtain so um here is this so the base case for this one if i is actually equal to zero i can know the last chart will be the only chart you need to return so this is length of one right so i need a return value for this function now i need to traverse my vowel with the mouse right and i need to see if this file is very equal to my last chart if this is true i'm going to swap result perfect for trunks and my last chart will be about and then there will be unmarried so i will keep equipment every single time right and this is pretty much the solution all right so if you see the time this is going to be the worst this is because what traverse every single ball this is all of five but how many like how many times you call for the count this is going to call for earned time for every single bar right so this will be what all of um to the power of phi right so uh here's a diagram so if you have a e i o u right and film very single character and you are going to call aelu again right this is how it is right you have to double check it and yeah so long right and this one so on right so this is pretty bad but it passed a test but i'm still going to talk about the timing space the time is although five times five to about five to a power fund right to the power and the space is one the space is uh this is a space you can say 05 which is stored in the array of about but that's fine and let me tell you another solution so uh using the recursion uh and starting from 2d recursion butcher so here is the problem so i will have a 2d to the array so my rule will be on my column will be mouse but in this case i'm going to just uh add additional row and column so i'll start from zero by one two three four five right and this is zero for n and one two three right and so on right so for every single time this is how it is and in this scenario the one two three four five represent the possible character you can append to the table so what does this mean how many way you can append only one character into a string that's for you right you can attend you eu a u i u so on right you this is only for this one you cannot say a right you're gonna you cannot have a right here this is not a lot you cannot say you a ua does not allow right so in this one in this table the in the index sorry the integer represent the power like the possible value can append to a string so this is you this is what for you this is i for you e i o u and a l u right and this will be it now if i equal to one if not equal to one like you need to know like how many uh how many way you can return so if i input one then the thing about it is that you can only obtain you to yourself right so which is you now all you this is two this is three this is four this is five and if you see this pattern you're going to return five with n equal to one right return five angular one but this is about equal to two when equal to 2 this color is better when equal to 2 i need to know like um when my m minus 1 and the vowel allow so this is you right so uh for angle 2 and this position is you right and this is going to be one way only right how about this o u and you can have u o u and uh o ano what else you don't have you all right so this is three all right so uh this is if you notice you're adding the top and left to the current cell and this is going to be what six is going to be 10 this one is 15 and this is the solution right 15. and this is pretty much the 2d okay let me just stop putting and maybe you put the new engine on first one and then six i'm going to return an audio for my helper function we use the same name and pressing from passing the valve which is high i'm passing the dp so i was probably insane in turn in browse in 2d array so if and if i go to one right you just have to return out i don't care right and if mouse equal to one and that would be only character you need to return right and then if vpa earn involves it's not equal to zero you will return vpn about and i need a return value so i will return results right so for every single uh um spiritual right you need for your upper function and then sometimes you have a minus one right and then you have to pause with mouse if you use this curve now but it's still traversing the rest of the character and this will be right and i need to assign my dpn involved right you go to regal so uh you can short this to go here right and let me want to select revolution this is what even uh sorry one more thing where is the arrow 16 uh let me think about this oh okay i will uh i will i'll do this anyway all right uh you don't need a plus equal you will just need to say equal oh i thought i did this all right anyway they just submit all right i still pass the piss but you need scenarios faster because i memorized this right so i would name definitely know the table and i would just have to return and uh let's talk about time and space it's just 11 times 5 right by n and the recursion is going to traverse every single table right for sure and that would be fine as well but you can make a short you can minimize to all of them if you want all right this is 2d let's talk about 1d a little bit easy so here is it equal to zero and then and you go to one equal to two i have a zero one two three four five all right so you can represent a l u in this case a l o u right a e i o u let me just quickly draw char draw the diagram aelu okay here's a different color okay so i'll initialize my uh 1d ddp so i will need a one just initially so we're only equal to one how many way you can um add into the string for n equal to one so length of one is what only a then over one for e is e right and this is e i mean one sorry and okay this is wrong the reason why i say wrong is for one ddp you need to keep adding for your uh summation for current uh current in this table so uh you we definitely know uh then for one for e is one but we also need to plus the previous one so which is two then of one for i is one so plus the previous pre previous one is two so which is three four five so when you go to one you just have to return the last index from your one dbp so which is five how about only two and let's think about this so angle two using the same idea you need to what you need are you above and left this is three this is six this is ten this is fifteen all right so this is the solution so how do you actually do this uh a little bit super simple so um is when k equal to one okay less than equal to five that will be for the ball about right okay plus first and then dpa epa1 dpha first equal for simple dpak management and i'm not done yet this is because i didn't initial like this and then this uh foreign time you will have a traversal and then for the character uh erase all the fives right uh this is the fast fastest for sure so they talk about time all of um finds all of five right so uh fair which is all of our own all of them and network space is although six probably right you can say constant doesn't matter but i would say all of six and uh this can be uh if you don't know this right this can be doing a 2d 3d array for sure i passed in the 2d array i know i'm plus 1 is 6 right i travel i initialize my the first one the first will be one and then i started from 1 to n and then from 1 to 5 four about and then i would just keep adding my top and left right top and left and then uh this is the return value uh dpn and then practify right if you don't believe it i just want it and this is just slightly worse because you when you use the space it's all the fun time slide but for the time it's going to be the same for the 1d array right all of 5 times five times right and this is solution and i know this video is long and i really don't recommend you to watch a long video for the solution the show the better and definitely the police should be the uh the first scenario thing you have to talk about right so i thought this is pretty good be honest and if you feel helpful uh leave the like and subscribe if you want it and i will see you next time bye
Count Sorted Vowel Strings
countries-you-can-safely-invest-in
Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._ A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet. **Example 1:** **Input:** n = 1 **Output:** 5 **Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].` **Example 2:** **Input:** n = 2 **Output:** 15 **Explanation:** The 15 sorted strings that consist of vowels only are \[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\]. Note that "ea " is not a valid string since 'e' comes after 'a' in the alphabet. **Example 3:** **Input:** n = 33 **Output:** 66045 **Constraints:** * `1 <= n <= 50`
null
Database
Medium
615
434
foreign welcome back to my channel and today we are going to solve a new lead code question that is number of segments in a string the question says give it a string as written the number of segments in a string a segment is defined to be a quantity a sequence of non-space quantity a sequence of non-space quantity a sequence of non-space characters let's start solving this question and just before starting to solve this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so we have to just return the segments in a string for example here the segments will be would be five one two uh this would be two this will make us three and this would make us four and this would make a five fifth segment so this is the thing we have to do here so let's do here and we can just say that s is equals to s dot split which will just split the hurry in segments and I will just return as uh Len this will give me the answer so all right guys this was all in the question I hope you have understood the question it was quite straightforward and thank you guys for watching it watching the video and if you like the video please do subscribe to the channel hit the like button and comment in the comment section that you have liked the video thank you guys for watching it see you next time
Number of Segments in a String
number-of-segments-in-a-string
Given a string `s`, return _the number of segments in the string_. A **segment** is defined to be a contiguous sequence of **non-space characters**. **Example 1:** **Input:** s = "Hello, my name is John " **Output:** 5 **Explanation:** The five segments are \[ "Hello, ", "my ", "name ", "is ", "John "\] **Example 2:** **Input:** s = "Hello " **Output:** 1 **Constraints:** * `0 <= s.length <= 300` * `s` consists of lowercase and uppercase English letters, digits, or one of the following characters `"!@#$%^&*()_+-=',.: "`. * The only space character in `s` is `' '`.
null
String
Easy
null
395
hey what's up guys this is chung here so today let's take a look at it called problem number 395 longest substring with at least k repeating characters i mean this is a very interesting problem to me okay so the description is pretty short like given like a string s and the integer k return the length of the longest substring of s such that the frequency of each character in this substring it is at least k so some examples here right so the first one is we have 3 s here and the k is equal to 3 and the answer is three because the longest substring right whose i mean the frequency right for each character is aaa and for example two here in the example two here we have five right that's going to be a b all right so i mean i think most people can just think can come up with a sliding window approach right i mean i think it's kind of also obvious that you know it's it should be using the sliding window because you know at least for this kind of uh longest substring with some conditions right like either the uh the frequency or the maximum numbers in it right so we already use that we usually use the sliding window and same thing for this problem you know but the tricky part for this problem is that you know if you're trying to use the uh the exactly same conditions as the uh to maintain the sliding window it will not work so and why is that because you know just think about the uh the conditions to keep a sliding window so what kind of condition can maintain a sliding window just okay so the conditions to maintain sliding window has to be whenever we're expanding whenever we expand the sliding window that's number that condition should be like increasing right and when we shrink the sliding window that condition should be decreasing right something like the you know the total numbers in the sliding window or the maximum number in a sliding window given like uh all positive integers right or something like you know the uh the total numbers included in the total letters including the sliding windows right those things can be used as a condition to keep the sliding window but for this one for this problem you know let's say you if you're trying to use the uh this the maximum i mean the minimum right the minimum frequency in a sliding window for each character it's at least k if we use this one to keep a sliding window can we can't can it meet our requirements and you know i mean it's obviously we can't because you know when we are like increasing the sliding window you know let's say we have a b c right let's see we have this one you know let's say the sliding window is it's right here that's going to be our current sliding window and if we are expanding the windows now we're at c here right if i see here so the minimum the smart the minimum frequency in the sliding window become now change from three to one right and what and the other way same thing right when we shrink the sliding window let's say that we are like let's see the current sliding window is it's right here that's the current starting window right and so the current uh minimum frequency in this sliding window is one right but if we shrink this sliding windows now that now the uh the max the smart the minimum's frequency becomes to three so both ways you know we have a opposite object like changing right we have a it's changing in the opposite direction then the uh then our definition of sliding window right that's why we can't just simply use the at this condition to maintain the sliding window so which means that we if we want to use a sliding window approach we have to come up with like a increasing conditions that we can use and i think i already mentioned that one of the conditions we can use is that you know i mean the total numbers the total unique the totally unique numbers of the ladders in business sliding window that's going to be that's definitely a valid condition to maintain a sliding window and so which means that you know we just need to get you know the total numbers in the sliding window unique numbers since it's always they're all like lowercase of english letters right it's like the uh it's what it's the uh at most we have 26 distinct letters right so we can just simply try so basically which means that we need to try all the possible at most we will need to try all 26 ladders as a condition to maintain a sliding window and then we use that conditions to traverse the entire stream and whenever we have a valid sliding windows right basically we just track all the elements in the sliding windows and if the uh if the minimum and basically if all the uh if all the frequency within sliding window has the uh if sorry if all the letters in the sliding window has at least frequency out of k right that then that's going to be our approach all right cool so now let's try to run it right now let's try sorry let's try to start the coding here and to get our for loop range here i'm going to get the frequency you know i'm going to get the total number of the uh basically the max number of the unique characters right so i'll simply use a frequency equals to counter dot s right and then the maximum numbers right will be what will be the length of the frequency right so that's going to give us the uh how many distinct letters in this ass here right and then uh we can just uh we have answer yeah first we need to have answer equals zero right and then like i said we simply loop through the numbers in the range of one two max numbers plus one right that's gonna be our for loop right for each of the numbers so that we can use this number as a condition to maintain the sliding window right because we need like a fixed condition to maintain the sliding window in this case it's going to be the unique the distinct letters in the sliding window okay and so within that for loop here we need like another like counter right to help us keep the frequency so that we can update our answers now we have a left equal to zero now since we have like uh conditions that sliding window can use now the rights will just be a regular sliding window templates right so we have a range n here and then so like i said so first we always increase the sliding so you expand the sliding window and then we update the counters right by s dot right with s right and then we do a plus one and then we will try to we'll check the sliding window right maintain the sliding window yeah sliding window so by doing this while loop here while the length of the counters rise if this one is greater than the num right and then okay we'll shrink right we'll stream we'll do a left corners that as the corner starts as left minus one right and then the if counters dot as left is equal to zero right and then we do a delete right to delete i'll just copy and paste this one here that's how we uh maintain the sliding window right and then of course don't forget to increase the left by one so now we have a valid selection window now we just need to check now with the valid right sliding window we check the frequency right so i mean here i'll just use like uh i'll just use like brutal force way to check that basically we can simply use like all right basically you know in python this these are functions just give you check all the uh everything in that iterator right and they give and if any of them is if all of them is true and then it's to adding them is false and then it is just false so i just use this one you can of course use using a while loop to do this with the flag right so here we of key and count in counter dot items right so basically you know for each frequency in the current sliding windows we check if the count is at least k right sorry four i think four this one yeah and if all the uh the characters has this one greater than k then we know okay we have find the uh the answer one of the answers so that's in which update max dot answer dot write minus left plus one right and then here in the end we simply just return the answer yeah i think that's it let's try to run the code here oh sorry i think i forgot to uh to define the ends at the beginning here so n is the length of s all right this doesn't look right limit exceeded did i miss anything oh yeah okay so accept it submit cool so all right so it passed um yeah and how about the space time and space complexity right so i think for the time complexity so first we have like this one right we have the max numbers which is what is 26 right so the max the maximum distinct letters we have is here is 20 is 26. so i'm assuming we can ignore this for loop here right and then the only thing left is like this for loop so this is of course a off n here right and then here is also like a 26. here we have a while loop here but this one will not be since it's like a sliding window so this is like a 001 yeah i would say this time complexity for this sliding window is it's a it's o of n you know yeah and the space complexity is we have frequency right just frequency the uh this is the at least 26 so it's like one right here we have a another counters here that's also like a 001 because at least we have we will need at most we need 26 here so yeah so i think space complexity for this one is o of one cool i mean yeah i think that's it for this approach right sliding window project i mean just to recap you know the tricky part is that we cannot use the uh the same condition that the problem is asking us as a condition to maintain the sliding window so we have to find another condition to maintain the sliding window and to do that we have to have a for loop because we want to include all the possible scenarios in for the sliding windows right that's why we need to look through all the possible other possible uh the basically the unique not the unique ladders right and for each of the unique ladders we use it as the condition to maintain the sliding window and then we just do a brutal force track for each of the valley sliding window and yeah and there you go so and that's that actually you know for this problem there is also like a very interesting uh divide and conquer solutions you know even though the time complexity for that is going to be o of n square but i still want to mention it here you know since it's very it's kind of interesting and also a good practice to for the uh for divide and conquer technique basically the way it works is like this you know let's say we have a b c b a c cd something like this and the uh actually so here i'll do a here and the k is 2. so the way divided conquer works is that you know we uh we have to find the root to do the partition right and for this problem we partic we part we do the partition until we find a valid substring whose frequency whose the who's each slider's frequency is at least k which means at the beginning we start from zero and from zero to n minus one and then basically we're gonna have a left for each of the divided conquerors we all we always have the left and right parameters in the recursive function right and then from left to right we'll calculate the count we calculate the frequencies for each of for we calculate all the frequencies within the range from left and right so at the beginning we have zero to n minus one and then that's going to be the prop preprocessing and after that you know we're gonna loop through this left to right again and for each of the uh the ladders we checked we check its frequency if that if his frequency is smaller than k then we that's that location will be our pivot point basically we're going to be we're going to split the uh we're going to split the entire string from this location because we know this slider will we have to exclude this letter from the substring right so which means that you know now we have what we have this as you guys can see here so the c is oh sorry so actually yeah this is not a good example so maybe i should have it here so i should not have this c right here let's say this there's a e here so which means that you know from c here right c frequencies is one which is smaller than two that's why you know whenever we see a like a frequency was a ladder whose frequency smaller than k would divide this string into two half so this is going to be the first half and this is going to be the second half and for those two sub strings will basically will call the same functions again partition right okay call same functions again and then we'll do a counters for this substring and then we'll check if there's any character who's who is not satisfying this k as a frequency condition and then we'll keep dividing until if there's nothing to be divided and then we know okay that string is a valid string and then we can simply uh do what we can simply return the length for that substring and then of course since we're dividing into two substrings right we'll we will and we're getting the longest right that's why after the split we'll do a max of these two substrings and then we'll return the maximum value among those two substrings okay so i mean the implementation is pretty actually surprisingly uh shorter you know surprisingly short than the uh than this one you know so i mean like i said we just need all we need is just a partition you know partition like a left and right and then the uh so inside each of the partitions we're going to have like a default and dictionary int right and then i count the frequencies inside the range here in the range of left to right plus one because i'm including the i'm including this right the right pointers and then we have a counters dot uh s i right and then nice i do a plus one right and then here i'm going to do a like middle right i'm going to have a middle in range of left to right plus one right and then if right if the counters if the middle the counter of the middle is smaller than k then we need to return the maximum of partition of left middle minus one right since we're excluding this middle and then the other side is partition of the middle plus one and then to the right okay right and then in the end we return what the right minors left plus one right so basically you know we keep splitting these things into two half and then we are getting the maximum out of those two halves until we reach the until we don't have to split it and then we simply return the right miners left plus one right so that's going to be our conditions to stop this partition and then here we simply do our what the partition return the partitions from 0 to n minus 1 to yeah so to n minus 1. so we have these things and minus 1. that's it okay so if i run the code here partition i think let me spell something here yeah partition yeah okay all right cool if i submit these things let's see yes it also passed but it only beats like five percent of the submission here because you know because the time complexity for this thing is like i would say it's close to uh the worst case scenario is still like o of n square because even though we are like trying to cut this thing in half right but in still i mean the worst case scenario is that we always cut this strings from either the last one or from the first one or from the last one right that's why you know we're not we're only reducing the size of the problems by one not by half that's going to be the worst case scenario that's why the total time complexity for this one is still like of n square but the uh the best case scenario is the like it's all of like what n log n right which means every time we cut it in half right that's why we have a login i think we can still also do some like optimizations or for this kind of partitions but i'm just showing you guys the basic idea of the how this divide and conquer solution works and that's there and there you have it all right cool guys i think that's it i want to talk about for this problem and thank you so much for watching this video and stay tuned see you guys soon bye
Longest Substring with At Least K Repeating Characters
longest-substring-with-at-least-k-repeating-characters
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`. **Example 1:** **Input:** s = "aaabb ", k = 3 **Output:** 3 **Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times. **Example 2:** **Input:** s = "ababbc ", k = 2 **Output:** 5 **Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 105`
null
Hash Table,String,Divide and Conquer,Sliding Window
Medium
2140,2209
1,710
hello everyone welcome to quartus camp we are at 14th day of june record challenge and the problem we are going to cover is maximum units on a truck so the input given here is a two dimensional integer array and an integer variable truck size where it represent the type of boxes and the number of units inside the boxes and the truck size and we have to fill in the boxes into the truck size that the truck size should not exceed with the number of boxes we put in and we have to return the maximum total number of units that we can put onto the truck so let's understand this problem with an example so here is a given input in the problem statement where we have three types of boxes where in type one they have one box and in type two they have two boxes and in type three they have three boxes and each box of type one can hold three units and type two can hold two units that is each box two units so total it has two box so two into two it can totally have four units and same way in type three each box can one have one unit and total of boxes are three and each can hold one unit so total it is gonna hold three units so now we have to fill our truck with four boxes max and we have to return the total number of units we can fill our truck with and that should be maximum so now we can pick the box number one of type one in our truck so that is gonna be of having units three so three plus so we have inserted one box into a truck so now our truck size has become three so we still have three more left to fill in our truck so moving on to a type two where we have two types of boxes and we are going to take all these two to our truck so again our truck is gonna fill with four units because we can fill two units and in each box of type two so once we put these two into our truck size will now become one we have only one box left to fill so now we have three boxes of type three so we can pick only one box out of this and here each box can have one unit so we can take one box of one unit so total of eight units we can fill in our truck now our truck sizes become zero and eight is going where output so how we're going to approach this problem is if you see the hints given in the problem statement they have clearly gave the idea of the solution that is we have to fill the maximum number of units to our truck which means we have to pick the boxes with maximum units first and then move on to the minimum ones so to do that we are going to sort the given array based on the number of units in the boxes and in the non-increasing order boxes and in the non-increasing order boxes and in the non-increasing order so once we saw that way we are going to pick the boxes in the front or in the first indexes then move on to the later ones so now take the same example our truck size is going to be four so this array is already in a sorted order in the example itself but consider we have sorted it based on the number of units so now we are going to take one which is which will give us the maximum units of three and again take two from the second type and we have filled a truck with three boxes by choosing the first one and the second one now the last one is left with three boxes but we have space for only one box so we are going to pick that one from this box and add its units to the units and return it so hope you're understanding this logic you will understand once we complete the coding part so before getting into the code this is going to work in big o of n login time complexity where we are going to sort the given array first and that is going to take log n time and then we are going to iterate the sorted array and add the values so that is going to take big o of n time so overall it is going to take big o of n log n times complexity so let's go to the code now so yes as i said we are first going to sort our array based on the second value in our given array so once we sorted the array let me declare my max units and this is going to be the output we are going to finally return now i'm gonna iterate my sorted array and i'm going to check if my truck size is greater than or equal to box of 0 is nothing but the number of boxes of that type so if it is greater than we are going to subtract the number of boxes in the front or in the sorted array so our max units is going to be the number of boxes into number of units we can put in that boxes so that is that will be box of 0 into box of one so once we calculate the number of units we are going to subtract the number of boxes from the truck size yes this loop is going to go until our truck size is greater than the number of boxes like i said once we fill our truck with three boxes from type one and type two we are left with three boxes in type three in that case our truck size will become one and our box size will be three which is nothing but three is greater than the truck size right now so in that case we cannot pick all the boxes of that type instead we can pick only what is left as the truck size so we are going to cover that condition here so we are going to calculate the max units which is nothing but what is the truck size left into box of 1 which is nothing but the number of units of that particular type and finally return max units so yes this is it let's run and try let's submit yes the solution is accepted and runs in seven milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Maximum Units on a Truck
find-servers-that-handled-most-number-of-requests
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`. Return _the **maximum** total number of **units** that can be put on the truck._ **Example 1:** **Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4 **Output:** 8 **Explanation:** There are: - 1 box of the first type that contains 3 units. - 2 boxes of the second type that contain 2 units each. - 3 boxes of the third type that contain 1 unit each. You can take all the boxes of the first and second types, and one box of the third type. The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8. **Example 2:** **Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10 **Output:** 91 **Constraints:** * `1 <= boxTypes.length <= 1000` * `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000` * `1 <= truckSize <= 106`
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
Array,Greedy,Heap (Priority Queue),Ordered Set
Hard
null
1,937
welcome to the problem 1937 from so in this problem we are given a 2d integer array where in general k the number of rows and columns equals eminent respectively and what we need to do is all about gaining as many points as we can by picking exactly one cell in each row and at this point you might say wait in order to maximize the amount of points we greatly need to grab the max in each row and you're absolutely right however there is a little extra condition which make this problem a bit tricky so what this condition is about well imagine for every two adjacent rows picking cells at coordinates ip0 and i plus 1 p1 will subtract the absolute difference between p1 and p0 from our score the following formula described that we need to find such a combination of cells where the sum of points will be the max with the given condition also we do have some restrictions along with this problem the important thing to know is that we'll not have any problems with allocating memory for the matrix and the points are non-negative integers from 0 points are non-negative integers from 0 points are non-negative integers from 0 up to 10 power by 5. so let's take a look at some given examples in order to understand the problem statement better in this case the combination which gives us the max amount of points is the following and the sum of those points is going to be equal to the nine so for the second one the max combination the following cells and the answer which we need to return is going to be equal to 11. all right let's have a look again at our example it is always good to start with something simple in order to check whether you've got the problem statement or not whether you're thinking the right way or not even if you know the problem take your time to verify your thoughts okay so here p max is nine right but how do we know which cells to peak okay maybe it's a good idea to generate all possible combination of cells and return the max one among them it looks good let's make it happen by picking the first cell in the first row we do have three remaining cells to pick in the next row right well let's simply pick the first one as well and for the third once again we do have three cells to pick let's pick the first one again so our first combination gives us five points so now let's generate another combination in this case we do have the same cells for the first and for the second rows but now in the third we are picking the second one because the first one is already picked for p1 and for this combination we have got two points and so on eventually we'll end up with 27 combinations for this example and after generating all possible combinations we simply need to grab the max one as we decided earlier and that's pretty much it well if we are talking about the efficiency of such an approach the time complexity is obviously going to be exponential right but can we somehow turn it into polynomial time complexity so let's find it out okay we are bringing back our given table and trying to optimize our previous approach which runs on exponential time right well if you already have some work in brute force solution always try to think whether it's possible to cast some useful information about the data to prevent some blind brute force but what exactly should we cache all right let's create some gp metrics where dpij stands for the max points we already gained at points i j mostly caching requires something to start with well after picking a cell at points zero we don't need to pay any cost right therefore the max points at point zero is going to be one and the same for the second and for the third in the first row so these are our base values right and remember that we are going from the top to the bottom if we are trying to go from the bottom to top the base values are going to be equal to the last row of the points matrix because we are starting by picking those cells now by having base values to work with we simply need to compute dpij for the rest of the cells once again what is dpij it is the max points we already gained at points i j okay let's try to compute the max values for the second row well in order to do that we simply need to answer the queries like how many points we can gain if we somehow came to the current cell from 0.00 0.01 or 0.02 in this from 0.00 0.01 or 0.02 in this from 0.00 0.01 or 0.02 in this particular case well it turns out that the max points we can achieve by coming to this cell equals two because we already have one point for being in the points one zero and another point from the previous row all right what about the second one here we can get five points because we are standing in that cell and two from the previous row and so on so after such computation the answer for this whole problem equals the max points in the last computed row well let's complete our computation and see what happened so as we decided earlier the answer is the max in the last computed row so in this case just nine okay so the time complexity here becomes of f of m times n times g of n where g of n described that in order to compute the max points at a specific cell we simply need to get the max from the previous row and it takes linear time for each cell which we are computing for well that's a good one because we hugely optimized our approach by simply saving max points we already gained i also do have a cpp code listing for that described approach of course we'll get time limit exceeded for that by now but that not the point here most important is to strongly understand the logic behind caching i strongly recommend you to implement it yourself in order to have a better vision as we decided earlier we somehow need to figure out about the base values for our dp then it's all about computing dpij for the whole points matrix and getting the answer in this case it's just the max in the last row by the way if you look closely my dp matrix is a copy of points well you can do that as well because it doesn't really matter if they are equal to zero or just some random values most important is to get our base values now it's time to make it more efficient than that by simply getting rid of gfm from the time complexity before diving into our most efficient approach i do have a quick intro about how precomputation might be helpful especially where we need to deal with some queries there are popular precomputation techniques like computing prefix sums computing prefix product prefix source some prefixes on strings and etc which significantly optimize the time complexity to operate with queries so it takes one time to compute them and after that we can easily get what we computed earlier for instance the sum on some specific prefix of an array or the maxwell in the prefix or on the suffix of the given immutable array that's exactly what i'm going to show you right now imagine having some random integer array and along with it we do have some queries such that the max in the prefix is basically the max from the beginning up to some ith index and the max in the suffix where it sends for the max value from the i position up to the end of the array okay let k stands for the amount of such queries in the usual case to answer such queries requires linear time per each query but what happens if we decide to pre-compute what happens if we decide to pre-compute what happens if we decide to pre-compute it once and after that just simply getting an answer for the constant type period query in order to do that let's say prefix max i it is exactly the maxwell and the prefix and suffix max i max well in the suffix let's see how we can pre-compute suffix let's see how we can pre-compute suffix let's see how we can pre-compute them in order to make it easy to implement we'll have an additional element in the beginning basically it means that the max value before the first element equals zero so the max before the second element in our array equals the max between the previous value and the current from our array and so on well in case of the suffix max we do have the same concept but here since we need to keep an answer for what is a maxwell on the right side from the certain element we need to start from the end basically for the prefix max we are keeping our max values going from the left to the right but for suffix just vice verse i'll provide call listing on how to basically compute them so here is just basic initialization process then computing suffix maxes and prefix max's as well of course there are a bunch of ways to compute it but i personally prefer adding an extra element in order to simplify working with indices it's getting hard to work carefully with indices when it comes to computing 2d or multiple dimension prefixes or suffixes okay now comes the beauty of this problem once again we do have our points table ndp table as well and we are going to try to compute those dp values all right the base values are here and we are ready to start let's pick some random cell from the current line which we are calculating for we already know how to calculate that in linear time while basically looking at the previous row and trying to find the best cell to come from which is maximizing our points at the current cells but what about the constant time per query okay we do have six available cells to come from right but if we look closely maybe we can somehow operate with only the left and the right blocks of the previous row just instead of checking every single cell but what are those left and right blocks well it turned out that they are exactly the prefix in the subject of the previous row we already know how to pre-compute the prefix maxes right so pre-compute the prefix maxes right so pre-compute the prefix maxes right so let's make it happen here after looking at the formula for prefix maxes you might ask why we're subtracting 1 from the prefix max of j well it's because remember we need to pay a cost whenever we are about to shift either to the left or to the right side so using the same logic let's compute the suffix max's as well after doing that you might see the main reason behind this beautiful approach i'm pretty sure that you already know what i'm talking about right now so let's go back to our highlighted cell basically we want to compute the max amount of points we gain at the highlighted cell right so in the previous approach we were trying to get the max by looking at every single value from the previous row right here we don't need to do that because we already have an answer for queries like what is the max on the left and on the right side from the highlight itself therefore we simply can grab the max between them and add it up to our overall points at the certain cell it's hard to believe but that's pretty much it this is the excellent problem to represent the power behind of precomputation techniques once again we do have some base values after that we are computing our prefix max and suffix maxes based on those values and we are ready to compute our dpij for the i throw and after computing the whole dp table you know what to do right it's all about grabbing the max from the last computed row in our dp table and that's would be the answer for the problem i've prepared the code listing for this approach as well but it's not necessarily needed because you already know how to compute the pref max in soft max's right basically the problem is all about pre-computing them carefully pre-computing them carefully pre-computing them carefully so the first part is all about basic initialization and then by having base values we simply can start to compute dpij for the rest rows well here i just created left to right and right to left arrays as prefix maxes and suffix maxes respectively but you might notice that there is no extra element there as i said it's also possible to compute them and i just wanted to show you how to do that in this way as well but you can compute with an extra element in the beginning as well it's pretty much okay after that we do have our prefix and suffix precomputation and the last part is like all about computing our actual dpij values for the current row eventually we have our answer and we are ready to return it as a maxwell and the last computed row of the dp table that's pretty much it i hope you guys enjoyed this gorgeous problem and wish you good luck on your journey
Maximum Number of Points with Cost
maximize-the-beauty-of-the-garden
You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix. To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates `(r, c1)` and `(r + 1, c2)` will **subtract** `abs(c1 - c2)` from your score. Return _the **maximum** number of points you can achieve_. `abs(x)` is defined as: * `x` for `x >= 0`. * `-x` for `x < 0`. **Example 1:** **Input:** points = \[\[1,2,3\],\[1,5,1\],\[3,1,1\]\] **Output:** 9 **Explanation:** The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0). You add 3 + 5 + 3 = 11 to your score. However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score. Your final score is 11 - 2 = 9. **Example 2:** **Input:** points = \[\[1,5\],\[2,3\],\[4,2\]\] **Output:** 11 **Explanation:** The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0). You add 5 + 3 + 4 = 12 to your score. However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score. Your final score is 12 - 1 = 11. **Constraints:** * `m == points.length` * `n == points[r].length` * `1 <= m, n <= 105` * `1 <= m * n <= 105` * `0 <= points[r][c] <= 105`
Consider every possible beauty and its first and last index in flowers. Remove all flowers with negative beauties within those indices.
Array,Greedy,Prefix Sum
Hard
null
135
hi guys my name is khushbu and welcome to algorithms made easy in this video we will see the question candy there are n children standing in a line each child is assigned a rating value given in an integer array ratings you are given candies to these children subjected to the following requirements the first one is that each child must have at least one candy and the second one is that children with higher rating gets more candies than their neighbor return the minimum number of candies you need to have to distribute the candies to the children so here you are given two examples in the example one the ratings are one zero and two so the candies that you can allocate over here are two candies to the first child because it has a higher rating than its neighbor and its neighbor will get one candy because it has lower rating than both of its neighbors similarly the third child will get two candies because its rating is higher than the neighbor so the total number of candies become two plus one plus two which is five similarly for example two here are some constraints that are given to us and so now let's see how we can solve this question so i have made up an array which has these rankings and now i need to find the number of candies i require to distribute amongst these children the first thing that we need to keep in mind is the rule that each child should have at least one candy and the second rule states that the children with higher rating will get more candies than its neighbors including both left and right so by default each and every child must have at least one candy and now we need to see their neighboring values in order to find the number of candies a person will get so let's take the left value for this we are going to compare the ranking for the current child with its left neighbor and so in order to do so we will start from the first index and by default for the 0th person we will add 1. now when we compare this 3 with 5 we see that the current child have lower rating than its left neighbor and so we can give him one candy similarly with the next one since 2 is less than 3 there is no need to give more candies to this person and we can only give him one candy similarly with this one now when we come to this child we see that it has a higher rating than its left neighbor and so we need to give him or her more candies we'll just add one additional candy from the candy that this person has got so it becomes 1 plus 1 which is 2. similarly when we go to this person with 6 as a ranking we know that this person has a rank higher than its left neighbor and so we need to give him comparatively more candies than the person with ranking two so we give one more additional candy to this child next we go for five and since this five is less than six we do not need to follow the rule of giving more candies we can just give the person one single candy similarly with four and now with seven as this is higher than four we give this person one extra candy compared to the candies with person next to him so here are the candies that we need to give if we are taking the left neighbor into consideration now we need to do the same considering the right neighbor also and so what we are going to do is we are going to follow the same so we will start with second last person and we will find how many candies that person should get if we are considering the right neighbor so over here we will give one candy as a default candy to the last person and calculate the candies we need to give to all other children so as over here four is less than seven we just give one candy to this child similarly with this one too now 5 is greater than 4 and so we need to give an extra candy to this person from the number of candies the right neighbor has and so we do 1 plus 1 which is 2. similarly with this one now since 2 is less than 6 we give one candy to this child similarly we fill the array till the end and now we have two arrays the one respect to left and the other with respect to right now what is the number of candies that we actually need to give that would be the maximum number of candy when we take into consideration of the left and the right so that would give me this array which is max of left comma right so over here four and one so it should have four candies if he has four candies he'll obviously have one candy so we need to give him her four and similarly with others and the total for this becomes 21. so for this approach we are going to iterate over our array once from the front and second times from the back and we need to store the candies that a person should get with respect to its left and right neighbors and finally we can combine the result to find the actual answer so let's go ahead and code this one out and then we will see a more optimized version for this particular problem so the first thing that i need is initialize the candies and the second thing that i need is two arrays that would be storing the left and the right values and now let's fill these arrays with the default value that is one and now we'll start looping for left and right so let's start with the left one so we'll start with i equal to 1 and will go till n over here we check if the current index rating is greater than the previous give more candies or an extra candy so we give one extra candy otherwise we just give that person a single candy as the array is already filled with one we do not need to do anything but move ahead similarly we'll do for the right part also and over here we are going to compare it with the value i plus 1 and finally merge both the sides so in order to take the candies we want to take the maximum of the value in my left and the right array and so i'll take math dot max of left of i and right of i finally return the candies so let's run this code and we are getting a perfect result let's submit this and it got submitted the time complexity over here will be o of n for each and every loop and so the final time complexity is also o of n the space complexity over here is also o of n because we are taking two arrays of length n with us now how do we optimize this one of the optimizations over here is removing one of the array and playing with just one array with us because in the second array will only need the previous value and we can take the left value and update the same left array instead of having the right array finally we can just do a sum on the array that we have so i am not going to show this particular solution over here but rather let's move on to eliminate the space completely that is let's go ahead with o of one solution so here is the graphical representation i have shown for the rankings that we have so over here the first one has a ranking of five then 3 2 1 and we see that this is going up and down and forming a mountain and if you see the total number of candies a person is going to get that is also going to go in a mountain that is the person with ranking five will get four candies then the third then this one will get three candies and so on so this has a relation with it and so we can use this relation to solve this problem in o of one space we are going to divide this into different parts how we are going to divide this into mountains so if you see that this is a part of first mountain and this is a part of second mountain this is a plateau and this is another mountain that is starting so we are going to divide this into mountain and we are going to calculate for each and every mountain if you see over here till this particular one the number of candies that we are going to give to a person is 4 plus 3 plus 2 plus 1 which is sum of n that is n number of points that are falling on that particular slope so for that we are going to find the points that a particular side of a mountain is going to have that is the slope of the downward trend and the upward trends so we will have two variables that will store the number of points which are going upwards the number of points which are going downwards and this will in turn give us our result so over here we have divided this mountain around this two and one why are we not considering this one because this one is going to be considered in the next mountain and so we are not considering it in the first one so if we start from four there is one point which is going down the second point that is going down and the third point that is going down so for this part we have three down points and there is no up point for this particular mountain because this is half of the mountain secondly when we go over here we have one and two up points and one and two down points then there is a flat plateau and then there is one up point that we have now how do we calculate the result for calculating this result so when we are encountering another mountain that is when we are going from down to up or when we are going to a flat plateau at that time we will say that we are dividing the mountains and we'll calculate the number of candies in the previous mountain so over here as we had three down points so we'll calculate the number of candies so this becomes 4 plus 3 plus 2 which is in turn 6 plus 3 which gives us 9 next we go to this mountain and over here also we have 2 up and 2 down points and the formula is doing the sum of numbers till 1 to n for up 1 to n for down plus the maximum number of points we have in either up or down so that gives us 8 for this particular mountain and now what we have is a flat plateau and so what we do in such case is any which ways the person is going to get one single candy so this gets one candy and the next thing that we have is this last mountain so over here what we are going to have is we are going to have one up so that becomes this one point and now the second point is the maximum plus one for this peak because this is the highest one so that gives us one plus one and that gives us three candidates for these two people if we sum it up we get our desired output which is 21. so that was the slope method to find out the number of candies that we need to distribute amongst the people with the given rankings so let's go ahead and code it out and while coding it out we will see in detail how the conditions work so let's write the initial condition and now we'll take some variables so we'll take a variable up down and we'll take the variable for slope so we'll have a previous slope which will be 0 and will also have candies now we'll start looping on the array we'll start with i equal to 1 and in here we'll calculate the slope for calculating the slope we are not actually going to calculate this mathematical slope but we are just going to assign a value negative positive and 0 for the increasing decreasing and plane slopes so increasing slope becomes 1 decreasing slope becomes minus 1 and plateau or the plane part becomes 0. so let's find out we'll take a current slope variable and we'll write the condition based on the previous and current value so here comes the condition stating that if the rating of i is greater than the previous one we take the slope as one if it is less than the previous one we take the value as minus one or otherwise we take it as zero now comes the part of dividing the mountains so we'll divide the mountain on three conditions that is if we are getting a mountain like this that is the slope was decreasing and then increasing or if it was something like this that is decreasing and then a plane or if it was increasing and then a plane that is this condition in these cases we are going to divide the mountain so let us write those conditions so these become the three conditions previous loop is less than zero current slope is either greater than zero or equal to zero and previous slope is greater than zero and the current slope is 0. so in this condition we are going to find the answer and change r up and down to 0. so we update the candies and we do sum of numbers from 1 to n where n is my up sum of numbers from 1 to down and we'll add maximum of up and down for this we need the sum method so let's write that out and that's the sum method that is n into n plus 1 by 2 which gives the sum of 1 to n with this we do up equal to 0 down equal to 0 that is we reset the mountain parameters now we need to write the conditions wherein we are going to increase the up or down values so if the current slope is greater than 0 then we do a plus else if current slope is less than 0 we do down plus else we just do candies plus because we have got a plane surface wherein we have to give one candy to that particular child once we have done this we need to assign previous slope equal to current slope in order to go into the next iteration finally when we come out of this loop we again need to add the candies that are there for the last mountain and over here we do max of up comma down plus one while doing sum of a plus some of down finally just return the candies and we are done let's try to run this and we are getting a perfect result let's submit this and it got submitted so the time complexity for this particular approach is o of n and the space complexity over here becomes o of 1 because we are not using any extra array or anything else so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep folding
Candy
candy
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. You are giving candies to these children subjected to the following requirements: * Each child must have at least one candy. * Children with a higher rating get more candies than their neighbors. Return _the minimum number of candies you need to have to distribute the candies to the children_. **Example 1:** **Input:** ratings = \[1,0,2\] **Output:** 5 **Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively. **Example 2:** **Input:** ratings = \[1,2,2\] **Output:** 4 **Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. **Constraints:** * `n == ratings.length` * `1 <= n <= 2 * 104` * `0 <= ratings[i] <= 2 * 104`
null
Array,Greedy
Hard
null
143
hello everybody welcome to my channel let's solve the lit code problem reorder list so this is very famous problem and it make use of other list problems like finding a cycle analyst reversing a list and so on so let's read the problem statement and understand the problem given a singly linked list which is has the nodes l 0 l 1 l 2 up to l n minus 1 and l n and we have to reorder it into such that first l0 then ln which is the last most node then l1 then the second last mode node ln minus 1 and so on you may not modify the values in the list nodes only nodes itself may be changed so we do not have to modify the value into the list while we can rearrange the nodes so this is how the linked list problems are there so here in this example one we have four nodes one two three four if we reorder then one followed by four and then two then followed by three so this is the answer if we have five nodes here one two three four five then one then five this last one then two then last second last 4 than the 3 so how we will solve this problem so let us understand this over here so initially we have a list let's take an example of 5 node 2 or 6 node better to understand in the bigger list so 3 and then we have here 4 5 6 you must have understand why it is in the second row so we have to change do something with this second half of the list and then fit into the alternate node of our first half of the list so this is our first half list which is had is pointing here so first of all we have to reach to this node which is middle node and this node so somehow we have to reach the middle of the list so how we will reach of the middle of the list we will use the two pointers one is slow pointer which will increment by always one node at a time and another is a fast pointer which will increment two node at a time and the slow will start from the head itself if had is not null and fast is start with the head dot next if head dot next is not null so if in our list we have like no node and if we have one node so we will just simply return there is no point of reordering this list so we will put this base condition in our code now by using this we will reach to the middle of the list by using the condition like either the fast not reach to the null or and fast dot next not reach to the null so why using this silo will be here so this silo we reach here now one solution what we can do we know this slow from the still after the node from the slow we will add all this node this all node into our one of the data structure which will reverse automatically our nodes in the stack so we will add node four then five then six if we edit this using the stack help and we will mark this next is null here we will break this list here so that so we will break this list here so once we break and this next we will make the null here now once it's done we know this stack we have set of node from the right which is already reversed because of this stack and we have the first half of the list here now we can do one solution like we will iterate the node this and create a room here and pull pick the one node from the top of the stack and add this node here like let us create this here ah 1 then 2 then 3 we have this list and we know the head pointer of this list now we will take the 6 from the stack and we will make the one dot next to this node six and six dot next to this node two similarly we will get another second next node and then we will change this next to five and then this 5 to this 3 so then we will get the last node 4 and we will make this 4 2 here and this end of this null so this is the one approach of solving this problem like reordering the nodes but if you see the cost of time is o of n as well as the cost of space is o of n because we are using this stack can we do it in o of one space so let's try to understand so let's from the previous solution itself we know we need to first divide the list to reach on the middle like this and four five and six so first of all by using the two pointer we will reach to the middle of the list like we will break so instead of breaking here we will just keep this not break here so now our slow pointer will be here now the other approach what we will do we will reverse this second half list if we reverse the second half list like this will become 1 2 3 and then 6 5 and 4 this will be null here and we know this node here from the we will call this is slow or we can call pre middle as well so and we know the head of this list once we know this now we will merge nodes one by one so as from here we will take the next to this node and this node next to this node set and similarly so let me use the different colors here so that it will be better understandable so first we will use this node had.next we first we will use this node had.next we first we will use this node had.next we will take to do pre mid node next so this will be a pointer will be here and we will break this pointer from here similarly we will change the pointer of this next from here to here and we will break this node and link here similarly we will use make this node next is this node and this node max is this node and this node previous to this sky and so on so if we do this will become the desired list like 1 6 2 4 2 sorry 2 5 then 3 and then 4 but how will we will so there are three step one reach to the middle of the list and second is reverse the second half and the third is merge this node so let's understand how we will reverse so there is a one problem in the lead code itself for reversing a list try that problem as well before attempting this it will be good so that you can easily reverse the list so let's understand how we will reverse with the new list let's say we have simple list 1 2 3 and 4 and we have to reverse this node list from head so head is starting from here so far what we can do we will use a current node one from here and an tamp node let it call temp and the temp dot next we will use a current which is a time dot next then we will update this current dot next so though had this head is we will change this head to head dot null dot next to null and we will reverse this two here and we will shift this temp to here uh current node and then current will be shifted to here then we will again reverse this two and this stamp will reverse to move to here then we will reverse in the end wherever the current we will return this is our the head of new reverse list so this is how the reverse will work now let's understand how the merge will work so for merging let us change the pen so for merging let us say we got the list reverse one like 1 2 3 6 and this will be 5 and this is 4 so if so and we know this node is noded in slow or we can also copy it into pre-middle so we will use copy it into pre-middle so we will use copy it into pre-middle so we will use another pointer which will be our pre-current pre-current pre-current so we will initialize this one node from slow from head new head which will be let it call hat and another pointer from here which is let it call fast we will reuse the pointers and which is from pre middle dot is next so this is how the node are here now so first of all we need to chain this perimeter dot next to fast dot next we will change this pointer let's take the another point this pointer to this node once we change this pointer to this node we will move the this fast dot next this 6 is going here from here we will take this to slow dot next so which will be pointing to 2. now once we reach to here we will change the slow dot next from here to fast which will be the current fast which is so the should be this so the should be this so the should be this 0.25 so this will first rearrangement is 0.25 so this will first rearrangement is 0.25 so this will first rearrangement is done like 1 then 6 and then 2 and after that we still have 3 and 3 is pointing to 5 now 6 got removed move to the location then this will be 4 and our pre middle is still here correct now in second step and we will also change fast we will move this fast to next node which is pre middle dot next so because our pre middle dot next is pointing to the next fast that is how we record it initially so fast will point here and then we will do repeat the same step so this will become 1 6 then this will be 2 then 5 and after that 3 and this will be 4. so this is how we reorder the list using the three steps so and this where how long this loop will run this loop will be run until our pre-current will become like until our pre-current will become like until our pre-current will become like slow pointer not reaching to the spree middle if slow pointer reached to this node because we started from in star to here we need to reach and we fill the right half of the node all here so this is the solution so try it out before seeing the solution so here is the code i have written down here so this is the first just a base case checking there this is the second step like first step to reach to find out the middle of the list using this condition and this is the second step to reverse the second part of the list and this is the third step to merge the right half node into one by one into the first half of the node using the condition i explained so that's it so let's submit this code so this is accepted and the time complexity of the solution is still of n but the space complexity is constant of one so if you like my solution hit the like button and subscribe my channel and if you have any doubt in understanding ask in the comment section i will be happy to respond thanks for watching see you tomorrow
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
148
hello everyone welcome to my channel coding together my name is vikar soja today we will see another lead code problem that is shortlist let's read the problem statement it's a medium type question we are given with a head of a linked list and we have to return the list after sorting it in ascending order let's see how we can approach this so we will use merge sort for this and merge sort is based on divide and conquer dividing this list with the Middle Point middle node so to find the middle load for the list we will use a slow fast approach I have already explained the slow fast approach in my one of the previous video finding the middle element in the linked list so you can watch that video to better understand the slow fast approach so for our let's start the head will start from the pointer 5 and after performing the slope fast approach to find the middle element will have slow at pointing at 4 and fast pointing at 3 we will have another new pointer previous that will point just below the slow pointer so we will divide the list into two halves the left half will be the list pointing from head to previous and the right part will be the list pointing from slow to fast so the left we will pass the head as the starting node and for the right we'll pass the slow as the head note now we have head and for the next activation we have head and previous pointing to five and again finding the middle element our slope will point to 2 and fast will point to two again we need to divide this list into two halves that is five and two so we will divide the one the left part from head to previous so head and previous are both pointing to five so there will be only one element on the left and again on the right slow and fast pointing to 2 so there will be only one element two on the right so here again we will do the same thing for 4 and 3 list that we will have to find the middle element so as slow and fast is pointing to 3 a slow is pointing to 3 so slow will be our middle element so we will have to divide the left part from head to previous and the previous will be just below just before the slow pointer that is pointing to four so again here there is only one element on the left after dividing n on the right side again we have only one element three one important Point performing the recursive call we have to eliminate this link between the previous and the slope otherwise it will go in the infinite Loop so that's why we will in after in each recursive call will make previous dot null equal previous dot next equal to null so that this link is broken now as we reach the last node we see that there is no a way to perform left and right recursive call so this node cannot be broken down into simple uh simpler notes this is the least possible node we can have so we have to then backtrack or go up so because we have reached our base condition either the node can be equal to null or node.txt if it is equal to null or node.txt if it is equal to null or node.txt if it is equal to null then we have to return back so now comes the point of merging that we have to see so when we will merge this 5 and 2 we have to take care of merging I mean staking the element smaller smallest element first and the largest element next so let's see how we can merge so at this level we have 5 2 and 4 and 3 as right left part of the subtree and the right part of the sub trees respectively so we will merge 5 and 2 and 4 and 3 in ascending order so let's see how merge works so in the first list we have five and the second list is pointing to two so we will make a dummy list node and a tail that will point to dummy and tail will the tail dot next will point to end now we will compare 5 and 2 as we as 2 is smaller than 5 so we will change our tail dot next to the smallest element and we will also so as soon as we do tail dot next to 2 the dummy dot next will also get changed to 2. now we have to break this link from tail to dummy so we will assign tail to the tail dot next so now tail will point to two so that tail can freely go from one node to another without changing the dummy next pointer now once we have chosen 2 from the second list we have to I means increment the pointer from 2 to the next two dot next that will be end so second pointer is pointing to end so we have only with left with first list so we'll directly change our tail dot next from 2 to 5. so this the tail dot next was pointing to two now it's pointing to 5 so when we are changing our tail dot next from two to five the two dot next will also get changed from end to five and dummy will still pointing to two similarly we will do here four with four and three as three is smaller will again create a dummy and Tail list notes the dummy as soon as the tail was pointing to dummy as soon as we three was smaller than four so we'll assign tail dot next to three so the dummy dot next will also get assigned to three we have to break this link from tail to dummy so we will also assign tail to tail dot next that is still will point to three now the second pointer was pointing to 3 we have to change it to the three dot next that will be end pointer that is null so the second bonding is pointing to null and the first list pointer is not empty so we will take this so now we will remove our tail dot next we'll Point tail dot next from three to four so if you see this point is changed from tail to 4 and also we'll change our tail from tail to tail dot next tail equal to tail dot next that will be pointing to 4. so as soon as this merging at this level is performed we will return the dummy dot next value because dummy dot next will point to all these values if w dot next will point to 2 and 2 will 0.24 so we have a link 0.24 so we have a link 0.24 so we have a link that is we will when we return dummy dot next we'll we are returning the head of the merged list that is to here also when we are returning dummy dot next we are returning the head of the merge list that is three now from this level we have returned to the upper level now at this level we have 2 comma 5 and 3 comma 5 return from the lower level now we have to merge this these lists in an increasing order so let's see how we can do it so in the next iteration in the next when going backtracking for the upper level we have list two comma five two to five and three four so first pointer is pointing to two second pointer is pointing to three so we'll compare two and three as to a is smaller than three so again 2 is comma 3 and we have already created a dummy and tail list note as similar to previous steps now we will assign tail we will assign our tail dot next to 2 and ultimately Derby dot next will get assigned to true now the first we will as we had taken the number from the first list we will assign our first we will increment our first dot next from 2 to 5. the second pointer will still be pointing to 3. now we will compare 5 and 3. so S 3 is smaller than 5. we will change our tail dot next from 2 to 3 so here the tail dot next got changed from 2 to 3 and ultimately the tail the two dot next which was pointing to five the next pointer element in the first list it will be removed and it will automatically point to the three that is the next node for the two because we have changed tail dot next to three the two dot next will also get changed to 3. and this will the link this link will be get will get broken now and once we have taken three from the second list the second pointer will change from three to four now we will compare 5 and 4 because from the first list only 5 is remaining and from the second list it is pointing to 4 as 4 is smaller we will again change our tail dot next from 3 to 4 so we have changed our pointer to 3 to 4 and also three that the next pointer in three will get changed from three to four so there is already a link between three and four so it's there and now this uh the we will increment our second pointer which will point to null end and uh and four will point to end as well because there is nothing after 4 so it will pointing to end now we will only 5 is left from the first list so we'll directly see that the second list is empty we have one element from the first list so we will take our pointer tail dot next we'll point to five so where we have this we have changed from tail 4 to 5 and both first and second pointer will increment change from their respective list to the end pointer and then we will return dummy dot next I the first note of this merged a list that is to from this list from this step it will be returned and after this the merge list two three four five will be returned outwards So This Is How We Do merge sort and divide and conquer so let's see the code part simple recursive call to do the Sorting to divide so this is the method that will uh means divide the list into two halves so to find in order we will first have our base case that is if the head is equal to or null or head dot next it equal to null will return with head as we saw that if the head dot next is null or head dot if the head is null we will return the head value now we will start with fast slow and previous pointers as stated for the slow fast approach to find the middle element and we will break the pointer the link between the left subtree and the right subtree left part and the right part that we divided so that it's not the recursive uh you know recursive call and it's not an infinite Loop now the first uh now performing the iteration uh recursively until unless we reach the base uh our base case then we start the merge operation so let's see the merge operation as we talked about that we'll create dummy until tail will point to dummy we'll first iterate till when will iterate from both first and second when they are not equal to null so we'll keep on taking the element from both the lists and if the first dot well is smaller than second dot 12 we'll Point our tail to the first element from the first list and we'll update the pointers respectively for the first and till will also point to till dot next else if the second if the elements in the second list is smaller than the first then we'll update our tail dot next to Second and second will be equal to Second dot next and also we'll update our tail equal to tail dot next so that the link so that this link between tail and dummy is broken and also every time the tail points to the last element of the list so as soon as if any of the first or the second list is empty we'll just see whether which one is empty and will assign the tail dot next to the that one which is not empty so if first is not equal to null will assign tail dot x equal to First else till dot next equal to Second and finally we'll return our dummy dot next in each iteration so hope this uh hope you like this video the let's talk about this the time complexity so the time clocks complexity will be n log n to iterate the tree to Traverse the tree that is n order of n for each iteration we are dividing we are finding the mid by dividing the list into half so that will be login so the total complexity and login thanks for watching this video and I hope you like this video please share and subscribe to keep me motivated to present more videos like this thank you
Sort List
sort-list
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-105 <= Node.val <= 105` **Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
null
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
Medium
21,75,147,1992
1,414
Hello viewers welcome back to my channel I hope you enjoying all the problem time uploading this has been subscribe To My Channel Please subscribe and Share with your friends Problem Minimum number of members will be happy with this game Rate that alliance number will keep returns Dum minimum number of branches name birds who is equal to one officer appointed multiple times pressure made from number 15 number and different f1s golden 1 2012 also in the affidavit and minus plus and minus to friends great dane tubelight is the definition of business name but Guarantee subscribe to 200 basically were given a number and need to find that Decline after two plus phase minimum number after Thursday subscribe The Channel subscribe The Video then subscribe to get 7 subscribe my channel right mental reader song dil aaj ke is hair oil fuel overload weight loose number 110 rock loop ki Profit Numbers Usually Not Even Log in Some Cases Even Last Episode of Mid Day Meal of the Day But in Some Cases Loop K Solar System Vary I Left Number of Branches Numbers of Category 1 Should They Go Into His Argument Generate the Problem Description Veer Subscribe Possible Number From The One Phone Life Is Feel Great Dan He Possible Number In The Power 909 10 Go Into Foot What Were The Number Three Subtracted From The Greatest 16th That A Given Number How Many Thanks And Number And 19 numbers abstracted from the middle name Video then subscribe to the Page An excerpt means show individual's 25th number quality use fennel rather send dating back number that Vikram of this dynasty is starting water that shirt fans that is the unique elements These two numbers were going to return the same welcome back side Don't forget to subscribe the description and subscribe the Channel subscribe Karna Thursday subscribe exchange of two boys subscribe silver 2250 people will give the number central power under 9th one switch yes this Amazon Se The White Miduing Bringing Down In The Mid-Day Channel को subscribe and subscribe the Channel को subscribe and subscribe the Channel को subscribe and subscribe the Channel Play List Hubris and Established Solly S U Go Oye Give Vote Mange Iss Yuvak Ke Leftovers subscribe this Video subscribe The Channel Please subscribe and subscribe the u guddu a pun's decade question from kia price so finally since aircraft of the element web tracking in hearts will definitely give the evening elements and drop this problem minimum number of the mind 's training branch number produce 's training branch number produce 's training branch number produce multiple times ad language's this great deal If invention Vaikuntha then this number to do the thanks for this is not only possible unauthorized appointed subscribe this Video give pregnancy 40 to a I can send it amount third hour example of people immersed in this darkness air chief executive whose oil 10 Subscribe Deducting Between Prem Mishra A That Damadamm Amount Dresses For Example K Is Equal To Right The Children Two Times Fight Super Quite Difficult Ujjain Two Types Of Sorrow And Subscribe Button In The Subscribe Thank You Basically Time Complexity This Problem Thursday Click On Subscribe Button By clicking on Amazon not holding for all elements Earth Water Jhal A Time Complexity Rate shows click on subscribe The link for detail view Ne Bigg Boss यूनिक से SUBSCRIBE TO लड़ान में लड़ान तथा रेक्स फैम्बर्स वे Bigg Boss यूनिक से SUBSCRIBE TO लड़ान में लड़ान तथा रेक्स फैम्बर्स वे स्टोरिंग एक हैर्ट्स ऑफ विक्टी टो स्टोरिंग एक हैर्ट्स ऑफ विक्टी टो स्टोरिंग एक हैर्ट्स ऑफ विक्टी टो only the evening elements Present for this is the amazing subscribe and subscribe the Channel Please subscribe and Share And subscribe my video updates hai ayurvedic with another problem from which got very soon children by
Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
shortest-path-in-a-grid-with-obstacles-elimination
Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times. The Fibonacci numbers are defined as: * `F1 = 1` * `F2 = 1` * `Fn = Fn-1 + Fn-2` for `n > 2.` It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to `k`. **Example 1:** **Input:** k = 7 **Output:** 2 **Explanation:** The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7. **Example 2:** **Input:** k = 10 **Output:** 2 **Explanation:** For k = 10 we can use 2 + 8 = 10. **Example 3:** **Input:** k = 19 **Output:** 3 **Explanation:** For k = 19 we can use 1 + 5 + 13 = 19. **Constraints:** * `1 <= k <= 109`
Use BFS. BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove.
Array,Breadth-First Search,Matrix
Hard
550
160
welcome back everyone we're gonna be solving Lee code 160 intersection of two linked lists so given the heads of two singly linked lists A and B we want to return the node at which the two lists intersect one another and if the two linked lists have no intersection at all we can just return none so they give us an example here A and B link to list a points to C1 and list B points to C2 so what we're going to do is we're going to use two pointers to solve this problem we're going to set pointer a to the first node in list a pointer B to the first note in list B and while these two pointers are not equal to each other we're just going to increment them by one so we'll say A1 or current a is now pointing to A2 current B will now be pointing to B2 a points to C1 B points to B3 a points to C2 B to C1 a now points to C3 B to C2 when a reaches none we want to take that pointer and set it equal to the very first node in list B and we'll do the same thing for our pointer B so let's keep going now B is playing to C3 uh a will now be pointing to B2 B is now at none on so we increment B to a now they're both pointing to the same thing but they are not equal to each other still so now we increment both of them by one again and they finally reach the uh C1 node and then we can return so let's say current a will be equal to head a and current B will be equal to head B we will say while current a is not equal to current B we want to check if current a is not none we will say current a will now be equal to current a DOT next else if current a is none we want to move it to the very first node of our list B so we'll say current a is now going to be equal to head B and we will do the exact same thing for our B pointer so we'll say if current B is not none we want to say current B will now be equal to current B dot next else if current B is none meaning we reach the end of our list we want to set it equal to the very first node of our a list and once we exit this loop our two pointers will either be pointing at the very same node or they will be pointing to a null node so in which case we can just return either a pointer so let's just say We'll return B so we'll run this we pass all three test cases we'll submit and it does run perfect so time complexity we are iterating through every node in uh list a and list B at most uh once so that is going to give us a Time complexity of O of n plus well let's just say a is the length of or the number of nodes in list A and B is the number of nodes in list B okay now the space complexity is going to be o of 1 constant time because we are not creating new data structures to solve this problem we are just using two pointers and looping through until we reach the same node or the null node all right they'll do it for Lee code 160.
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
1,004
hey guys this is Alex and welcome back to my video series on solving lead code problems and now we're solving problem 104 Max consecutive Ones Part three so given the binary array nums so it's an array with integers which are either one or three or zero and an integer K which is this one return the maximum number of consecutive ones in the array if you can flip at most K zeros so if I have k equal two it means I can turn two of these zeros into ones and I want to form the longest string of ones the longest will be this one Z you turn them to one so one 1 2 3 4 5 six other solution is this so how do we do it let me copy this and let me put it here I was already looking at it before so how do we do it we just go and start and create a window so hey we have window one another one then we have a zero it's like well we can flip it so let's keep it in the window and we find another zero it's like oh cool let's flip it and let's keep it in the window and if we find another zero and our K is two so it reaches the limit then we need to find to move this um to move this window all the way to the right shrink it to the right until we find our first zero and replace it so yeah we found our first zero we replace it and we insert our new zero uh like this and then we continue oh another one good we can do it one then hey new zero same thing let's shrink it good and whenever we change the window we keep track of the best uh window size biggest window size at this moment it is six but when we started it was one or two three four five and then it was five again when we change here oh no wait it was then it was 2 3 4 five 6 and then we have six so yeah we just need to return it so let's get coding so window is a list of integers starts with nothing starts so for uh best window size zero so for nums uh num in nums at the end we just do best window size equals Max of best window size and length of window so what we do if num equals uh one then window. aend one else if it's a zero then we can let's keep a track of curve zeros and starts with zero so if uh per zeros equals k then it means that we have too many zeros and do something I'm just going to do bigger or equal it's always going to be equal never bigger because of what's going to happen but else so if current Z is a smaller what we do is window. pens Uh current zero no pend zero and current zeros do pend no plus equal 1 plus equal one so if current Z is bigger or equal than K there's an edge case here so if uh k equals z then Cur zal Z window equals empty else what do we do so we need to find the first zero in the window and then remove it from the window so remember when we did this which was hey we found oh we're here so we need to shrink it so we find the first zero and we shrink it so for I index in window if window of index equals zero then window equals window of index + one onward and break and window. aend zero so now return best window size now I'm submitting wrong answer let's see why case two solution just want a = 2 so it's 11 it should be six yeah because it's yeah this is actually the example we saw so let's just run this and figure out the bug so we start with one then we have three zeros one then we have zero we append it then we have another zero we append it and now the number of zeros yeah so else and then window let going to find the first one never found the first one window what do you mean window of index equals z it must be okay so for index in range length of window I'm just going to run this again and see if we get to six magically six let's go submit cross our fingers let's go good so it got accepted the run time is a bit too slow the memory is pretty good how would I do it better so one thing that we're doing here is I'm iterating over the window to find the first zero so what we could do is we could do something like uh positions of zeros in window and then we would add the position which would always be um position of Zer in window. append length of window minus one same thing here but whenever we remove it we also need to remove the zero so we need to remove the first zero so pop the first position which is consider a zero and then we need to update all the other zeros um remove zero and then we need to update all the other zeros with X for x and xus uh remove 0 minus one see if this works actually should return six position of zero is in window position of zero well let's try it six I's submit it so this will pretty much just speed things up there's probably a bug here so don't expect miracles but I'm happy with the results and while time limit exceeded actually it takes even longer for some reason uh yeah actually if I'm doing this I don't need to yes that's the point like I don't even need this for indexing range I can just go and say um so I need to remove this and I can move this back and window index and removed zero is the new IND index here index so let me just submit I'm going to stop the video after this submission even if there's an error because I know my strategy works and I hope you guys enjoy the video so let's just see if for some reason I'm successful well time limit exceeded anyway so oh well I guess I will have to do some shovel shooting but I hope you guys enjoy the video see you later
Max Consecutive Ones III
least-operators-to-express-number
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. **Example 1:** **Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2 **Output:** 6 **Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Example 2:** **Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3 **Output:** 10 **Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. * `0 <= k <= nums.length`
null
Math,Dynamic Programming
Hard
null
1,945
foreign 1945 sum of digits of string after combat so basically sum of digits of string after convert so the description is that you're given string as consisting of lowercase English letters and an integer K first convert s into an integer by replacing each letter with its position in the alpha in the alphabet that is a plus a with a one B with two and Z with 26 then transform the integer by replacing it with the sum of its digits repeat the transformation operation K times in total and then for example if s equals a z b a X and then return k equals 2. then there is resulting integer would be 8 by the following operation Operation so you have 26 to 1 and then 24 and then end up this and then transformation one you sum them up and then transformation to you end up with eight here you end up at 17 then here we end up with eight so pretty much that's what we have to do uh let's say for instance input here k equals one and then we're going to end up with 36 explanation the operation are as follows so we have I 999 hi whatever and then sum them up it's 36 thus the resulting integer is 36 so if we have leap code then we have here we have uh twelve five so we're gonna end up summing them up and then when once we are done so we're gonna end up with the what three plus three which is uh two so basically that's what we have to do and those are the constraints let's go ahead and break down the chord line by line so first we start by creating a string Builder to store the trans the transformed string that's the first thing we're gonna do and then um we're gonna have a for loop at this fold basically what we are doing we're going to calculate the position of the letter in the alphabet right here that's all we're doing here and then we're gonna append those uh the digits into the screen Builder and then here the K side uh so what we're doing on the K side so with it so basically uh we are going to perform the transformation with the K times if K is greater than zero then we're gonna keep as long as this condition is correct and we're going to continuously perform the transformation and for the transformation uh basically is to convert the character to its corresponding digit value and then here that's what we're doing and then we're gonna sum them up so that's what's happening there so basically this will deal with the transformation and then in the end we're gonna return the desired uh response from the uh from our card and if we run it you will notice that it's going to be accepted and then we're going to submit it and I'd be here it's accepted all right guys I will see you guys in the next one don't forget to subscribe uh this is Chris see ya
Sum of Digits of String After Convert
finding-the-users-active-minutes
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum of its digits**. Repeat the **transform** operation `k` **times** in total. For example, if `s = "zbax "` and `k = 2`, then the resulting integer would be `8` by the following operations: * **Convert**: `"zbax " ➝ "(26)(2)(1)(24) " ➝ "262124 " ➝ 262124` * **Transform #1**: `262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17` * **Transform #2**: `17 ➝ 1 + 7 ➝ 8` Return _the resulting integer after performing the operations described above_. **Example 1:** **Input:** s = "iiii ", k = 1 **Output:** 36 **Explanation:** The operations are as follows: - Convert: "iiii " ➝ "(9)(9)(9)(9) " ➝ "9999 " ➝ 9999 - Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36 Thus the resulting integer is 36. **Example 2:** **Input:** s = "leetcode ", k = 2 **Output:** 6 **Explanation:** The operations are as follows: - Convert: "leetcode " ➝ "(12)(5)(5)(20)(3)(15)(4)(5) " ➝ "12552031545 " ➝ 12552031545 - Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33 - Transform #2: 33 ➝ 3 + 3 ➝ 6 Thus the resulting integer is 6. **Example 3:** **Input:** s = "zbax ", k = 2 **Output:** 8 **Constraints:** * `1 <= s.length <= 100` * `1 <= k <= 10` * `s` consists of lowercase English letters.
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
Array,Hash Table
Medium
null
1,583
okay yo what's up guys babybear4812 coming at you one more time uh with a problem by popular demand it's the count unhappy friends problem now uh it's only really bloomberg that's asking this one recently and i guess a lot of you are preparing for bloomberg so i figured we'd go over this one today now unlike most of the problems that we do i think part of the challenge in this problem is actually understanding the question i think in a lot of the questions we do they're more or less self-explanatory this one's a bit tricky self-explanatory this one's a bit tricky self-explanatory this one's a bit tricky okay the code thankfully will be code will be very straightforward so that's nice i don't think this will be too long of a video but it i think it's a decent problem nonetheless now we're given a couple of items here we're given a number n for friends we're given a list of preferences and we're given pairs they don't mention that here but it is given to us so uh n is a number that's always even we're given n people an even number and for each person i of the surrey preferences i uh each element in that preferences array contains a list so we got a nested array of friends sorted in order of preference in other words a friend earlier in the real list is more preferred than a friend later in the list friends in each list are denoted by integers from zero to n minus one so if we have five friends five people in total rather uh we've got can't have five people because we always have an even pair let's see we got four people those people will be labeled zero one two and three all right no funny business uh now we're said that all the friends are divided into pairs and the pairings are given this list pairs which is also passed in uh and in pairs of x y x's is paired with y and y is paired with x logically now certain pairings may cause people to be unhappy so this kind of rolls you back to like your middle school or high school days when you can't pick your own group um and then things happen in this problem we need to count the total number of unhappy people uh no and we're kind of we're gonna define what unhappy means here but uh in a certain pair of people either one can be enough so both men could be happy maybe one of them is unhappy and the other isn't or vice versa or they could both be unhappy right that's really important to take into account here because i think that goes over some people's heads in this problem so it says if x is paired with y x prefers u over y and u prefers x over v all right then i guess x is unhappy so let's look through an example in this example we're going to dive into a bit deeper and we'll build off of it but if we're given four people and these are their preferences uh zero's paired with one two is paired with three it says that friend one is half a friend one is unhappy why are they unhappy because it says one is paired with zero fine uh but one this is one's preferences one prefers three to zero right and they also prefer two to zero fine that in and of itself is not enough to give us any good information yet however if we acknowledge the fact that three prefers one to the person they're paired with so once paired with zero three is paired with two one prefers three to the person they're paired with three prefers one to the person they're paired with therefore red one is unhappy by the same logic we can actually find out that three is unhappy as well we'll talk through how to go about finding this but um it's important to understand this example first so if that didn't quite make sense pause the video reread the question uh look over the explanation again like i said because we need to start from a common understanding and really getting what the problem's about and then i don't think it's trivial so let's say that i've i'm going to elaborate on this example here i've got four people these are my pairs these are my preferences what do i actually do about this the first thing that we need to acknowledge is the fact that the person that i'm paired with may not be my favorite person meaning that there are other people that i would refer to the person that i'm with so how do we go about dealing with that first thing we're going to do is we're going to create a dictionary and i'm going to call this dictionary d and the reason we're going to make it a dictionary kind of as the problem goes on we'll will become a bit more clear because we're going to want to loop through things in a clean manner and kind of using a constant lookup time all right um i'm going to start walking through these pairs of people so i've got 0 1 2 and 3. for person number zero what i'm going to want to do is i'm going to create a list of people or rather i won't be using the list i'll be using a set which again will become clear in a moment but i want to create a set of people who xero prefers to their own partner so these right here are zeros preferences xero's best friend or their most preferred person is one that also happens to be who they're paired with so since once i find the one i'm going to say that everyone after that one is less prepared than my partner so i'm going to close off that set in essence here zero's paired with their favorite person zero's gonna be happy all right let's say i go to person number one now i'm gonna go to person number one and i'm gonna say okay one's paired with zero cool where does zero fall on one's preference list well they're right here they're at the end zero actually prefers both three and two to their own partner so i'm gonna add three and then two imagine kind of iterating through all the items until you get to zero okay i'm gonna go to person number two now i'm walking through these pairs in order to create some dictionary which will become clear in a minute what i'll do with it um i wanna say that too so who's paired with three uh they don't prefer anybody to three's actually their top person so that's fine and in this dictionary maybe i could make it more clear this would be something like i've really been debating on what to call this thing but maybe something like preferees i don't there's no way that's actually a real word but it's essentially the list of people per person who they prefer to their own partner all right um and for person three we can see again three spirit of two three however prefers person one to person two they prefer person two to person zero sure but they prefer person one to person two and let me just make sure that i copy that down right uh one two zero so they're going to for person one to the person that they're paired with and overall this will just kind of close off the dictionary and what i've got now is a dictionary or an object depending on the language that you're in a hashmap um that gives me kind of for each person i have constant access to a set of the people that they prefer to their own partner okay this is the first half of the question once we tackle this part the second one will require a bit of i guess logical acrobatics but the first things first is i need to identify who are the people that somebody prefers to their current partner all right so we've got that kind of sorted out what do we do with this now how do we then decide is somebody unhappy or not in this list again i've got everybody that i prefer to my current partner so what i want to do is i want to begin by iterating through this list so if i iterate through this list and for each person i want to walk through all the people that they prefer to their partner so imagine that i said something like i'm going to pseudo code this which yeah i guess pseudocode is actually similar to what it'll look like in python but for each person in this dictionary i want to walk through each of their sets and then for that counterpart so i'll say maybe for y and d of x because i want to iterate through everybody that they prefer to their current partner in what case are they unhappy well x is going to be unhappy if they prefer somebody else to y and y prefers them to the person that they're paired with all right that's where the tricky part comes in so uh you know x is gonna be unhappy if they prefer somebody else to y and that somebody else prefers x to be so it's like hey let's see you and i get along great and i'm like well i prefer you to the person i'm paired with and you're like well i prefer you to the person that i'm paired with we're you know like we're going to be unhappy so from my perspective i'm going to be unhappy from your perspective as well you're going to be unhappy um and so that's where things kind of fall apart and if that happens i need to keep track of some sort of result variable that says add a plus one to the number of unhappy people all right so what uh what i'm going to do here is i'm going to say if and this is actually this pseudocode is kind of going to be what our code is going to look like um it'll say if x is in a d of x so basically oh lord that was a mess if it's in d of x all right i don't know what's happening d of x then we're going to say you know get some sort of result plus all right and we'll obviously it'll be plus equals one in python but you know details what does this code actually mean this code means that for every single person i'm going to walk through the people they prefer to their partner and if it just so happens that the person that i walk through or i'm sorry this is what i made a mistake here if x is in jesus christ this should be d of y i'm sorry i don't know why this sum let me make sure i got this right yeah all right something's going wrong here well what's the issue where am i messing up here i'm sorry for the difficulties guys there i'm gonna walk through all the people i prefer to my partner if the person that i find also prefers me to the person there with that means that i'm unhappy and we're gonna add the result and i'm gonna at that point i can just break because i can say of all the people that i prefer to my current partner i found one who prefers me to their partner cool i'm gonna break out of that meaning i'm gonna break out of this loop i'm going to jump back into here i'm going to jump back into this loop i got to look into this after i don't know what's happening um i'm going to jump back into here and keep iterating through every person individually and so that's really all that's going to happen then in the second half of our code so once we put together this list of people we preferred our own partner we then need to walk through those preferences and actually find out what the um excuse me brain freeze we need to find out if those people also prefer us to the person that they're with all right uh in terms of the time and space complexity i haven't thought too much about that just yet and i don't want to mislead you guys so check the description i'll put it down below for what the complexities will be with the brief explanation as always so let's dive into this code here while we're at it i'm going to pull up my notes here and the first thing i'll begin to do is i'll create this dictionary again i'm going to call it d you could call it preferees or something again i really didn't have a good word but what this will be a um it'll be a dictionary with the set property where or sorry it'll be a dictionary with so maybe we'll say person uh to set of uh people they prefer over their partner all right just to be descriptive i want to leave that there once we do this we need to walk through all the pairs and for each single person we're going to need to create this graph over here that's right it's not even a graphic maybe you could interpret this as a graph question actually but we want to essentially create this list of people that we prefer to our current partner so what i'm going to say is for x and y in pairs meaning that's going to destructure it's going to be structures so 0 and 1 2 and 3 and so on and so forth i'm going to say in dictionary of x i want to set that equal to some set and i want to set yeah why also equal to sum set and now the question is how do we create that set the way that we want to create that set is as follows is we need to have some reference to preferences of x so if i'm looking at person zero my you know my property here is going to be zero and i want to look at the preferences of person zero and i want to grab a certain chunk of that array what chunk of that array do i want to grab the chunk of the array that includes everybody up to but not including their partner so for instance i'm looking at person one here they're paired with zero i want to include three and two because those people i prefer one prefers excuse me person one prefers three and two to their own partner zero so they want to go up to so we're kind of going to split the array here they're going to go up to uh preferences of x dot index of y so what am i saying here x y is x's partner we want to go to the preferences of that person x and we want to grab everybody up to but not including the index of their partner right so since the way we split arrays here in python in the second on the kind of the latter half of this column this is not inclusive whatever the indexes of their partner we're going to grab everything before that and similarly i'm going to do kind of the same here i'm going to say preferences of y and we're going to go up to but not including preferences of y dot index of x meaning everybody that they prefer that's not that person themselves cool that's the first half of the quote that we talked about the second half now we're gonna have some sort of result we're gonna return that result at the end and now we said that we need to start iterating through this dictionary that we just created so let's say for x and d and then for every item in that dictionary here we want to iterate through every item within that set okay so we'll say for y and d of x and now we have this if condition here and in this if condition we said that um i'm looking through all the people that i prefer to my partner if each of those people if one of those people excuse me if one of those people prefers me so if i'm in their list then i'm unhappy so we say if x is in d of y then resolve plus equals one and since we found someone we're going to break we know that person's unhappy if we don't break then we might count the same person being unhappy multiple times which isn't what we want and that's why we're breaking here so again i'm looking for every person i'm looking through all the people that they prefer to their own partner and now if i'm also in their list of people that they prefer to their own partner i'm unhappy by the definition that's given we're going to break out of that for loop here we're going to go back through iterating through the main dictionary we made and we're going to return that result so i'm going to run this quickly make sure i didn't make any mistakes i'm going to submit that and there we go yeah what is that 99 percentile almost uh in time and we got some good space there as well this is will be the optimal solution uh like i said i'll drop the asymptotic analysis and complexities in the description below as always if you have any other questions drop them down below contact me my emails in the description and i will see you guys in the next video peace
Count Unhappy Friends
paint-house-iii
You are given a list of `preferences` for `n` friends, where `n` is always **even**. For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`. All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`. However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but: * `x` prefers `u` over `y`, and * `u` prefers `x` over `v`. Return _the number of unhappy friends_. **Example 1:** **Input:** n = 4, preferences = \[\[1, 2, 3\], \[3, 2, 0\], \[3, 1, 0\], \[1, 2, 0\]\], pairs = \[\[0, 1\], \[2, 3\]\] **Output:** 2 **Explanation:** Friend 1 is unhappy because: - 1 is paired with 0 but prefers 3 over 0, and - 3 prefers 1 over 2. Friend 3 is unhappy because: - 3 is paired with 2 but prefers 1 over 2, and - 1 prefers 3 over 0. Friends 0 and 2 are happy. **Example 2:** **Input:** n = 2, preferences = \[\[1\], \[0\]\], pairs = \[\[1, 0\]\] **Output:** 0 **Explanation:** Both friends 0 and 1 are happy. **Example 3:** **Input:** n = 4, preferences = \[\[1, 3, 2\], \[2, 3, 0\], \[1, 3, 0\], \[0, 2, 1\]\], pairs = \[\[1, 3\], \[0, 2\]\] **Output:** 4 **Constraints:** * `2 <= n <= 500` * `n` is even. * `preferences.length == n` * `preferences[i].length == n - 1` * `0 <= preferences[i][j] <= n - 1` * `preferences[i]` does not contain `i`. * All values in `preferences[i]` are unique. * `pairs.length == n/2` * `pairs[i].length == 2` * `xi != yi` * `0 <= xi, yi <= n - 1` * Each person is contained in **exactly one** pair.
Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j.
Array,Dynamic Programming
Hard
null
641
Hello hello everyone to Ajay, slow down the set point according, so today we are going to design a circular DQ, so let's take a look at what teachers we have to do well, here I have given the description of all the functionalities and here they are. Through a test, we understand that further work has to be done on this question. Print on the top of one bone and in these two positions, the entire operation has been done. It is okay on both these sides. So, let's see the first task. These were the last ones for you now. DP is not any tight then interest means first banna is this only then interest will come again here two is talent front then delete the first one which is closed on the front side, if there is two from here then remove it and remove this. Along with delete, it has been said that his rally has to be returned as well, so you have to return the value, give the next guy insult front free on this, it is not necessary that only these teachers will be there, this generic type has to be made, you are fine. If the next value ink jet print is not enough, then it will go to a friend, it brings trolleys of get hair but does not delete it, then there is a tutu on the website, you will not be a general candidate here, okay, this digit is last, we will fold it from here. It will break and it will be bittu, new one will come, it is fine, next guy battery, a fresh soil, three has come that the last digit of the villagers, so the last three is kept here, remove these that ink jet print son Hazara Gaya gate front But my feet are kept tight, you will come with that strip, you will not date, the work on that front is done, delete the front, you will also give loss on the different, and but you will go, he just moved further and also completed this work, again different, this guy. The physique is given and you give more agility and return it. After this, see here on your video, there is no one in the tight box, there is no one and again here it was said, what to delete, the front gets this condition that What do we have to do, here it is written FD because Guarantee Eternal is still null, now there is an edit entry, so we will null it, then the deposit front will be available here and it will be available here, okay, so basically the work was done, they were insulted. Front and insult last start from the front side or Reddy expresses tight electronic digital last, both of them follow the same direction and if there is no one to delete then they return the tap. Cat Front Detroit does not delete, only brings To Worli and here it is also written that if the values ​​are not there then return it. What is it, we values ​​are not there then return it. What is it, we values ​​are not there then return it. What is it, we need front toe and one more cartage anti, so now you don't have any diggi, so this Jayanti you will return it. Ok ok, if there was one or two things in it then it would have returned false and this is tanning ok then you can give opinion, an application has been made to implement the remind, why am I only ladies, in which the meter is drunk on generic And here the function safe insult front last point last is to update the functionality. Okay, okay and we can do 113 years. Basically, a link data structure that I require is tight here in which to remove an element from one end. Is being done and elements are being added from this end. If you talk about tight and related then till now I have playlists. My list is tight and linked list. Out of these three, if I use 'are' then why should I achieve if I use 'are' then why should I achieve if I use 'are' then why should I achieve Kabir? So I will have to add support dynamic behavior. Here the constraint is not said that why you have to work only on the size of the DQ so that the apps can follow it, so here you have to work separately for the dynamic way. If we look at it already goes with the religious behavior but if I add more on it then the internals will also be quite similar like if I have one on it first and two if I have alarms. If it is called then it will be created here but on add first it will be closed here if I want to add then the address will shift internally again tight will attract many points and then join here then here I would go time course here also time would go This time, what we are going to do is if we speak English here and there, then the basic list uses the memory very well, either create as many notes as required and dynamic behavior because new notes can be created, so dynamic heavy. It is easy to do things in this because of a very tight ego that to achieve that, I would have to have approximately a space of some length, because this plan will have to be fixed, so if it fills the lens completely, after that I am asked to add it, then a larger size than this. Let's say, all this data has to be copied on it 1234 and then I add the letter here, it is tight, so a new memory was created here, so unfortunately here also some money gets emptied in this black, okay so Some specific vestiges are now available here, but then it also takes time to copy it. It will take time to copy this remedy, but instead of both of these, there are element apps on this, at this time, we can directly access this Amla. We can do it later, we get this benefit but it is not needed right now, it is not needed because all the work above is being done only on front and rear tight, we do not need to access any gun in between, so we get this benefit and time. Come this, we can directly randomly practice some guy's oven love but there is no need for him to be tight so now the penis less is a perfect match that they are to achieve so we call it just written Okay, so basically you are going to remove it, you are going to make some notes, accept, here is the note from the note here, this is the note, this is completely different to my why, basically tighten the DQ, so now in this also, single point at least one tablespoon telling list. So if I used single point earliest here then an operation can be done to remove from last and if I removed the last guy then because on this guy I would be able to take back the previous new juice, which one would have been, I would like to doctor. If I had to find out, on doing 8 it would have taken a dependent time. I would not have known that the new one is rare and this one has become the height. If this English was a little bigger then it would have shown you more clearly whether you are here, mine, don't or else. You can say recording front of this class then some notes sleep and lastly this guy right here is air tight inside if you have total end guy and he is pointing only ahead is English pointer after removing this temple. If you did not know its address then here you will get completely old silly point. You can match the course but time complexity is condensed milk so remove last does not add much. Let's see the set daily point that if I have made double border English. If it is, then this work will be done well, it will be easily tightened, I am fine, I think this is enough, so if I removed the zip front, then the next guy will know this, if I removed the front, before this guy was a new bun. This work will also be done over the phone, it will be difficult because I have the references of both of them. Okay, this time we achieve this work with another double border English, but on this too, we ask the starting person to do the work, just like on starting, we will achieve this work. Add is also null, if it is like a donor then your head or front is null and rare is also null, then here Vishal is required to check the condition, many times it is tight and here if you are told add versus, then you You will have to check the condition, the previously closed channel is not you, make a note and this will be the front and after this, the next day if you remember any person then you will object to this, the ad would have been last if call me, ok, then Mirzapur appointment is here. I want to make it here that you have to do chatting, I am not pointing to the tap somewhere, add that if you work on English and W, then it is fine, so there are not many settings to handle these two just settings, but these two settings What am I going to do to avoid this, I'm going to put these two not affected on the starting and the last tree, okay these two will grind, this is my always one came on the front and my rare we will come right here and the current this is pointing this and It is pointing from this, okay, now I am told to set one more noose so that I am completely clear, I do not have front and rear taps, so you set a gun and attach it to the Nehru of your front and behind this note. Take it from and let's do this here. Okay, there is no border improvement, just to save some checking now, to save the settings with some taps, I fixed two guys here, dummy front and dummy pressure and The nerves of my penis will be between these two, okay, only the first and second one, either this dummy front on the side of these two and dummy pressure here and the rest of my entire list of stitching between these two is this, so basically see. If we go, my original front is here and the original is here, the work will be completed from here, okay, so let's see from and let's go to pigmentation. Okay, so to make the gender list, let's make only one first, told me basically. It has been said that the real life input that one has to receive at that time is mud, the pimples back has been covered, you can see it here, you will get its link in the description. Okay, so let's create a private class here. Note this. But there will be data, it will be of the type that data and note will be next and previous. Okay and let's also make a conductor, quarter inch tractor and one with parameters, it is a figure of jhal, it is complete, now what gift did I want, Meena, first of all. Have to pick on Monday, right, one guy here and one guy over here on the front, this is the first one, the pitch guy will always be here and my work will be on the inside, let's make these two, that node will be front and one. No dear, it is ok and both of them will always be there, so we can do it finally and no one from outside will be able to change it, but if we can, then we can do it in private. Ok, it is ok that a new node is created on the front. There is no need to give data, this will also not be used or this will also become a new note, now that these notes have been created, I have not linked them but till now its next permission should come, meaning it will come on the previous one of pressure and razor. If this is the next and previous ee, then let's link them too. Hello friend, the oil on the next and the key print on the previous of the oil is okay, so this is coming late and there can be another irony. It is okay to keep the size in these. Size equal 202 How many notes do I have to maintain their account and also fall into the requirement of checking somewhere Now insult front, if we have to add a person on the front, then how can we do it, so basically what do I have to do, my goal is to be fulfilled by so many and so many Right in the middle, my front should be here, just next to the pointer of the purple front, my axle front will be added tight, I should remove both of them sometime, let's take some notes from this guy, all are already here or here. There is one here, one is connected to the point of next office's next cross data, one and two are okay, if I was told, friend, add the front page zero, then one two should come here on the front, that cooked on the front. So what do I have to do with the data here then create 19 here with G road now its next here your or previous will go here tight I have to do something like this it will become a note right new node with this value of friend's Review or Add and Head will be next. By calling, this zero will come in the next tight but now I can set the mode. Advise, this point is of Gurjars, this is how I have to do it, so first of all what I did was note down. If you have placed the previous fat, then this guy is pointing it. Next on the previous, this band should be completed. Tight and what does next. Okay, so the job is done. He is pointing whatever impact there was on the head. What I have to do is to make the next point of my head that this is a break, this is the next part of the add and then I will come in the environment of this which is my next, then this old one will be a break and I will come. On the middle, I want to come to the environment of my next Android Next, tight, this we deleted that the work of adding the guy on these support of front is completed, now on this room, let's see more of the difference here. There is a lot more that won't happen, this is my list right now, if Roy has said that there should be two-three here, 201 should be two-three here, 201 should be two-three here, 201 are here right now, so basically 3 are here at this place, just an extract from Kaya Ray, first I will come to this. Next point this and edit this Next point this and the previous also gets done like this, if the work is fine then let's achieve it one by one, on the current situation this is pointing this first make this note team son's With that it became a note n equal to new that node and this value came on it ok a first task my next thing will be watel other air and water snake 222 aprayer that hey man's previous one should be my entry Will make the environment of tight hair your husband that and what is equal to 2ND year dot previous this work is done cheap rate now forgive both of them if you put it on the next one then this one will be broken then your one which is on the previous one Make me next to my previous one and this is the work you have to do to marry a tree, you yourself will become this environment, and this work of 222 ₹10 has also been completed, and this work of 222 ₹10 has also been completed, and this work of 222 ₹10 has also been completed, here the infection has reduced, here the bean fight has ended. Okay next we have what to do next is delete front ok I have created a pass property one that like I added a new guy my penis on this one cut it near me man a new guy has gone show body photo near plus okay Friend, now delete front, I have to delete it differently than before, I have to delete the note with night sweet zero, this is the front page, so how can I do this in work, node and equal to that which is on your front, the next front key which is on the neck is your excel. Front is right type of value request to end what value it will be absolutely great and in the middle I have to delete this note so we can talk on the gender list that this work can be done easily like this I am Android a plate function now I am in gym I do that Android and it will delete itself and also set its next9 previous quarter. Okay this is the work that has been blasted, by the way the work is getting repeated so I have done this work that here also node and equal so L Dot had to remove the previous Lajwanti, so I have asked for the previous note and its data is velvet, so end data or I will say Android delete A, then this guy will be removed and return it, tighten the bud, now I have to work in this digit function. So this note goes to the note, this note corpse will be a quality here, a public wide it, basically what will it do, we will see, tomorrow at any time, this is made, okay medicine, the whole city can speak that before you, your previous But there will never be a tap, so you will not need to do that and here also there will never be a tap on your next because now we have the effect, what do you have to do for 20, now you will remove this temple, it is the situation as it is now or From two notes, here you have one on the next, you have your prevent, this on your next, this is the closed Jhala environment, you have to establish a direct connection between these two bonding, basically, this point, if you get this notification, then it will automatically remove me. This work is very easy, note, entry from previous is equal to hands free, I know, there is no need to increase, this is the previous and next, put the next on the next of your previous, then basically this one will be linked or is your previous and This is next to you have also placed it next to the reverse and for this point, you have to keep the previous on the previous of next. Pune's jeweler is equal, so one previous Priyanka has been deleted. Okay, the work of digit is also done and get front. So here if I have to return null if DQ MT is there then after deletion I have not decreased the size or decrease it no I have deleted that cat front then if the size is equal to zero then you will update null otherwise you will update. is not front daughter this is is not front daughter this is is not front daughter this is front torch light if sa is equal to zero then return two null else return real dot previous daughter rep's previous our actual prayer is anti so here we have to set a pin size Guddu, zero, this soil is not the opposite, okay, so it is completely complete, let's run it and check Jhal. Okay, there is some mistake on the thirty one line, Jhal was current water with statement is written here, it would be that this mistake. I think, the price is rising, I have made a panel, I have to make it private, I just have to press this oil, all will be done, and I have to turn and replace it, the accused is increasing it, there is a mistake somewhere. What are the mistakes? Expected Output: What are the mistakes? Expected Output: What are the mistakes? Expected Output: This is often the output, we put it in front as a strict and then here delete is the prem kinnar pointer exception, so we have to see where exactly the mistake was, we made the mistake here, my tablet. Front Spray Basically what is said is that if Diggi Palace is MT then you have to file return height then this is the mistake done if here delete request is required on front and I don't have any it was destroying me in the evening Today if it is there then I had to return it in Al Fatiha. I had to return the excise total of 204 here too. Why was this not working? If the size was zero and I was asked to bill then my original one. And this one is the front, next to it is the original detail, now this one is fine, okay, so if I got a request, care, delete the front, then what had I done for free, I told the next one to the front, friend, you go and delete it. Get added means basically I told this person that if you go and get deleted then what mistake will he make? I have written the code here on it, I have accepted this, what is gym, friend, your next 9 previous two taps will never be tight and here Narwali condition will be there, its next panel is okay, so when I said something like this here, friend, if this guy has to be deleted, then he is next to the previous one, and next to this, he himself is big in the front, so this is what I should do, show that here. But I have given the previous message of the next one, there is a tap on the next one and if you free the tap dot, you will get a personal contraction, okay, so basically on the size zero one, I had done the wrong thing that hey man, come on, I had not thought about it is okay. The work is going on in the middle, the left is doing how, that is why 611 is working for everyone, now you see the logic of what was the previous entire structure, there will be a front of what it is, then the poison of what it is, feedback. Okay, okay and inside this is our original data, on the bra link list form, okay, this is our English front and this and when I was told to add it, I simply did a split here and cut this point. White called me, remove is the answer, so at last, here is the quality in me, collected this point and cut this point, I did this work, for both Delete Front and New Delhi Blast, I had the whole city for my front. My first stop is in front of 'Ling', remove this, first stop is in front of 'Ling', remove this, first stop is in front of 'Ling', remove this. Fonts, I am fine on this, I have picked up all the operations over the phone. The time quantity is tight, it is also an oven of functions and the space complexity is off. If it's tight then thanks for watching, see you in the next question paper.
Design Circular Deque
design-circular-deque
Design your implementation of the circular double-ended queue (deque). Implement the `MyCircularDeque` class: * `MyCircularDeque(int k)` Initializes the deque with a maximum size of `k`. * `boolean insertFront()` Adds an item at the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean insertLast()` Adds an item at the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean deleteFront()` Deletes an item from the front of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `boolean deleteLast()` Deletes an item from the rear of Deque. Returns `true` if the operation is successful, or `false` otherwise. * `int getFront()` Returns the front item from the Deque. Returns `-1` if the deque is empty. * `int getRear()` Returns the last item from Deque. Returns `-1` if the deque is empty. * `boolean isEmpty()` Returns `true` if the deque is empty, or `false` otherwise. * `boolean isFull()` Returns `true` if the deque is full, or `false` otherwise. **Example 1:** **Input** \[ "MyCircularDeque ", "insertLast ", "insertLast ", "insertFront ", "insertFront ", "getRear ", "isFull ", "deleteLast ", "insertFront ", "getFront "\] \[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, true, true, true, false, 2, true, true, true, 4\] **Explanation** MyCircularDeque myCircularDeque = new MyCircularDeque(3); myCircularDeque.insertLast(1); // return True myCircularDeque.insertLast(2); // return True myCircularDeque.insertFront(3); // return True myCircularDeque.insertFront(4); // return False, the queue is full. myCircularDeque.getRear(); // return 2 myCircularDeque.isFull(); // return True myCircularDeque.deleteLast(); // return True myCircularDeque.insertFront(4); // return True myCircularDeque.getFront(); // return 4 **Constraints:** * `1 <= k <= 1000` * `0 <= value <= 1000` * At most `2000` calls will be made to `insertFront`, `insertLast`, `deleteFront`, `deleteLast`, `getFront`, `getRear`, `isEmpty`, `isFull`.
null
null
Medium
null
215
Hello friends today I'm going to solve liquid problem number 215 Kate's largest element in an array so here we are given an integer area numps and an integer value K we need to return kth largest element in the array so the kit largest element is in the sorted order and it's not the distinct element okay and it's asking us that can we solve it without sorting so let's take this example and see how we can approach this problem and let's also look at the constraints so we are given that um K is less than or equals to the length of the nums and we have at least one element and the value of Noms could range from these to extreme values okay now using this example let's look how we could solve this problem so the first way brute force method would be basically to sort all of these elements and to find uh the kth element starting from last right so if we sort this element then we would get something like one two three four five and six right and since we have been asked to find k equals to 2 so the second largest element is equals to 5 right so what we do is just we count from the last where I is equals to zero and we keep counting until I is less than 2 I is less than K right so here I is equals to 1 and that is when we end up so we return this value at this Index right so this is sorting method and to sort an element it would take off and log n right log of n time complexity so we have been asked that can we solve it without sorting so yes we can solve it without sorting and that could be done by using a mean Heap as well so what is a mean here basically in mean Heap the element at the top it's kind of a tree so it's a tree structure and the element at the Top Root node is the smallest of all of these elements so let's suppose that we have been asked for to find the value k equals to 3 so kth largest value right so if we have a mean Heap with um uh with maximum of three nodes then the smallest value will be at the root node right and we know that smallest means it will be smaller than these two values so that will basically be kth largest element between these three one right so this is the concept that we are going to use here so what we'll do is we will insert all of these elements into our mean Heap so as we are inserting we insert three so initially there is no node so 3 becomes the minimum the element in the top and next we insert to as we're inserting two three two is less than 3 right so now our top element becomes equals to 2 okay so I'm just going to create a tree randomly I'm not following any uh algorithm like how the internal structure is so I'm just showing that the top element is 2 here now here we have one so now the top element is one so maybe we'll have something like this a branches and again we have five now so 5 is greater than one right so we could have five somewhere like this children of any one of the notes and now if you would look k equals to 3 right but here we have k equals to four so what are we going to do is we are just going to remove the top element from our in from our hip so the remaining element will be equals to the size of K okay so now we all only have remaining elements 2 5 and 3 so let us remove one so we'll have a tree something like this and then next we have the value 6 so we add six so let's suppose six calls somewhere over here now again the tree size is equals to 4 we need to remove one of those elements so we remove two and then we'll have a tree with only three elements I mean only three elements and this is the front next we again add a four so let's suppose four goes somewhere over here now again we remove the front element which is three so we remove three and then we need to have the minimum one right so the four will be the front because 4 is the minimum value so here 4 becomes the front Okay and four is branched out to these two values so since 4 is the front and now we have added all of the values in our nums so this becomes our result right because now we have a mean hip with only K largest elements right okay largest elements and among these the kth largest element is this one right that this is the third largest element this is the second largest element and this is the largest element so in this way we can use mean Heap to solve our problem so this is one way and in this problem the time complexity would be as we are iterating over each of the values in our nums array to add it to our mean hip so that would be oauth n and as we are inserting in our main hip we also are performing hipify operation uh internally right and that is a logarithmic time complexity so if our size maximum size is k then that would be log of K so our time complexity becomes o of and log of K and well this is less than the time complexity we used for sorting right which was of n log of and right so the this is a an optimization but it is not a huge optimization also so we can even optimize it and solve it in linear time complexity but I'll show it in a while let's first code this solution so let us first create our mean hip equals new um so in JavaScript uh it doesn't have a heap library but lead code provides us with the heat Library so I'm just going to use that one so mean priority queue so you can learn about this JavaScript mean Heap library or maxip Library in lead code okay so now that we have created our main Heap now for iterating over each of the num of nums okay and we in queue mean hip so in queuing include num and we need to check while we are inquiring if mean Heap dot size if the size is greater than okay then what are we going to do is we are going to remove the first element right so that would be DQ so we are dequeuing from our L our mean Heap now that we have our mean heap of Max size equals to K the front element will be our result right so we are going to return the front element so mean okay mean hey Dot front Dot okay print is a function and element is wear out is the property okay now let's try to run this and check if it works awesome let's submit this one great so we have been able to solve it using minhip now let's try to optimize it even more so that we can solve it in logarithmic time complexity I mean linear time complexity so thanks okay so what are we going to do is we are going to start by finding the minimum and maximum value from this nums array so basically we will create an array over here the minimum is 1 and the maximum is 6. so we will create an array of length um 6 and each of the indices will here denote the values over here okay so 0 1 2 3 4 5 okay so we have an extra one so I'm just going to all right so now that we have created our array in this error we are going to keep the frequencies of each of the elements so three hoot basically mean um it's pointing towards the index to right because like this is a minimum element so we would take the num and new M number minus the minimum value and minimum is equals to 1 and since this is a zero index area well we will end up at index number two so we insert the frequencies here so the frequency of 3 is equals to 1 also like each of these have frequency of one so we are just going to add a frequency of 1 over here let's suppose that we have two sixes okay so then this would be close to 2 and let's suppose that value of K is equals to 3. so now we have our frequency array now what we're going to do is we start from the last and we count the frequency so the frequency here is equals to 2 and then we again count over here the frequency is equals to 1 so 2 plus 1 is equals to three so now here we found a frequency equals to three so this is the kth element so this index will represent the kth element the index plus the minimum value right because that was what we used to find our nums I equals right I was equals to num minus minimum so now num is equals to I plus minimum value and that would be our result so this is using counting sort uh algorithm so now let's start coding this one it's an easy approach so first we need our minimum value so let minimum be equals to infinity and max value equals to negative Infinity now we are going to create an array of okay now we need to find our minimum right so let num off nums and mean value equals math that minimum of mean value and num and similarly max value equals math dot maximum of max value and not so this will give us our minimum and max value okay now once we have it we are going to create our array so the length of the array will be equals to minimum value I mean maximum value minus minimum value plus one so let array calls new array of length Maxwell minus mean valve plus one okay now that we have our array we are going to count so let's num of nums and um we also need to fill all of these with zero so initially the frequency is zero and then we are going to increment num minus um mean value plus so this gives us the index right and we are going to increase the frequency at that given index now that we have found our index let um count equals to zero and we are going to start our account from the end so I equals to error that land minus 1 I is greater than equals to zero and I minus and here um we are going to increment our count by the frequency at that given Index right and we need to check if count is greater than equals to K in that case we found our result and we are going to return okay return um index I plus minimum value right okay now let's try to run this code okay so what went wrong here awesome let's submit this one great so for this case the time complexity here is uh since we are iterating over each of the value in our nums array it is of N and this is also of N and here we are iterating until and unless we form the count to be equals to K right so if the length of the array is M so that would be of M so the total time complexity is of M plus n and the space complexity is of M over here because we are creating an array right and that is all about the solution so I hope you'll like my solution if so please like And subscribe to my channel thank you so much
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
520
hey guys how's everything going this is jay sir uh today let's uh continue our journey on lead code it's uh the first problem of uh daily challenges on august this one is detect capital uh we're given a word we need to judge whether the usage of the capitals in it is right or not we define the usage of capitals in the word to be right when one of the following cases holds one if all letters are capital like abbreviation or all letters in this word are not capitals like lead code or only the first one is capital okay all the other ones are not right cool so usa is through all capital and the flag the last g is invalid right so for each letter we have two cases the first letter uh it will not be lowercase and capital case right if it is lowercase so um what we care actually is the previous one right if it is prevalent is uh a vatted uh upper case like you then it's okay right it could be following any word or it's the previous one is uh vatted um as us uh lowercase then it's still okay and for if it is uppercase we check the previous one if it is a lowercase then it's invalid right because there the prevalence must work case then it's something like this it's not okay right yeah and uh the if the previous one is uh upper case then it is oh then it is okay right yeah if there are usa there's a another lowercase at the end then for usa here they all valid because yeah it's matted and then there's a lower case this lower case is invalid the previous one is a vatted uppercase but this lowercase is not valid because if there is a uppercase before a lowercase it must be the only be the first one so we need to check that also so for lowercase um for lowercase if there is a uppercase before it must be the first one right so that's the event invalid case so we can jump to the conclusion if lowercase the invaded cases is creef is uppercase and uh index uh okay it's and not the first letter right for the all the other cases then it's valid if it's uppercase if has have a lowercase before it invite it well this reminds us that we just keep two flags right so the first one is has which travels through the word and i keep two flags so the first one is hop have upper default to false let has lower false and then we will look through the word okay if it's lower case we use regular expression to do this test uh um word i if it is lowercase as we said if previous one is uh um when it comes to it to these index it means the previous uh letters are all valid right so we could just check if the previous one is uh um if there is uppercase or not if it is a lowercase we don't need to so if has uppercase right if it's already uppercase and what and uh is there is an uppercase and the index is not uh index is bigger than okay one and uh index okay has a pic uppercase and index is bigger than one but like uh the lead code like case here is it's valid right so it probably should be there will be no lower case right if no lower case would be all uppercase if this has if it has a lowercase it means that these letters are all valid because we come to these um lowercase so the condition should be has uppercase but no lowercase right and index is bigger than one in this case we return false and we upset it has lower to true energy is uppercase if has lower then we should return the force right for the audio outlet which means all uppercase then it's valid so we update pass upper to true we just use to these two flags to check and then we return if all these letters pass we return true right let's run the custom test cases true and we run like a and then u s a and the u s a they say and then u s a you run a code long time error index is not defined okay we use i okay true false true that looks good let's sum it great let's accept it so that's this one it's kind of uh simple easy one hope helps we try to analyze the invalid cases and uh deduct what kind of flax we need and we just look through the word okay that's it helps you next time bye
Detect Capital
detect-capital
We define the usage of capitals in a word to be right when one of the following cases holds: * All letters in this word are capitals, like `"USA "`. * All letters in this word are not capitals, like `"leetcode "`. * Only the first letter in this word is capital, like `"Google "`. Given a string `word`, return `true` if the usage of capitals in it is right. **Example 1:** **Input:** word = "USA" **Output:** true **Example 2:** **Input:** word = "FlaG" **Output:** false **Constraints:** * `1 <= word.length <= 100` * `word` consists of lowercase and uppercase English letters.
null
String
Easy
2235
94
doing analytical number 94 binary tree in order traversal so given in the root of a binary tree return the inorder traverse know its values so in order simply means visit all the left nodes first and then visit the node itself and then visit the right-hand side nodes after the words so right-hand side nodes after the words so right-hand side nodes after the words so in this case there's no right-hand side in this case there's no right-hand side in this case there's no right-hand side node but this is a basic binary tree the left node is two so we print that first and then the node itself is one and that's it in this case there is no left-hand side no so we have to start left-hand side no so we have to start left-hand side no so we have to start with one we print one and then two the right-hand side node so this one is more right-hand side node so this one is more right-hand side node so this one is more complicated so the layers again so we start with one there's no left-hand side start with one there's no left-hand side start with one there's no left-hand side so we don't have anything on the left so we print one itself so that's the one so and now we have to print the right hand side but before we can do that we have to visit the right hand side left node so we go to two and then the left node of it is three so and then we return the two so that's it and that's the algorithm we can do recursively by going through the nodes as i explained so we have in python the root node and we want to be able to return an array of integers which are the values of the array of the tree so let's go ahead and let's assume we already know what we're doing so the uh in this case as we have root so we want to traverse the left hand side of it as such so that hopefully return an array of all the lyft nodes and so we'll call that l and then the node itself we will call uh well and then the right hand side so right the right hand side node is going to be called same thing with dot right so hopefully that will turn an array and what we're interested in returning is basically just left so in python you can do something like this it can concatenate arrays and so the value should be in the middle right so the left the right and the value in the middle which is our current value and that should do it so now the thing is like we just have to check for the edge cases in this case uh if the root is null um if not root in python then return an empty array otherwise do what we just did here so if you ever encounter a null on the left side then the new route is going to be null so then it's going to turn an empty array so it's coming into red it's going to join it and it's going to turn that way so hopefully this will work let's go ahead and give it a try okay it says uh is not okay so we have to do something like that called the function oh great okay it works and we can submit it and see if the submission is accepted and it's good enough and i'm going to go ahead and give this a thumbs up alright thanks for watching see you in the next one
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
1,535
hey everybody this is larry uh now this is find the winner of an away game uh this is q2 of the poem uh this is actually for me this was a little bit of a tricky problem i don't i think there's some mathematical proofs around it or something like that but uh but i made two optimizations that uh so basically the key note is that k could be a billion uh so you cannot just simulate it at least not directly simulated all the other things is that n is 10 to the fifth which is a hundred thousand which is so you can't do anything n square has to be linear right and you could simulate in linear time so that's not a big deal but the way that you allow this simulation to work is noting two things um one is that even though k is a billion if k is bigger than the wavelength then once you hit the wavelength will just go in infinitely right so it doesn't really matter um and then the other case is that um you know if you just put this in a way like let's say this one all you have to do is just look at it back to back right like so basically you know where can the winner be from could win it can be from either of these places but if it's toward the end then you have to go through the loop once right so that means that if you do the array twice then this one will go through all the way at least once so that means that um just going through the array twice will allow you to uh enumerate all the possibilities using those two observations um yeah and because all the numbers are distinct uh i just have a cheesy thing to kind of ignore it and then beyond that you just have to keep count on how many um how many wins a number have uh so yeah it's a little bit tricky that the math or the observations are a little bit tricky to make uh once you make those observations and more importantly perhaps once you actually believe in those obstacle observations uh then it becomes easier um yeah and then i returned the first instance in which this is true and then if for whatever reason i don't know if this actually gets hit i can't prove it otherwise but um but because i think this should always hit but if i just put this as a thingy so maybe i'll play around later but yeah you could watch me solve this live next uh let me know what you think okay that's a little bit weird but okay only does everything twice okay darkest thing okay you
Find the Winner of an Array Game
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
Given an integer array `arr` of **distinct** integers and an integer `k`. A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds. Return _the integer which will win the game_. It is **guaranteed** that there will be a winner of the game. **Example 1:** **Input:** arr = \[2,1,3,5,4,6,7\], k = 2 **Output:** 5 **Explanation:** Let's see the rounds of the game: Round | arr | winner | win\_count 1 | \[2,1,3,5,4,6,7\] | 2 | 1 2 | \[2,3,5,4,6,7,1\] | 3 | 1 3 | \[3,5,4,6,7,1,2\] | 5 | 1 4 | \[5,4,6,7,1,2,3\] | 5 | 2 So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games. **Example 2:** **Input:** arr = \[3,2,1\], k = 10 **Output:** 3 **Explanation:** 3 will win the first 10 rounds consecutively. **Constraints:** * `2 <= arr.length <= 105` * `1 <= arr[i] <= 106` * `arr` contains **distinct** integers. * `1 <= k <= 109`
Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k changes.
Dynamic Programming
Hard
null
1,252
Scientist Hi How Are You I Am O Positive Welcome To Your Friend Today Bhi Dhud Urban Migration In Illegal Playlist Sombir Widow With Values ​​In Sure Thank You For Widow With Values ​​In Sure Thank You For Widow With Values ​​In Sure Thank You For Watching My Video And Everything In Every Day You Are Really Please Like Subscribe And Comment And Share Subscribe Geet Kaun Peena Cigarette Or How To Proceed With According Shoulder Disco Sansad Gave Amended Bill Not Go Into Waste Much Mode Turn On This Vishal S Fast S Chief Good Deeds And Crops And Ethics And Medicines 508 Sudhir And Kuch Deer Mein Doody Hey Indies morning he is in this is second morning sun so what is the president of do and columns you can see in these directions 8000 volume increase the self on the value wishes in one act 2009 that in one column gold is very Importance Number More than 90 Olympic Gold Previously One His One Medium to MP Vs Command handed over to Police Now This Water and Destroy The Devil Mufarad Will Get One Related Lucky Number-1 Devil Mufarad Will Get One Related Lucky Number-1 Devil Mufarad Will Get One Related Lucky Number-1 Miss 1510 Silver 908 Is So It's Women Has The Same and Will Change Suzy Robin thicke to and give them one so in this riot victims were frequent amazon man this country and back S2 speed less seat arranged has to begusarai bihar to increment is watching please advise closed serve welcome to kumawat note relation we are thankful that he prime minister And So Share It Is Vivek Solve Mode On WhatsApp Cars And Will Be Given Through A B Id In The Current Financial Year One Person Subscribed To This Channel Subscribe In This Life What Is Meru Ooo Ghar Reach Gaye In Ek Range And So Did So End Sisters and Columns Sonth and Just Making an E.M. Just Columns Sonth and Just Making an E.M. Just Columns Sonth and Just Making an E.M. Just Pending 1009 What is the Matrix Hue Dwivedi Rough and Graphics End K Cut in the Ninth Game 100 Wars to That What We Have A Ten of What They Have in This Apart You Won't Get Confused About Danger 100's or sugar syrup is also Battu's Fish Studio Frequency Adhesive Special and from the point of view of Control and Learn more Olympic Record 340 grams Desi Dabang in long pieces 12345 Scamable Bottled Water and Air Drop Down S Water Proof I Am just saying prevention and we were the way in which what ever I have behaved in this show will take place in the middle of Baghwa Olympic and other popular and diverse forms of Swift in range 500 1000 daily morning 10 absolutely till til-til 500 1000 daily morning 10 absolutely till til-til 500 1000 daily morning 10 absolutely till til-til long baby alarm morning 100 caller tune president n to hand matrix the magic of swords and ruby ​​now this magic of swords and ruby ​​now this magic of swords and ruby ​​now this column is the column of damascus or columns should sing in the same will do but he will change your comment for loop slow will take it So chat and will give villain is MB hai wa jeth vihada 200 what is MS road suite is column on a column jan because normal checkpoint range that you prem kanwar a cause a is range pain in back to give in the work number the number of twelve in that How Many Different Ok So No Problem Matrix of By Kamal.ji of By Kamal.ji of By Kamal.ji That Is Peeth Ke Is Not Divisible By Two Do It Means That Bewafa Ho Gallu And Have To Return That Aishwarya He Return Khant In Which One Slice Bread 100 200 Ye Kar Behaved In This Should Include a hui hai kar do hai to ke initial day first invalid s ko refer id in french and forgery in french a pan ok point is masjid matrix ok so is 130 dhyana rakhange aapko return tak account hai the kid has been friends let's celebrate rahu doc Ek WhatsApp Meters Wide Open Even Today BSP Hame Graphics Daabi Hai Waha Ka House Number Subha Hai Body Ro Byavlo Videos Morning Column Sona and Column Isse Mitro End Columns on This Column in This English BF Problem Hai Problem Solve Senior Submarine Neeru And Who Has Embarked On A Major Role In Palam Shoaib This Is Program Was Long Improvement And I Find The Number Of Value All Fans Them Length Bikini Model Of Every Where You Left May 010 Behave And Aveli Baghwa And David Warner Like This Video Share and subscribe be amazed
Cells with Odd Values in a Matrix
break-a-palindrome
There is an `m x n` matrix that is initialized to all `0`'s. There is also a 2D array `indices` where each `indices[i] = [ri, ci]` represents a **0-indexed location** to perform some increment operations on the matrix. For each location `indices[i]`, do **both** of the following: 1. Increment **all** the cells on row `ri`. 2. Increment **all** the cells on column `ci`. Given `m`, `n`, and `indices`, return _the **number of odd-valued cells** in the matrix after applying the increment to all locations in_ `indices`. **Example 1:** **Input:** m = 2, n = 3, indices = \[\[0,1\],\[1,1\]\] **Output:** 6 **Explanation:** Initial matrix = \[\[0,0,0\],\[0,0,0\]\]. After applying first increment it becomes \[\[1,2,1\],\[0,1,0\]\]. The final matrix is \[\[1,3,1\],\[1,3,1\]\], which contains 6 odd numbers. **Example 2:** **Input:** m = 2, n = 2, indices = \[\[1,1\],\[0,0\]\] **Output:** 0 **Explanation:** Final matrix = \[\[2,2\],\[2,2\]\]. There are no odd numbers in the final matrix. **Constraints:** * `1 <= m, n <= 50` * `1 <= indices.length <= 100` * `0 <= ri < m` * `0 <= ci < n` **Follow up:** Could you solve this in `O(n + m + indices.length)` time with only `O(n + m)` extra space?
How to detect if there is impossible to perform the replacement? Only when the length = 1. Change the first non 'a' character to 'a'. What if the string has only 'a'? Change the last character to 'b'.
String,Greedy
Medium
null
1,658
Hello Hi Everyone Welcome To My Channel It's All The Problem Minimum Operation Studio Sector-20 Se Z In One Operation You Can Sector-20 Se Z In One Operation You Can Sector-20 Se Z In One Operation You Can Remove Left Most Women From Its Value By This Modified Cars Number To Do Subscribe - 151 To 30 Celebs Subscribe From Left To Right In just 120 days will start recursive function like write helper method and they will have an original but according to Al Bashir V is from write now surrender value of To feel activated and will take a minimum of this to life minimum of helper that attack also elemental incremental oneplus one shades subjects - numbers of one shades subjects - numbers of one shades subjects - numbers of e-mail who e-mail who e-mail who is the one 40 like sharing electrons element and sacred meanwhile helper that first British and subscribe element presents subscribe our solve this problem will be one plus one our vikram relation and subscribe solution from subscribe like this is the missions early morning return maximum number of canteen and system will power for the answer cannot be that light maximum answer possible time Key 5 2010 Power Six Widows Maximum Video plz subscribe Channel subscribe our and like water side values ​​subscribe our and like water side values ​​subscribe our and like water side values ​​subscribe this remedy if you like and subscribe then what will happen when ever written this way leads automatically canceled it will not be active fennel just minimum soft destroyed in This Example The First Word You Hear More Start From Sydney Morning subscribe and subscribe the Light Element Festival Decrease Vanaspati subscribe and subscribe to 4000 Ki And Have Eat And One More Step Live 137 221 Anyway So They Can Keep Doing A In India And Abroad With A Subscribe 230 This Is The Solution Element Free Subscribe Like And Subscribe Every Year During Subscribe The Channel Please subscribe Video To This Industry Will Be Repeated His Quote Question Solved Edison Hai 202 Secretary One More Details Of History Will See The Repeated Problem Solved Indicators Which Can speak and apply in problem but still it will not help as big boss the size of fog solution will help to solve like subscribe and intense pain in time and subscribe to have so lets and device now they choose elements from left side and from outside So What We Can Do Subscribe My Channel I Will Be Id Am Id 2nd Subscribe Guest Yuva Vikram Seth And More Queensland 510 World Have No Know What We Will Strive To Start From Right 920 Free From Fear And See Meanwhile It Is Defined S Yediyurappa for all is equal to - 120 and subscribe and updated on that to - 120 and subscribe and updated on that to - 120 and subscribe and updated on that and flood light bill check if - some is in the and flood light bill check if - some is in the and flood light bill check if - some is in the map effect coordination committee not notice youth result from maximum amazon se withdraw from right side - verb - 4a withdraw from right side - verb - 4a withdraw from right side - verb - 4a 's development zero Elements pointed to offer 's development zero Elements pointed to offer 's development zero Elements pointed to offer any number of elements from left side is what ever determined from the maps for is what ever determined from the maps for Length of the day volume full reach india and will see results maximum dowry advice return result subscribe and subscribe the Channel subscribe our is so can we father optimizer time and space complexity select see this second me latke are turmeric element and midwing element from laptop and elements From the power development combined total will be found total power total beauty total wisdom total subscribe channel thank you will find the total boys loop subscribe this Lootpaat and bittu so this is the dangerous how will solve this problem you will get destroyed in Riots will understand using Dasham subscribe to is so let's implement code for decoding for what we will do first of all will create the target with me to find the target use this normal for Rukh subscribe this Video Please subscribe and subscribe this Video from start from right Element 000 to 1000 Like Subscribe in a reader quintal our opinion is Adheenam slot length hai ka naam start length and heavy increment our right place will be updated on a plus right swedish 920 check if current crossserver x current prospects in the case and the leftist Luno Request You Are Right Down What We Will Do Subscribe Value From 10 Friends Hum Idli Sandwich Subscribe Channel Subscribe Our Video And Subscribe Bhindi Sathi Feel That Positive Effects And Jesus Return Gift The Return Like This Window Size Still If It Is Not - 151 - 192 Returns The Video Is Not - 151 - 192 Returns The Video Is Not - 151 - 192 Returns The Video then subscribe to The Amazing Typo 200 Recording Compiled And Where Getting A Romance For This So Lets EGS Subah Window Size Cutting And This Point Is This Point subscribe and Share subscribe and Withdrawal Dheer Wa Air Chief Current Subscribe Seervi Looking for Window - Subscribe To Hai - Subscribe To Hai - Subscribe To Hai High Court Accepts This Is That Point Approach And Daily Wear Calculating The Time Pregnancy Time Table First Year Student Of Power Rangers subscribe The Channel thanks for watching
Minimum Operations to Reduce X to Zero
minimum-swaps-to-arrange-a-binary-grid
You are given an integer array `nums` and an integer `x`. In one operation, you can either remove the leftmost or the rightmost element from the array `nums` and subtract its value from `x`. Note that this **modifies** the array for future operations. Return _the **minimum number** of operations to reduce_ `x` _to **exactly**_ `0` _if it is possible__, otherwise, return_ `-1`. **Example 1:** **Input:** nums = \[1,1,4,2,3\], x = 5 **Output:** 2 **Explanation:** The optimal solution is to remove the last two elements to reduce x to zero. **Example 2:** **Input:** nums = \[5,6,7,8,9\], x = 4 **Output:** -1 **Example 3:** **Input:** nums = \[3,2,20,1,1,3\], x = 10 **Output:** 5 **Explanation:** The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` * `1 <= x <= 109`
For each row of the grid calculate the most right 1 in the grid in the array maxRight. To check if there exist answer, sort maxRight and check if maxRight[i] ≤ i for all possible i's. If there exist an answer, simulate the swaps.
Array,Greedy,Matrix
Medium
null
1,171
um hello so today we are going to do this problem which is part of um Elite code daily challenge remove zero Su consecutive nodes from linked list so here we have a linked list and what we want to do is repeatedly delete consecutive sequences uh that sum up to zero where the values sum up to zero until we can't anymore okay and then after that we want to return the link the head of the link list after that so you can think of it as collapsing when the sum is zero you collapse all of them so if we take a look at the this link at list here 1 + 2 is three and link at list here 1 + 2 is three and link at list here 1 + 2 is three and then when you get minus three um you could you collapse it okay um and you may ask well should we collapse this one or should we collapse this one and the answer is it doesn't matter because any answer that does collapse until we can't anymore would be accepted so in this use case if you had collapsed the to and end up with one two one that would be accepted as well so that makes it easier um this example we could collapse this here and we end up with because this is zero we end up with 1 2 4 if we do this one we collapse these and then we end up with one 2 minus two we collapse these um and we end up with zero or you could do collapse five because you get five and then minus five so it collapse those so that's the idea now how do we solve this we'll do first the simplest possible solution and then from there we can do a more sophisticated one so the first less like just simplest first solution it's to convert the linked list to an array and then collapse the array until you can't anymore and then convert it back to a linked list so that's pretty straightforward so let's just write it down and then from there we can do a solution that doesn't convert to uh a list so just um first conver converting a link list to an array you just Define your array um let me just refresh this so that we get highlighting so first you just convert it to an array so basically you just have this poer to the linked list and each time you advance it and add the value okay so by the end of this we'll have in a we would have the same values here and now we can just collapse it until we can't anymore so we need to just Define a function to collapse and since if you look at the constraint here we have up to 1,000 noes constraint here we have up to 1,000 noes constraint here we have up to 1,000 noes so this should be a pretty simple two Loops so how do we do that we create a new list and then we go through um each range if any range is equal to zero we just collapse and by collapsing means if from I to J the sum is zero we just remove that I J what does removing well we can just return a list for anything before and anything after so let's say you have I here J here and then you had something before so and the sum here is zero what do you do well we just return this and plus this that would basically give us a list without the range that sums up to zero okay so that's what we are doing here now this collapsing we want to keep doing it until we can't anymore what does can't anymore means we do a pass and we don't find any range that some up to zero okay so how do we do that well first we need to initialize with a list let's call it collapsed um and then we can while the collapse it is different than the current list keep collapsing okay so um but we also need to say we don't we shouldn't keep collapsing the same list we need to collapse what we previously already did right so that's what we do here um and now we can just create at the end of this what we have here we stop only if we can't anymore okay um and so now when we can't anymore we can just construct back our linked list so we just need a d linked list to hold the beginning of just a node before the beginning so that we can return at the end the next value and then we go through this collapsed list and we add each value as a node um so in this case for example let's say for this one we would have here um collaps it would be equal to uh 31 okay and so we just say 3 first 0o and then point that zero to three a node of three and then go to the next and point that to one and our d node would be pointing at this zero here D node would be pointing here and so to return we want to return 31 and so we return D next which would be here okay so that should be straightforward solution if we run this submit it should get accepted okay it does work but if we look at the term complexity here o n here n is the length of the linked list of n here because at most we will do let's say n times if each element is zero so oven plus oven and this is oven as well so ENT time but the problem is we have this extra list that has length OV this extra list also each time which has link oven so we have a lot of extra space we are using here so how can we do this without too much extra space and without converting to a linked list uh let's see how we can do that sorry without converting to an array let's see how we can do that um okay so let's see how we can tackle this so if we take the first example here the main idea is let's say you are just using Anar link list like I did here how would you do this well how would you do this in an efficient way well one way to do it is to keep track of the sums you've seen so far right and so just a hash map uh for the sums and the position you've seen the sums in and so for example here you can say even before just to see your map this is usually good um you can say maybe we have a sum of zero maybe at index uh let's say you could either do at index minus one or you could say you could start at zero to the array and have this at index zero it doesn't really matter um and then we have a sum of one a prefix sum of one at position zero prefix sum of three at position one um and then prefix sum of um now of zero right because here we have three 3 minus three at position two prefix sum of three at position three prefix sum of um five at position four now why with why is this useful well look at this look at what we have here of this zero and this zero okay when we are at this prefix sum we will find that we've seen this before we've seen this value before and so since we've seen this value before that means you could actually just collapse all of this and end up at with just position three and four okay so basically what this means is that if we find a prefix sum that is already in scene then that means we can collapse let's say this prefix sum is at position J and what's in scene is at position I that means we can collapse um I to J okay so that's the core idea here um because if you have zero and you had zero before prefix sum is just the sum right and if you let's say have zero and now you have zero that means what's was here is a wash which means it's equal to zero same thing it doesn't the value doesn't have to be zero if you had two a prefix sum at position let's say two at position maybe four and now we have two at position eight what does this mean that means the values in this range here didn't add up didn't add anything right so that means the values here didn't add anything so we are we may so it means their sum is zero right so that's the core idea that we'll Implement there is one thing we will do so we will build this scene from just the link list we don't need to convert to an array to build it we can just go through the linked list and build it and then once we build it what we can do is just go through our linked list again so let's say our linked list here with this scene now is one to two uh 2 - scene now is one to two uh 2 - scene now is one to two uh 2 - 3 to one so we'll go through it and we look at each value we will keep track of a prefix sum so first it's equal to zero and when we go here well now it's one do we have any one value one in scene not yet uh do we have any value one in scene um we um so at zero do we have we add this value okay um and then do we have any value no at one no and so um we keep going because if we use just this value we'll just make that next equal to two so same thing it doesn't change much at three uh same thing but our sum now is um sorry our sum now is three so here we are here uh and then we look at uh what is the prefix sum of three same thing we are still going to minus three but then when we have minus three now we have zero did we see Zero before yes we have zero in scene so what do we do well we need to point the current value which is now here we need to point the current dot next to be the position the prefix sum which in this case it's not going to be a position it's going to be a node so here instead of adding a position if we are doing a linked list we'll just point to a node we can just point to the next that node because basically anything from current to that node at the perfix sum was a watch so the sum was zero so we need to get rid of it so what this would mean is that we will Point our um current which was we'll Point our um current to this one okay um so basically when we are at this zero we'll find that we have this zero so when our current is even before at the dominoe of zero we oh we have a zero already so let's just point to it so this is a wash okay so that's the idea here um okay so that's pretty much the idea is we construct the prefix sum and since we have a zero we know that anything in between was a zero so at the start at Domin know zero we'll just point this to this one to the next of this one which is this three here okay so that's the core idea um now let's take another example just to make sure this is clear so let's take one 2 3 minus let's actually do it with a link list just to make sure it's super clear so one two to go to three go to minus 3 go to four Okay so we will build first our scene um and now we first we start at zero uh let's call it in the at the front um which in our front let's have a d node here just so that we don't lose the pointer to one here and so it's going to be that let's call it front our demin node here let's call it front um so that has a value of zero and now value of one points to let's call it node one okay um let's actually do the entire thing so the sum of one points to this node okay uh minus three and now we go two the sum three that points to two 3 - two the sum three that points to two 3 - two the sum three that points to two 3 - 3 um and then four and then the node minus 3 points to the node sorry now uh we do uh sorry this is not this is three but then when we add this three is going to be six okay 6 now points to 3 - 3 4 and six okay 6 now points to 3 - 3 4 and six okay 6 now points to 3 - 3 4 and then when we add minus three uh 2 six that's going to be um uh 2 minus 3 that's going to be three okay now 3 points to minus 3 4 and then when we add four 7 points to 4 and that's what we have here okay so now we do another pass to collapse uh what we've seen before so first we have zero do we see Zero before no so we keep that zero um one do we see have do we have one in scene no um so we keep one do we have uh two and then we have um the prefix sum now is three because 1 + two so do we have three yes because 1 + two so do we have three yes because 1 + two so do we have three yes we do have three here so we should point a um so we should Point our next to the next of the prefix sum which is this node here four okay so we point that to four um and we end up like this and now we remove it what was a wash here okay so that's sort of the idea create a scene so that you can know what the same values that you have later on so that when you find a value and you have the same before you know the range in between is zero and you can just point to the next one okay so that's the core idea now let's build it up and make sure it passes um okay so let's do this so the first thing we said we need to do is um create our front which is going to be just a dum Noe that is zero but has the next value as the head right because we'll just put zero in front of the linked list and we'll start our traversal from that front node and then we'll keep track of a prefix sums that we added to scene and then we need a scen hash map right and so first the prefix sum is zero and our scen hash map needs to be um uh need to have just the value zero for this dominoe front right so this would be equal to zero and then we have a scene that um is equal to uh zero that points to front okay and now we'll just do while current equal to current. next and we need to keep track of the prefix sum so far so and the scene for prefix sum is going to be equal to what should it be equal to it should be equal to the current node right we are saying we have a sum a perfix sum of plus a three at this node and so we say current here and now that we build our prefix sum we will do another the traversal so we need to initialize again to front and keep going um we'll do the same traversal but what should we do in this traversal well we should again we want to keep track of the prefix sum so when we are at let's say value of two we want to know if in the future we have that value of two which means the range in between is zero and so we will keep updating the prefix sum now for the scene of the prefix sum that next what do we want to do with this we want to point the current next okay now you might say okay what if we don't have any values in the future that is equal to this prefix sum well in that case we will have only the current value so we'll point just to the next node of the current node which is equivalent to not doing anything so we don't need to do a special case for if there is no same sum in the future but if there is a same sum in the future we'll just skip to that sum because anything in between is equal to zero okay that's the core idea now once we do this we can just return our head of the link list which because front is a dominoe is just front D next this would be the collapsed link list because we collapse using this here okay um and now if you look at this solution uh oent traversal another oent traversal here so V time overall in terms of space we are only using this extra scene map which is oven um so it's still oven time oven space but it's better um it's better overall since we are not converting to an array and we are not creating an array each time a new array each time will collapse um so if run this submit it does gets accepted okay and yeah that's pretty much it for this problem thanks for watching and see you on the next one bye
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
231
in this video we are going to solve problem number 231 power of two so let's read our task first given an integer n return true if it's power of two otherwise return false integer N is a power of two if there exist an integer X such that n is equal to 2 the^ of X and such that n is equal to 2 the^ of X and such that n is equal to 2 the^ of X and here you can see several examples if n is equal to 1 we are going to return true because 2 the^ of 0 is equal to 1 true because 2 the^ of 0 is equal to 1 true because 2 the^ of 0 is equal to 1 if n is equal to 16 we are going to return true because 2 ^ 4 is equal to 16 return true because 2 ^ 4 is equal to 16 return true because 2 ^ 4 is equal to 16 and if n is equal to 3 we are going to return false and also you can see our constraints and is any integer numbers so you must think about some mathematical solution like check the remainders of the division n by two and then divide n by 2 until we reach one and so on but there is actually much simpler solution you should think about the binary representation of our number n so let's think how to convert number from decimal representation to Binary representation if n is equal to zero in binary representation it's also zero if n is equal to 1 in binary representation it's one if n is equal to 2 in binary representation it's 10 if n is three in binary representation ation it's 11 four in binary representation will be 100 and so on so basically we need to represent our number n as the sum of powers of two so it will be the sum of BK multiplied by 2 the Power of K where K has range from zero to some number n and BK is our bat Z or one and from this representation it's clear that if number is the power of two then it will have the next form8 is 2 the power of 3 so according in our formula in binary representation it will look like 1,6 which is 2 the Power of 1,6 which is 2 the Power of 1,6 which is 2 the Power of 4 in binary representation will look like 10,000 so basically in a binary like 10,000 so basically in a binary like 10,000 so basically in a binary representation any number that is power of two will look like one and amount of zero that is the same as uh the power of two so 4 is 2 to the power of two so it looks like one and two zeros 8 is 2 to the power of 3 so it looks like one and three zeros 16 is 2 to the^ of 4 so it three zeros 16 is 2 to the^ of 4 so it three zeros 16 is 2 to the^ of 4 so it looks like 1 and four zeros so we need some way to identify that our number our decimal number in binary representation looks like one and several zeros and how we're going to do it in this case we're going to use bitwise operators you might think about using shift operator to check that you have all zeros at the end of your number and one at the beginning but there is actually much simpler way to do it and time complexity of this procedure will be 01 and I'm talking about bwise operator and that I'm going to use for our targeted number and for the number andus one because 1 4 looks like 100 3 looks like 11 so all Beats that are 0 4 are 1 for three and bit that is 1 for 4 is 0 for3 and if I'm trying to use bat wise operator for this two number the outcome will be zero because all Beats are opposite 1 and 0 is equal to zero and the same for example 8 and 7 if 8 looks like 1,000 in example 8 and 7 if 8 looks like 1,000 in example 8 and 7 if 8 looks like 1,000 in binary representation 7 or nus1 will look like 0 1 and if I'm going to use bitwise operator end the outcome will be zero because all bits are opposite let's also talk about our special case 2 the Power of 0 that is equal to 1 one in binary representation is 1 and 1 - one in representation is 1 and 1 - one in representation is 1 and 1 - one in binary representation is zero and of course Z and one will be equal to zero now let's go back to the lead code and Implement our code okay so first we are going to check if N is a positive number because if it's zero or negative we're obviously going to return false and then I'm checking n and our bitwise operator n minus one and if n and n - 1 is equal n minus one and if n and n - 1 is equal n minus one and if n and n - 1 is equal to Z it means that n is the power of two because n has representation one and several zeros but n minus one is all ones let's submit our solution and check the result and you can see that our run time is 0 milliseconds because once again time complexity is 01 and we beat 100% of users with C++ and if you use C 100% of users with C++ and if you use C 100% of users with C++ and if you use C or C SHP code will be the same for C and C SHP so you might take this code from my GitHub or write it yourself and check the result for C and C Shar will be also great as for the python code will be exactly the same if n is nonpositive number then it's obviously not the power of two we are going to return false and then we are going to check if n and our bitwise operator n minus one is equal to zero if so it means that n has binary representation as 1 0 and so on that means that n is the Power of Two let's submit our solution and you can see that for python we also have really good results we beat 83% of users regarding runtime and 96% 83% of users regarding runtime and 96% 83% of users regarding runtime and 96% of users regarding memory I hope this lesson was helpful for you if you write your code in different programming language I will be happy if you share your solution in the comment section and see you in the next lesson
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
296
let's go to question number 296 best midpoint this is hard question let's guarantee it has a lot of summer a group of two or more people wants to meet and minimize the total travel distance you are given a two degree of values zero or one where each one mark the hormone of someone in the group the distance is calculated using manhattan distance where distance p1 comma p2 is abs p2 dot x minus p1 dot x plus p two dot y minus p one dot y okay let's check the example one okay this one is given so there are three houses one two three so middle is here right so we have to get distance from this is 2 and this is 2. so total 6. did this make sense okay how are we gonna do okay let's say this one is not 2d dimension okay let's say this one okay let's say this is one dimension and then can you calculate the distance how you have it quickly that's right just we found the medium value so when you found it and then just get calculation from distance with this one so this one with this one is all one two three so this is three and then it this one distance is zero right zero and this one is three so answer is six we easy to calculate it but if uh our abn is the 2d so how we got it okay today i'm gonna solve it with uh the medium value and then soaring and then finally i would like to use one idea convert 2d to 1d okay actually i will split the both one is columns index of columns and another is index of law and then finally we will add the two distance loss distance and column this the region why we're able to do that is we are using manhattan distance right so distance must be did not this one just going right hand bottom that is so we able to split two things okay oops okay so okay let me so my approach is let me simulate approach first before that let me write approach i'm gonna use the 2d to 1d and then i will use and salting and using media medium value so first create toy name is blouse and columns and then next scan the grid and if read loving column is one i will put blouse of paint love and curves and then after that sort are laos and curse so last salt and curse salt and then next is canned medium los angeles so uh-huh medium uh-huh medium uh-huh medium low it must be loss and medium index is length close by two with the colors the same colors length curves divide two so now some all of c from medium value so must be return some okay and then let's get abs because we need to get only distance so low calculate minus the amount for loud in gloves and plus some is typed column like abs car minus the car maybe we can able to calculate it okay um okay let me simulate the code by using this one okay let's say this value is input insert it and then okay now first we make routes and cars and then now we are here and if grid 11 column is the one house and then we put this one is and then next is this one is four and then last is this one is two comma two right so we have information over rows and the information first and then next sorting so if the serene is here and then can medium which one is medium value right central is medium right so medium column is two so finally return a medium low comma zero is zero right zero plus and then zero is also zero plus two minus zero is two plus medium column zero minus two is two plus two minus two is zero and finally four minus two is zero so return six does this next set okay let's implement the code first i'm gonna calculate and is length grid and then four row in range i'm gonna scan uh cell in grid so m for column in green if read low column is one and then i will put lows up and low columns of pen upgrades and then finally i resort to laos salt and then carrots assort and finding the calculate medium law is must be loss and length loss by two medium columns of curves length curves by the two and then finally they turn some abs low minus medium low for low in range i will get from loss plus it's time to calculate cars pbs curves minus curves for car in cars okay that's not the code this is not correct for okay 47. um this is soft light okay looks good not bad okay let's check the complexity great to array this is the uh-huh great to array this is the uh-huh great to array this is the uh-huh o1 o m worst case and then this is our o command time complexity and this space is one and then this one is omm low gamma because we use soaring one and then this one is a one and then some this one also omn so finally time complexity is equal mn log mn and then space complexity is because we use low end cars thank you
Best Meeting Point
best-meeting-point
Given an `m x n` binary grid `grid` where each `1` marks the home of one friend, return _the minimal **total travel distance**_. The **total travel distance** is the sum of the distances between the houses of the friends and the meeting point. The distance is calculated using [Manhattan Distance](http://en.wikipedia.org/wiki/Taxicab_geometry), where `distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|`. **Example 1:** **Input:** grid = \[\[1,0,0,0,1\],\[0,0,0,0,0\],\[0,0,1,0,0\]\] **Output:** 6 **Explanation:** Given three friends living at (0,0), (0,4), and (2,2). The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal. So return 6. **Example 2:** **Input:** grid = \[\[1,1\]\] **Output:** 1 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `grid[i][j]` is either `0` or `1`. * There will be **at least two** friends in the `grid`.
Try to solve it in one dimension first. How can this solution apply to the two dimension case?
Array,Math,Sorting,Matrix
Hard
317,462
725
Hello gas welcome to me YouTube channel so today we are going to solve problem 725 split link list in parts ok so what is this question about I have been given a head of link lift and I have to split it in the text of It is okay that it has to be divided into parts and the length of all the parts should be equal. If it is equal then it is good otherwise one more can be greater, meaning a maximum can be one size greater, so I have to do it in sequence. It is given in the sequence like one two three square I have this link list 12 and after that the second one in the text is 34 okay but mother take part like Rahat one two three four five is okay now if we divide it into two parts then It should remain equal or one can be greater and which one will be greater then what will we do now if we start then what will be the length of each part, the value of k equal to 3, here is three, then how will we divide, ok if we divide by then three means 3 has to be divided into 3 sizes, now see but here there is one extra left, if we divide 10 by three, then one extra will be left, otherwise one will be left, which if we give in the left part, then 1 2 3 and here it is done and then 567 left. This will be done in three times, text justification means the problem is as it was, okay, so this is a question, so how will we solve it, first of all, I should tell you its size, then I will know what is the size of whatever part it is, okay? So, what will we do for that, first we will find the length, so first we will run a loop to find the length because I have how to find the length, first here is here, then came there, then length plus happened, then next page again length plus happened, let's do the length like this. Whatever is A will go, the second part has to be divided into three parts, okay, now the step is you, if you divide it into three parts, then this lesson has to be given in Kalyan, okay, then how will the extra come out, Tan Mode 3, 1 A, Gaya Mode, on doing the mod, did it in this. If Tanot three one comes then there is an extra one in it which you have to give to that in the left part. Okay and in any other part in the left part it is not that maybe as much as this child like mother of two children, take relief till 11 so this is not. Can it be 12? No, it doesn't have to be done like this. It's okay, it does n't have to be done like this at all. What do I have to do? This is given so 4 is divided into 3, which means whatever is the length, the difference of none should be more than one. Okay and as much as it is equal, it is possible that it should remain equal, so see what is happening here in the length, look at the length, what is the length of both of these, this is five, this is three, five minus three, two, so it should remain the same, so what will we do first? So, we will divide into as many parts as we want and then we will divide one by one from the left side, first it became 3 and 4, after the pickle, then 56788, what kind of methods are there in it, like one is three, it is okay, so we can divide by one. We will do two or three in one and as many children as there are children, we will give tap in it, tap, so what we did before is to make it better, you can create the aerial list in Java and you will definitely not have to do it in Tamil Nadu, so it is okay then you It is going on among the people to divide as much into parts as it was to be done into three parts, so how did one part come out by dividing, so like for this one, you are for three four, if you have come for the first time, then what if you have come for the first time? What is divided into 1 2 3 parts will be 33, won't it be 10/3 is 3, so 3 will be in 3, sir, so it is 10/3 is 3, so 3 will be in 3, sir, so it is 10/3 is 3, so 3 will be in 3, sir, so it is three. Now look at the extra one, if you start giving from the left, then check the extra. After doing the mode, how to take the mode. What is the mode and what is the size of the lesson, how will it come out then it will not work because giving extra is greater is equal to zero, it is not there because the extra is finished, there was only one extra, right, only one came after dividing 10 by 10, then it will not work. There will be only 567, then second time will come, then it will go till p5 and then how much will come. This is the size of the part. See P. Here, this is the size of the part. Plus, its size is three now, okay, so how to divide it in 12311, what we are doing is to divide it, so see how the parts will come out, if we know how to find the parts, then after coming in extra, there will be one, in this, zero will work because take- On doing 'K' there is zero 'A' zero will work because take- On doing 'K' there is zero 'A' zero will work because take- On doing 'K' there is zero 'A' but extra will be added to 'Extra', 'Extra' will be added but extra will be added to 'Extra', 'Extra' will be added but extra will be added to 'Extra', 'Extra' will be added to 'Extra', 'Extra' is greater, ' to 'Extra', 'Extra' is greater, ' to 'Extra', 'Extra' is greater, ' Den' is zero, then 'A' is gone, then it Den' is zero, then 'A' is gone, then it Den' is zero, then 'A' is gone, then it became a part, then it came to 'Extra', then ' became a part, then it came to 'Extra', then ' became a part, then it came to 'Extra', then ' Extra' is greater, 'Den' is zero, yes ' Extra' is greater, 'Den' is zero, yes ' Extra' is greater, 'Den' is zero, yes ' Extra &gt; 0' in the second time. In the second bar, Extra &gt; 0' in the second time. In the second bar, Extra &gt; 0' in the second time. In the second bar, then you went to a, then to three a and it continued till three. In all the rest, we have first created the vector and inserted null, so null remained in it, so how is this one handling it, okay, so its time. How much is the complexity, how much is the first account, how much is loaded in it, then how much is its total in N plus, order of you N, then it is order of N, so this is it, so its complete code is such that your notes are counted and then vector is made. Joe's side is everywhere else, then this is the zero index which is used to trade in the vector and the same is the H part which is derived from it, after taking the part P which is the size of brother's eight part and kept the extra one. And we were giving it one by one from the left, we are seeing that as long as the greater den is zero, we have to start giving it from the left, then the extra one is also giving it and to set it in the vector that is equal to zero. If you took it and returned it in the last, then it's okay, in the next video, please like and subscribe my channel.
Split Linked List in Parts
split-linked-list-in-parts
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return _an array of the_ `k` _parts_. **Example 1:** **Input:** head = \[1,2,3\], k = 5 **Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\] **Explanation:** The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null. The last element output\[4\] is null, but its string representation as a ListNode is \[\]. **Example 2:** **Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3 **Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\] **Explanation:** The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. **Constraints:** * The number of nodes in the list is in the range `[0, 1000]`. * `0 <= Node.val <= 1000` * `1 <= k <= 50`
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
Linked List
Medium
61,328
1,368
hey what's up guys john here again so this time let's take a look at another lead code problem here uh number 1368 minimum cost to make at least one valid path in a grid hard problem i like it very interesting problem so basically you're given like a m times n to two-dimensional grid times n to two-dimensional grid times n to two-dimensional grid and on each positions there is a value from one to four it represents the direction of the arrow basically so one means right two means left three means down four means up and uh right so basically you're given like this for example you're giving like this like four by four 2d arrays and now each of the elements represents the direction of the arrows and you can only move the to this direction and then okay so what is ask you that uh it asks you okay one more thing is that uh you can change at any you can um once you're you add any cell here right you can modify that this arrow direction only once only one time only right basically you can modify this one from pointing to the right to pointing to the to down right and the cost of doing that is one right so and then it asks you to find the minimum cost to make the grid basically the minimum change you need to make so that you can travel from the left from the top left corner to the bottom right corner if the basically if you're travel traveling along with the uh along with the arrows there's no cost only when you want to try to travel to a different direction uh comparing to the to this arrow then you need to uh you need to add your cost by one and they ask you to find the minimum cost to travel to down here right very interesting problem okay so let's take a look at oh some examples here so here we have we need we can uh change three arrows to make us travel to this uh target point and the example two here is here if you follow this example right if you follow this path from me if you follow the path okay from here oops sorry from here to here and then here and here right so in this case you don't need to make any change of any arrows all you need to do is just follow the direction of the arrows defined and then you can travel from start to the end point right so at the beginning you know when i saw this problem i was thinking okay since we have this kind of definition here can i use dp to solve this problem right so i was like um okay can i try to define a 2d dp basically a dpf db inj right so dpinj represents at the current position what's the minimum cost i need to make so that i can arrive at this current state right that's like normal attempt right basically normal attempt and then while i was trying to write uh write the dp state conversion func uh function here i realized that since we have uh since this arrow can be changed to any direction right basically both up down left and right which means that for example if i had dpi and j here let's say if you are at this position here right not only it can be uh can be reached from the previously row and column right but it can also be reached from the future row and column right let's say we can also reach this dpi and j from dp uh i plus one right and j or the other i j plus one which we which are the states we haven't we hadn't been calculated yet right and you guys may already know that one of the preconditions of using dp to solve a problem is that all the pre other previously all the sub problems to get the current to get to the current uh state has to be calculated beforehand already right when once we uh when we are at this inj basically we cannot depend on any future or slash un calculated states to calculate to get our current state right this like inter dependent right interdependent to each other which cannot be solved by the dp problem can not be solved by the dp technique here so then if we cannot solve it by dp then the only choice we have here is the graph right basically we have to do a and then i was like since it asked us to find the minimum cost to make the find the to the final place right final target position um i need to use some i need to use the breadth first search right but then i got stuck again because i was like with bread first search how can i build this graph right so because we have the graph here let's say we have a i was like from the zero i can free i can be free i can freely travel to any of the following uh positions by no cost right then i was like can i try to build like a graph such that from the current positions uh if it can be traveled to any of the positions without any cost then i will add that add address to this current position right and then i was like um if that's the case how about the ones that the position that we cannot be traveled from here right how can we add those edges right to the graph right because to be able to travel from the start to the end point right so we have to have we need to have like a complete graph of each of the elements right if we're only considering the places we can travel from here then how about those ones we cannot travel right and uh so that's because of that the normal native bread first search graph will not be helpful to solve this problem and so what we need to consider is a graph with a weight on each edge yeah this is also kind of new to me because i never yeah because i never built uh i never built like a graph with weight before but now i saw this problem and one of the takeaway for me is the next time when i see this cost right cause to move from one place to another i should have thought about a graph with weight on each edges right okay so with that being said what we need to do here is that at each of the position i and j here right inj we try all four directions right basically we will be travel we'll be trying to we'll add in we'll be adding uh four edges to the current i and j right but the only difference here is that those four edges have either zero or one cost on top of the edge right as you can probably you guys already uh realize that if the address is following the same direction as this arrow here right then the weight on that edge will be zero for all the other edges right the weight will be one right so this will be zero this will be one then this will also be one go up there's it's not a valid edge right so and now after trav after traversing uh all the elements here we have built like a graph which added which wedges with a weight on each edge right and then now the problem is converted to uh to calculate the minimum path from start to the end point right because the co it asks us to get the minimum cost which is the weight on each edges on each edge right so we just need to uh to calculate the minimum weight total weight on the address from zero to this endpoint m and n right and that for that we need to use the dicastro algorithm to solve this uh minimum path right the minimum or distance or minimum weight whatever you want to call it from start to end point okay so with that being said let's try to code this problem and i will be explaining a little bit more about that die crystal problem while recording it okay so first thing first and let's build the graph right so m equals to the grid right and equals to the great uh zero right and then we also need to build the directions right so what's the direction here the we have to have a four directions here right four directions here is the uh directions and you know since in the future uh we'll be using these values right for each of the direction for the for me for to make it easier to compare uh the current uh arrow direction with the direction is itself right i'm instead of using a simple array here i'm using the uh i'm using a dictionary but you know what let's try to uh let's try to use this simple like uh list here to represent four directions let's see if we can if this will work with that then we don't have to make it like a dictionary so first is the uh right so the right is going to write is zero one right and then going left is yeah going left is zero minus one right uh same for the uh down on the right so for going down is one uh one zero right and then for going up is minus one zero all right so now let's try to uh okay so graph right so we're gonna have a graph it's a default dictionary uh it's a list right since each uh position could have up to four edges that's why we're using a list to store all the edges for the current position so then simple nested for loop here j in range n right so now we need to have four directions here right and not another place is the four directions in directions right so for four for each directions we need to find the we basically we have to compare with the uh we need to have a weight here right basically i'm going to have a weight or cost yeah let's do a cost yeah instead of waste weight maybe the cost is it's more appropriate for this prop for this problem but you know what actually i'm going to use a weight because weight is a more generic tool for the for all of the graph problems i'm going to use a weight here so at the beginning 0 and right then not zero so it has to be either one or zero right so to for one or zero it depends on the grade of the value itself right depending on the grade value of i and j right basically if this iron if this thing is one then this weight for this direction will be uh in this direction the weight on this address will be uh if the same as this direction then we will be having like a weight equals zero otherwise it's going to be one right so you see we have to leak somehow link this one two three four with all those kind with all these four directions right how we can link them of course we can have like uh if apps right we can have like four if outs here to check if uh if it's one then we know it's a it's zero one right if it's two blah right so for me i um instead of using the this direction here i'm instead of using a list here i'm using a dictionary here to add one more uh one more layer on top of these directions and so the so basically the key of the directions will be this one two three four right and the value will be the this thing will be the offset of the x and y right so for that we have to change this directions from a list to a dictionary right three four right so now you when we uh search when we uh like loop through this direction dictionary here now the d here it becomes to either one i become to one two three and four right and then we can simply use the uh this like this direction to help us uh determine how what's the weight for this add right basically if this derive if this thing is the same as if this uh the key is the same as a current direction here right then we know the cost will be zero right else what right so that's the current weight of the edge and then okay and then we uh and then we are basically we will be creating our graph here right so the key will be the current position right and the value will be the new one right so the new one will be uh actually you know what let's create new i equals i plus uh directions right dot d because we will be we need to get the offset from the dictionary here so the opposite will be the first zero right the new j is to j plus same thing right directions d dot one right and then let's do a simple uh boundary check here right so as usual right and i am and same for the for a new y coordinate right new j uh new j and we only add we don't basically we are we're only adding the valid address right and the value for the edge for each edge will be new i new j and the weight right okay so now once we finish this the first uh nested for loop we'll be having like a graph with weight on each edge right so now okay so build graph with weight on each edge right so now we need to implement the dicrystal algorithm to help us get the minimum weight from the zero to the bottom right corner right so to do that we need to use a priority queue to help us do that i'll explain a little bit later about this how we are using this priority queue to make sure we have we get the correct answer here and the starting point is of course is zero right and then um and then for the die crystal problem you know uh for the uh another things another variables we need for the diagonal is the it's a dictionary for uh for the minimum distance or minimum weight for each of the nodes and so here i'm going to call the uh either distance or cost okay all right and at the beginning uh at each positions the cost from the start to the end will be the maximum right so here you know since we have like how many positions we have uh m times n right so that's why for each of the positions here i and j right and that's the key basically and the value of that will be the uh system maximum right because at the beginning since we will be seeing a lot later on when we uh traverse when we traverse the graph here we'll be updating this uh this cost uh dictionary when we have a smaller value right since we're going to get smaller value of this of each of the position that's why we initialize it to be the biggest number so that we can always like get a smaller one right and for i in range m and sorry for j in range n right so this is just like a shortcut to initialize this like uh cost a dictionary right and one thing we need to notice here is the uh notice that at the last one there's like this example here basically if there's only one element in this 2d grade right what does it mean it means that start and an end point are the same which means we don't need to move at all right so that's why because at this moment at zero is also marked to be maximized right maximum size so that's why for zero right it means that to get from zero to zero we don't need to do anything basically the cost will be zero right and then okay so that's that and cool because the reason we need to use the cost here because we will be using the current cost values to be uh to decide if we want to update uh because we need to use this one to keep it the current uh smallest uh distance or different cost for each of the positions and we'll be using this one to decide if we see a different path to this position shall we consider that's why we need to use this like dictionary to store all those like the state for each of the position right and um uh let me you know for the diagonal problem you know the uh another use of that is the uh not only we need to get the minim the minimum weight or maximum value but sometimes it also asks you not only to find the value but also find the path right so to find the path from start to end even though we're not going to use these things in the in this problem but i'm just listing that code here so that if you are asked to find the path you know how to do it so the way we're doing the find the path is we are going to define a parent right apparent a parent's dictionary for each note all right and we initialize it with zero right so for the zero there's no parent right that's kind of obvious right and okay so since we have everything we need here let's get into the dicastro while loop here basically while this priority queue is not empty right then basically we are we do a current node uh current distance right where the weight where the cost i'm i don't know which uh what i should call this thing cost yeah let's do a cost okay cost i'll call distance here ah no this because on the in terms of a graph it's a something like a distance but in here it's like okay fine i'll cut cost here cost i j uh equals to uh hip q dot heap pop right basically what this one does is every time we're always trying to uh to process the at the node that has the minimum cost at the moment so that we can make sure we'll always be processing the minimum distance first to make sure we always mean approaching to the minimum cost for each node okay and then let's do uh so once we have that right orchestra we also need to maintain like a scene stat right so that to make sure we won't be stuck in the infinite loop here basically every time when we pop these things here right we do a scene dot at inj it means that we already seen this uh this is at this like positions right so that if we in the future if we see this again we don't have to process it again because we know we already seen the minimum value for this position right so that's that and then for neighbor right in graph i and j right um next i sorry okay sorry so for the priority queue the uh not only we need to push the state the position we also need to push the like i said that the cost right and we need to put the cost at the first element because we want to get the minimum cost so if you put this one in the first element that's how this priority queue will be sorted based on the first element the fir based on the first element right so this one will be like the cost i and j all right so but on the graph since we're storing in a different way maybe we should also storing along with the along with this sequence but it doesn't really matter right so this graph it's fine i'll just use the keep it what it is as it is so j and this is going to be the next cost right next cost and then and so we will with this thing we will be having a new cost here right what's the new card the new cost will be the cut the current cost plus the next cost right and so now we need to do two checks here so first is if the new i and new j not in the scene right and new cost is smaller than the uh current than the cost of this new i and new j right so what this thing tells us is the uh okay first uh this is pretty it's obvious uh the this new position must have not been seen before and with this path so the path is from the from this i from this old ij to this new ij and we're getting this new cost right the by following this path to get the new uh the inj if this new path cost is smaller than our current cost for the uh for this new for the new uh i and j then we will be push it into the queue uh if it's an even bigger one then we don't even need to care about that right because we know we need the smaller one right then priority queue uh hip q dot keep push right basically we're going to push the uh rdq uh new cost right new cost a new i and new j right that's the q and we'll be doing two more things here so first since we have a new smaller cost for the current new for the new i and new j we'll be updating our cost array dictionary here right new j is the new lower cost and then this is the we also need to update the parents because since we have a better uh candidates here we also need to update the path for that right basically the parent of inj new i and new j now becomes to the i and j right okay so that's that all right and once this is priority queue is finished right then we can just simply do a return right so now we just need to return what return the last cost because now remember once we have finished processing everything the cost dictionary will be storing the minimum cost for each of the position right and all we need is the last one right from this dictionary which will be m minus one and n minus one right so that should just work let's try to run it okay so this one got accepted let's try to submit it cool so fast all right so and a little bit of explanation about the actual problem you guys can uh maybe you guys can also find some other explanations on the internet but i'll just do a quick uh proof of concept of the extra here let's say there's like here right and then so there's a 80 okay let's see that the weight from a to d is 5 it's 5 and then a to b is 1 right c is 2. also one okay there's some others which we don't care right so e or whatever it is in the somewhere down the road we don't care so now let's take a look at its d here right so there are two ways to get d to d y is from a to d the second one is from a b c and d right and that's how we use this uh die crystal uh sorry the priority queue to make sure we will get the minimum cost to get to d y right let's say uh from a right from a we have a it has two edges one is to the d one the other one is to the b right and we'll be pushing both uh a b uh pushing d and b into the priority queue right and then the next one got popped will be b because one is smaller than five right and then so we have a one and b right and then we have a five and d right here so one of b will be popped from the priority queue and then there are like one another different edges the b will be added to the priority which will be c right so the c then we'll be having like a three to c right because from one to two to get to c the total distance is three now we have three and c and five d since we are using this priority queue to help us always uh keep the smallest distance at the very beginning so the next one got popped will be will also be 3 and c right so 3 and c also got deleted and now we have this uh what we have another d here right which will be a four and d right four and d so in this case you already have like so basically we have duplicated uh positions with different uh length here okay so one more thing is the reason we can add this four and d in into this is priority queue here is because we have this two check here right remember so the first check is if inj has not been seen before that's the first one second one is that if the new cost is smaller than the current cost for the so in this case the new i and j is d right because the first time we see that when we add this the first five into this uh q here is we'll be updating this cost for d to five now we see another way of getting to d is four and it's the new car it's and the cost is smaller than the previous one that's why we can add this four to the priority queue right so now we will we have two elements in the priority queue with the same coordinates but different cost right and then the uh the first one will get popped here right so the fir four and d will get popped and then we'll be using this four and the d to calculate the future right we'll be using the sorry the four and d to calculate the distance for e here right because the four the this one will be or gets popped first right and then we'll be uh we'll be pushing uh the e based on this four right to this part to this priority queue and someone may ask right okay and then what happened since we already have this five and d uh in the uh in this priority queue so the next time maybe five and d will also be part get gets popped right correct that's right so let's assume once this four and d is finished and the next smallest uh let's say we have a like uh eight e here right okay that's going to be a four and four right so from four and four so now we have an eight e here so then this one is gone right so the next time five and d will get popped right from here and so the five and 5d will get popped and we can you know we can add the improvements here by uh even though the scene here is a set right basically we're trying to add this five uh the d into the scene again right which will won't change anything and then it will try to uh it will try to process the these neighbors again in this case it's e here right and it says that okay is the e already has been processed has been already seen before no right then it will okay but then it will try to check if the cost is the same is smaller than the current cost right in from d to e the new cost we're getting is nine right instead of eight because at this moment the cost of e is we already updated from uh max size to eight right and so now the nine is not smaller than the e then eight that's why it won't be pushed here again okay and the what the reason i'm saying that we can do a quick check here is we can save this for loop here and this check here by only by just do a simple check if i and j is in c right we simply continue right i mean even though but uh regardless adding this one or not it won't affect our final result because even though we're pre we are re we are processing the same node same uh node again but since we are we're always processing the first uh the smaller one first and here we are leaving we are adding a constraint by continue only if we have a smaller one that's why even though we're processing the same note again it will not affect our priority queue but by adding this one we can save the trip until to here right for the duplicate notes and uh another thing is that let's say someone may ask right can how can you prove this thing because this is just one example here right since we have five d uh this one how about what if like this is just it's a seven here let's say there's sorry what if this from one we change it to six okay and now this is another example right basically the five here becomes to the shortest path from a to d right and you know what maybe this is not a good example let's change this one from six to four all right so let's say we have this updated graph here now the total path from a to d is five but from this side it's seven right which means we should get five and how can our pro priority queue still uh make sure we're getting the five other the correct answer here right let's go over again so at the beginning we have a and d and we're getting two edges right and uh okay i'm getting two edges here uh okay so the first one is 5d and second one is four b okay and then the four b will be popped right since we are always uh popping the smallest distance right first so the four b is popped and then a c will be added but for c the length will be six right and six is greater than five 5d so when we push this c into the priority queue it'll be pushed it so it will be placed after six after five right so now since we already because so that's how the product you can help us like to make sure we always get the d first right because at this moment right it doesn't really matter how many other nodes here how many paths we can get from this c to d maybe there are ten more ways of from to get from c to d but we don't care right because the cost to get to c is already greater than the then the five in this in skew here right so that we don't care about all those the five these the ten more ways to get from c to d right that's why this priority queue can help us it always get the smart the quickest way to get to five to this target here that's why we're gonna be popping this 5 and d right and now the d has already been seen and the minimum cost for the d becomes 5 right so now uh once we pop the c here right so now the c here we have another d here right the d will be like seven uh so now the six c will be get will get popped right and then from c we'll get like 7 d right so now we have 7 and d and it 7 and d got popped okay and let's uh with this like uh small changes the uh the seven and the will simply got skipped from here okay but assuming we don't have this right if we don't have seven and d it will be uh going through this for loop again basically we'll check the d here the neighbors of d but again things will be uh we're trying to basically add this d to the neighbors of uh from d to the address to e again right but the new cost will be smaller i'm sorry will be greater than the ones we already added to the e because once we pop the d here right we have a we have an x e here right and this x will definitely be smaller than this 7d right and that's why it will be skipped from here basically it will be skipped from here and so basically regardless of adding this like if check here the final result will be guaranteed to be correct uh cool i think that's about everything i can think of uh think about up about this problem okay let's do a real uh recap oh my god this video has made a new record a record for my youtube career here so it had almost like 50 minutes that's the by far the longest video i have ever recorded all right so let's do a real quick recap here first uh first thing first you have to uh first thing first there's you cannot use dp right like i said you it's dp the current state cannot be depending on the future state all right first thing first is no dp in this problem second is second one is that how can we convert this problem into a graph problem right because we're getting the minimum cost that's either a bfs a traditional bfs or the bfx or the bfs with the weight on each edge right and in this case it's the graph with weight and then the second thing we have to figure out is how can we build a graph with weight on each edge right so on this problem is the we have to utilize this the direction of each arrow right so which means following the same direction of the arrows the add the weight on that edge is zero because it means that there's no cost from that one from that state moving to the next position but if the direction is there is different as the arrows then the cost is one right and we have that weighted graph here and then the next one is just a simple diced draw dextroactus algorithm to calculate the shortest path or the in this case is the lowest cost from the beginning to the end and these parents i'm just adding these parents here just to help us to understand how can we in case we you are asked you're asked to find not only the minimum cost but also the path to get to the uh from zero to the to this like final destination right and we can just simply use a for loop right for uh sorry a while loop uh to start from the uh from the last uh element and then traverse back to the zero right and then we just reverse the uh and then in the end we just simply reverse the array that will give us the print as the path right and cool guys i think that's pretty much everything i want to talk about this problem very cool problem so let's combine like two things into its one hard problem thank you so much for watching the videos guys and i hope you guys uh enjoy my videos i'll keep uploading some other videos in the future and stay tuned and see you guys soon bye
Minimum Cost to Make at Least One Valid Path in a Grid
web-crawler-multithreaded
Given an `m x n` grid. Each cell of the grid has a sign pointing to the next cell you should visit if you are currently in this cell. The sign of `grid[i][j]` can be: * `1` which means go to the cell to the right. (i.e go from `grid[i][j]` to `grid[i][j + 1]`) * `2` which means go to the cell to the left. (i.e go from `grid[i][j]` to `grid[i][j - 1]`) * `3` which means go to the lower cell. (i.e go from `grid[i][j]` to `grid[i + 1][j]`) * `4` which means go to the upper cell. (i.e go from `grid[i][j]` to `grid[i - 1][j]`) Notice that there could be some signs on the cells of the grid that point outside the grid. You will initially start at the upper left cell `(0, 0)`. A valid path in the grid is a path that starts from the upper left cell `(0, 0)` and ends at the bottom-right cell `(m - 1, n - 1)` following the signs on the grid. The valid path does not have to be the shortest. You can modify the sign on a cell with `cost = 1`. You can modify the sign on a cell **one time only**. Return _the minimum cost to make the grid have at least one valid path_. **Example 1:** **Input:** grid = \[\[1,1,1,1\],\[2,2,2,2\],\[1,1,1,1\],\[2,2,2,2\]\] **Output:** 3 **Explanation:** You will start at point (0, 0). The path to (3, 3) is as follows. (0, 0) --> (0, 1) --> (0, 2) --> (0, 3) change the arrow to down with cost = 1 --> (1, 3) --> (1, 2) --> (1, 1) --> (1, 0) change the arrow to down with cost = 1 --> (2, 0) --> (2, 1) --> (2, 2) --> (2, 3) change the arrow to down with cost = 1 --> (3, 3) The total cost = 3. **Example 2:** **Input:** grid = \[\[1,1,3\],\[3,2,2\],\[1,1,4\]\] **Output:** 0 **Explanation:** You can follow the path from (0, 0) to (2, 2). **Example 3:** **Input:** grid = \[\[1,2\],\[4,3\]\] **Output:** 1 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `1 <= grid[i][j] <= 4`
null
Depth-First Search,Breadth-First Search,Concurrency
Medium
1271
999
yeah okay cool 999 available captures for work on an 8 by a chess board there is one white work yeah there also may be empty squares like bishops and black points these are given as counters or B and P respectively uppercase characters represent my pieces and lowercase characters represent black pieces ok the work move as in the rule rows of chairs it chooses one two four directions and then move until it stops which is the edge of the board or capture an opposite colored point also works cannot move to the same squares out of any bishops we turn the number of points of work can capture in one move okay so this seems pretty straightforward there is a little weird that I guess these are all colored so you only need to worry about black points there no white pawns okay I mean it seems pretty straight for you just kind of almost like a ray casting and just shoot away from the work - and just shoot away from the work - and just shoot away from the work - laughs up down and right and then just seem good capture and you could capture at most four point I think I mean obviously in real chess and just four points but okay so yeah only up to four pounds let's try that out and call it up so these are the four directions to find the work some keys a little sticky okay now we just go in each other for direction I guess descriptive switched statement actually so that's weapons for this a pawn if it's a bishop you just I should quick early everything else you which is like it's just a dot yep that's roughly right to win a quick test whoo save I mean eeeek should not sure why this is crashing back and that's why this is always eight but uh I guess this could be undefined if we don't find to all that right why am I getting a sheep buffer overflow and put those away okay so I guess it is something I did Oh probably something out of bounds but it's well that's kind of odd though when there's just some input thing like why would this point gosh oh no oh why okay I mean it's time to exceed it for a different reason buddies that's why cuz the Perry this is an int pointer and that it's an in the way another whatever a little bit oh okay so that makes C is C exceeded it means PI this doesn't terminate should I guess right now that's right so that's I guess I have time to exceed it again before printing out a bunch of stuff okay oh yeah because prick works out to switch look but not the world okay well there's annoying to miss it go through but okay won't live i got'em package okay that looks okay we try another case I guess the case to someone to make it do multiple inputs but I could never get it to work I'm just give it a quick shot oh so I guess you can't do more inputs that would save me so much time in the past yeah okay just okay cool ten minutes okay yeah so for I wouldn't say an easy problem well it's an easy problem and that's why it's a little bit easy yeah I think I went into a couple of silly hours with internment this array size which I guess I'm most languages you just started to add cow and I actually would have been very simple and also being familiar languages I changed it to you switch instead of if statement and then this very kind of we have to code a little bit around it well boy a straightforward problem whether you know chess or not because so I guess we know chess or I'm familiar with chess it saves like a couple of minutes of doing it but in general we just kind of look up but I guess you can't see my mouse but you look up with the work you look down left right and then just see if you could just hit upon or not free straight for long I mean I would say probably there's enough coding for on this problem for it to be used on a phone screen I imagine it if you're doing like in-depth phone it if you're doing like in-depth phone it if you're doing like in-depth phone screen or politics like an average person or an average okay good to could can apply like 2025 minutes just to set up and work on this problem so then you could throw the rest of that time we've kind of like backward background architecture or just like where first stuff so I think this time it's a little bit knowing enough data I could see myself doing it as a phone screen but it's still a little bit on the easy side there's no movement complexity there it's just what getting to call queenly and watching out for maybe some edge cases and yeah I think that mostly roughly worry about this
Available Captures for Rook
regions-cut-by-slashes
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**. Return _the **number of available captures** for the white rook_. **Example 1:** **Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\] **Output:** 3 **Explanation:** In this example, the rook is attacking all the pawns. **Example 2:** **Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\] **Output:** 0 **Explanation:** The bishops are blocking the rook from attacking any of the pawns. **Example 3:** **Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\] **Output:** 3 **Explanation:** The rook is attacking the pawns at positions b5, d6, and f5. **Constraints:** * `board.length == 8` * `board[i].length == 8` * `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'` * There is exactly one cell with `board[i][j] == 'R'`
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
422
hello everyone let's look at lead code question 422 valid word square at the time of recording this uh question has 407 up votes and 264 down votes and it asks given an array of strings words return true if it forms a valid word square a sequence of strings forms a valid word square if the rows and columns read the same string so in this first example we have the first row and it is a b c d and the column is also a b c d the next row is B nrt and the next column is also BN RT and so on before going into depth to these examples let's look at the constraints are that the words do length or the row length will be between 1 and 500 units and the columns will be also one and 500 letters long words I consists of only lowercase English letters okay so let's understand the examples okay running through the code really quick we see two for Loops the first for Loop defines the iteration of the rows and the second one of the columns so here we have for I in range zero to length words the length of words is four here and the columns is zero to length words of i words of I is simply the index of the current row so if it's row zero it'll be four therefore the column should be 0 to 4 also next we have this if conditional which checks that the length of words is equal to or less than J which would be the length of columns this just checks to make sure that the length of the rows and columns is the same and it also then checks that the letters at the specified cells of each row and column are also the same and if they're not we simply return uh false and then if we Loop through every single cell in this uh word square and we see that false is never returned we return true so let's run through this example so in this first example we iterate through the first row and the First Column and we see that the range is between zero to length words and zero length words at I is zero here at the start so we see that the length of words for the row is a b c d that's four and the length of the columns is for also for the first column A B C D next we can check if these letters are the same for the values of the rows and the columns so is a the same as a since this is both uh column and row value that's true is B the same as B yes c d okay so far everything's been true uh the valid word square is true so far next uh iteration so then we Loop then to the next row that's row index one and that's bnrt and then the same applies for the column that's bnrt for the second column as well and you can see that four characters on the column and four characters on the row show that the lengths are the same there's no greater than J values for the length words and the values are the same bnrt next same thing but the next row we iterate then this I to two and it's CRM Y and then we Loop through the column zero to length wordss at I so that would be CR RM Y and we check so these are also four characters of length for both uh column and row and they have the same values starting with uh the column here we see that c r m y so that's true so far so we go to the last iteration and we see then that the uh length of columns and the length of rows is the same and the letters are also the same d TT y e so in this example we return true all right let's check the solution and it works very nice so what is the time complexity of this solution the time complexity of this code is O of n^2 where n is the length of the longest n^2 where n is the length of the longest n^2 where n is the length of the longest word in the input list this is because there are two nested loops and each iterates up to the length of the longest word the space complexity is o one we use the code uh with constant amount of space to store the loop variables and the input list that's it for this question thank you for watching
Valid Word Square
valid-word-square
Given an array of strings `words`, return `true` _if it forms a valid **word square**_. A sequence of strings forms a valid **word square** if the `kth` row and column read the same string, where `0 <= k < max(numRows, numColumns)`. **Example 1:** **Input:** words = \[ "abcd ", "bnrt ", "crmy ", "dtye "\] **Output:** true **Explanation:** The 1st row and 1st column both read "abcd ". The 2nd row and 2nd column both read "bnrt ". The 3rd row and 3rd column both read "crmy ". The 4th row and 4th column both read "dtye ". Therefore, it is a valid word square. **Example 2:** **Input:** words = \[ "abcd ", "bnrt ", "crm ", "dt "\] **Output:** true **Explanation:** The 1st row and 1st column both read "abcd ". The 2nd row and 2nd column both read "bnrt ". The 3rd row and 3rd column both read "crm ". The 4th row and 4th column both read "dt ". Therefore, it is a valid word square. **Example 3:** **Input:** words = \[ "ball ", "area ", "read ", "lady "\] **Output:** false **Explanation:** The 3rd row reads "read " while the 3rd column reads "lead ". Therefore, it is NOT a valid word square. **Constraints:** * `1 <= words.length <= 500` * `1 <= words[i].length <= 500` * `words[i]` consists of only lowercase English letters.
null
Array,Matrix
Easy
425,777
3
and welcome back to the cracking paying YouTube channel today we're going to be sewing lead code problem number three longest substring without repeating characters before we get into the video If you guys enjoy this kind of content please like and leave a comment on the video it helps me out a lot with the YouTube algorithm all right given a string s find the length of the longest substring without repeating characters that was simple alright let's look at some examples so let me just pull my pen up here and okay so we have this string ABC BB right so we want to find the longest substring without repeating characters and it's um worth noting that the substring actually has to be continuous we can't just pick and choose characters as we please so it has to be continuous so let's just start from the beginning and see how far we can go so we'll take this a and then we can take the B because it's Unique we can take the C and then we get to this a which means that now this substring would actually have two a's so we can't have that so we can only go up to this C here so that would be length three right or alternatively we could go BCA but unfortunately we hit a b here so again that's length three we could go c a b and then we unfortunately get to a c so we can't really go anymore we could take this a b c um we can't really do much after that because of the double B's so we actually end up seeing that the best answer here is going to be three here in this one similar thing we would start you know okay let's try to do PW all right that's fine and then we encounter another W so that's only length two and then we could try ww no that doesn't work uh what about WK that's fine e that's fine and then we get to the W which obviously breaks it so we can only do wke which is actually our solution here and it's uh three as well so to solve this question you could do one of two things one could be to literally calculate every single possible substring and then take the lengths that would work you wouldn't pass the interview if you did that just saying that would be a very expensive solution because you're literally defining every single one what we want to do is we actually want to solve this in one pass through the string so that way we can get a big O of n runtime complexity and the way that we're going to do this is uh similar to how we actually did it with our example where we were taking one character at a time and trying to add more as we go so essentially we were using a sliding window approach so what we're going to do is you know we need to know what characters are actually in our um you know our sliding window and the way that we're going to do this is if our sliding window has characters in it we're just going to assume that they're unique and whenever we reach a new character we're gonna check whether or not we've actually seen that character before so what we're going to do is we're actually going to keep a dictionary which is going to map um a letter to the last time we saw it so we're going to say letter uh and this is going to map to an index where we last saw that character so that means that um you know we can basically calculate our length right so if we are having our substring here and we're building it with the sliding window as soon as we hit a character um that's already in this kind of uh dictionary here then we can basically just um you know take the difference between where we are and um you know where we started so we want to keep track of like our left and our right and we'll kind of use those to calculate the distance aka the length of our substring so let's see how this might work in case it's not clear so we'll have this dictionary and I'll just whoops uh let me put it over here to give us some more space so what we're going to do is we're gonna go um character by character so we're gonna have a left pointer which is orig gonna start at zero and what we're gonna do is we're going to start a right pointer and it's also going to be moving from left to right over the array but it's going to start at zero as well right so this is the zeroth index this is where we start our pointers what we're going to do is we're going to get each character as we go along so the first character would be a right so what we're going to do now is we're going to check is this character have we seen it before uh and obviously we haven't because we just started so we would put into our dictionary a that we lost saw it at zero right so now what we're going to do is we are basically um going to go forward right because this is a valid substring we haven't actually encountered any characters here so uh what we're going to do now is just move our right forward so now the right would move to the B so B we haven't seen before either so we can put B into our uh dictionary here and we would continue so now right would move forward to the C and now we've uh CC for the first time so C would get added to our dictionary and that's at uh index two so now our right will move up and unfortunately we hit a again right so this is a problem because obviously in our substring we already have an A so we can't take this new a so now what we need to do is okay we're going to check is this character in our uh dictionary here which it is right so what this means is that we need to double check uh whether or not it's actually within our substring and the way that we're going to check uh if it's in our substring is we're going to check okay is the index that we last saw it so is zero greater than or equal to left and left is going to represent basically the start of our substring here so since 0 is obviously equal to zero that means that we can't take this a because it would be part of our substring so what we need to do is we need to update our left uh to basically move one character up because now we can't take that last character we have to remove it uh given that we're now going to be taking it with the current character we're at so in this case when the character is in our dictionary here and we make the check is the character is index is it greater than or equal to left if it is then what we want to do is we want to move the left equal to whatever that index was so we're going to say the position dictionary of our current character which is a right we're going to take the position that we had before and we're going to add one to it because that's the new Left position right so zero plus one equals one so now left equals one and right is going to be so this is 0 1 2 3 right so right is going to be at index three now um we can basically just uh you know update our maximum so we can take the difference between the right and the left so 3 minus 1 is obviously two and then we do a plus one because we want to have uh inclusive here so we would simply say uh that this is three right so this would be you know our temporary solution and we would see if we can find anything better and now what we want to do is obviously we've seen another a so we need to update the dictionary here so instead of being one we've now seen it at position three so let me actually clean some of this up here and actually we'll keep our dictionary and maybe we can clean a little bit of this up here just to make it clearer for you guys okay um all right that's probably fine so we know that left uh we moved left to equal one right equals three and we just finished processing so that means that right is now going to move to the B and remember that um we already have seen a b so we're going to do the same thing we're going to check okay where did we last see the B we saw it at one is this greater than or equal to where our left pointer is which it is right because left pointer is currently one so that means that we can't take this B because we would have a duplicate right so this represents where our um uh substring starts so now we need to update our left so we now need to move it one character up so where was the last time we saw the B we saw a b at one so we would just move it one plus one right we're gonna move it one to the right so now the left pointer is two so the left corner becomes two and obviously the right pointer now is four and then once we finish this it's going to be five so we would essentially do that for the rest of the string and obviously we have an answer which keeps track of the biggest uh difference that we found so far and remember we calculate it as right minus left plus one oops that's kind of messy uh right minus left plus one and at every iteration we want to take the maximum of this value and whatever the pre previous Max was right and then at the end we'll actually have our final solution uh and that will be stored in whatever variable we choose to call it but we can just call it previous maximum so that's how we're going to do it basically leveraging this dictionary to tell us uh where that left pointer should be and whether or not we've actually violated the bounds um that way we can actually do it in you know one pass through we only have to process all the characters once and we don't have to you know generate all the possible combinations so hopefully that makes sense on an intuition level um now what I want to do is actually go into the code editor and type this up the code is super simple I think it's really clear if you're still a little bit confused don't worry we're going to go into the code editor and I'll walk you through it line by line and hopefully that should clear up any sort of confusion all right let's now go there and code this up we're back in the code editor let's type this up so the first thing that we want to check is actually if our string is of length one or less than one obviously then we just return the length because there's nothing for us to do right there's never going to be duplicates when there's only one character or no characters so we can say if the length of s is actually less than or equal to one then we can just return the length of s so pretty simple there just a nice little Edge case we can catch uh otherwise let's define our dictionary which is going to store uh remember a mapping from character to the index that we last saw it at so we're going to say position dictionary is going to be an empty dictionary and then we want to initialize some variables so our left pointer and we also want to initialize basically our result here right so we're going to say res and these are both going to be zero because we haven't processed anything and obviously the left pointer starts at the beginning of the array so what we want to do now is we're going to say four right Char in enumerate uh s this is just some syntactic sugar in Python to basically give us the index and the correct character at that index which saves us from just uh subscripting it so um yeah so now what we're going to do is remember we need to check whether or not we've actually seen um this character before and if we have seen it uh we want to make sure that it's actually not in our current substring which uh remember left denotes the star of our substring so let's do some checks so we're going to say if Char in position dict so if it's in the position dict and if the uh position dict for that character is actually greater than or equal to left then what we want to do is um that means that our string already contains the character so that means that we need to actually move our left up to this new uh character so we're going to say the left pointer is now going to be wherever we saw that character before plus one right so to the right of it we're going to move our window and kind of reduce it a bit so once that's done uh now what we can do is we can actually update our answer here at every iteration so our answer is going to be the maximum of whatever the current answer is and the difference between remember right minus left plus one and that will give us the length of the current uh window here so the last thing that we need to do is actually just update um the position dict for our character because we basically have now seen it at whatever index R is so we need to actually reflect that in the position dictionary so we're going to say position dict of R oh sorry of character is going to equal R so all we need to do now is once this for Loop ends we'll have processed the entire string and we can simply return uh our result here so where is my uh submit button I okay I seem to have lost it uh there we go let's just run this make sure we didn't make any syntax mistakes and we look good and submit it and cool it was accepted all right okay satisfied go away um let's see so let's talk about the time and space complexity now so time complexity wise as you can see all we do is we iterate through the string one time right so we go from right to left and we process basically every single character so because we're doing that it's obviously going to be Big O of n um I guess where n is the length of the string right simple enough uh space complexity wise what we want to do here is obviously we have this extra data structure for um our position dict so obviously this is going to be storing characters and the amount of characters we store um depends on how large uh s is so this one actually technically the maximum amount of characters I believe um let's see so English characters digits symbols and spaces so technically this is Big O of one because you know how many letters digits symbols and spaces there could possibly be that is like a predetermined number and since it's not um you know based on the actual string itself it's technically Big O of one though you might have to say that it's Big O of n because it depends on how long this is there won't be any overrides let's actually just check the official solution here uh why not so let's see sliding window um Min m and n up sliding window optimized okay yeah so it is gonna be um big of um okay so yeah it depends on how many characters there are um although okay if it was just English characters because the maximum you could store is 26 characters then it would be big of one but I guess there's we don't know what's going to be given to us so we'll just call it Big of and uh just to be safe so there you go that is your um you know runtime complexity and space complexity here that is how you solve longest substring without repeating characters like I said relatively simple one we're using a greedy approach only iterating over the array once and uh we're good to go so that is how you solve the question if you enjoyed the video please consider leaving it a like and any random comment really it helps me out a ton with the YouTube algorithm subscription to the channel really helps this channel grow and uh if you want to join a Discord Community where we talk about all things Fang interviewing systems design uh you can have your resume reviewed by me and other peers uh you can ask for referrals and all of that if that sounds interesting to you then please join the Discord Channel I'll leave a link in the description below otherwise thank you so much for watching to the end and have a great rest of your day bye
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
347
Hello Guys Welcome To Gautam Samay Disney Today I Will Go Through The Death Sentence For July Recording Is On Top K Frequent Elements Please Like This Video And Don't Forget To Subscribe To My Channel Subha Never Miss Any Update That Given In The Refrigerator Most Frequent Elements And Give One Example 1212 Most Frequent Element Superintendent In The Giver Notes Give And Take As Always Wished To Come Up With Solution The Complexity Better Than Life In Log In It's Also Greeted And Service Union Week And Western Dance In This Edifice Dynasty Now Problem Or Job Basic Steps Latest 2017 A Husband Returned Ke Fattening Buffalo Starring The Number Of Account Below Comment Dance Step One Who Did All The Important Encounter 840 Maintain Story At Its Best With Example A Apne Pati Ban Input Vishudh Chakra N Sinha The Ki Suvidha Element And Value Will Be The Number Of Tiger Element Hai Dhaakad Hai Mein Nau Devi Sharda Current Map With Me To Short To Observe Akram Pure PK Is Written Rakhi Most Frequent Elements Which Can Directly To Amazon Value Treatment For Kidneys Birthday Wish No Data Structure In Which Will give this functionality to win yet another data success Will give priority Q you can use any data structures and you feel comfortable with the volume set the priority Q diversity element has been increasing Another explains his views as a custom computer in Java to complex at Will tree to roam the map and insult key interactive now Point mintu return the last k elements 3D cube notification note index 20 minutes to remove all the elements for the last k elements subah continue to remove the elements objective test size great think and new delhi iss bhi taklah k most frequent elements no departure values into a Burden and Welcomes Reminder Step Video Villain Smile Concluding to the Elements Clearances Value Nominees Compound War Custom Compare To Pure Person Unemployed Increasing Order Against They Remove Element from Acute and Excited When's Editor and With Elephant in Winter and Vitamin E in Vitamin Complexities of Law That Bigg Boss Vikram Optimizations Tattoo Entry And Will Take Some Time And Space Complexity Will Also Improve To Of Any Place In An Exact Same Pattern Tomato And Check Watering Pooja And Dinner Description Clock Off Thanks For Watching The Video Effect Video Please Like Share And Subscribe Like Our Channel Comment Section What You Think About The Video
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
216
Hello ji welcome to week four, it is going very well man, you have come to the second last week, you guys have covered a lot of things so far, only a few things are left, will wrap up quickly, fifth week will end soon. We will do this and you will get very good preparation for DSC. Let's move towards the solution. Yes, let's start with question number 58. What is question number 58? Let's see the combination sum three. What is the question saying? The question is saying, Find all valid combinations of K numbers. You have to find such valid combinations in which the number of numbers is the K number of numbers, meaning how many numbers are present in it, then the K numbers are present in the combination of K numbers. Sum up to n means I choose k integers. Meaning, if the value of k is th then I choose three integers, their sum should be n. If the value of k is four, then the sum of four integers should be n. True, the following conditions are true. What is the condition Only One Only Numbers One through Nine are used Only numbers from one to nine will be used Apart from that no one else will be used Numbers from one to nine are used Ok i.e. to nine are used Ok i.e. to nine are used Ok i.e. only single digit numbers will be used Each number is Used at Most Once Each number must be used only once Not used more than once Each number must be used once i.e. duplicates are not possible Return i.e. duplicates are not possible Return i.e. duplicates are not possible Return a list of all possible valid combinations List of which valid combinations to return The list must not contain the same combination. This same combination means the same set of numbers should not occur repeatedly and the combination may be returned in any order. Return in any order from top to bottom. No problem. Ok, see. What will we do in the code? First of all, what do we have to return vector of vector int, we will not face any problem, we do one thing, we create a vector of vector int outside, vector of. Int and name it, the answer is ok, it will return this answer to us, now let's see, will it work in a different function, if we create a recursive function, then there will be no problem, now see if the vector of vectors is the answer, then what do I have to do every time? Make it into a vector first and then push that vector into the answer. Make a complete combination into a vector. First and then push that vector into the answer. Then make a vector of ant x. Name it anything. Here, I have kept Firstly, how many numbers have to be chosen, secondly, how even should it be, thirdly, the Choose from the digit. You understand that if you start choosing from this number then the sum of zero does not count anywhere. So we said that we have fooled our function that we had chosen zero, you choose from one, okay. We have given the starting point. Okay, now let's write the function. We are not expecting anything in return, so we named it Void Solve. After this, we have received it as int. Second, we have received it as int n or target. Let's name it that it has to be achieved. Second vector of int. In this I have received a pert I want to say that because we said no, so as not to repeat, I want to say that after counting all the previous ones, count the remaining two and add the remaining ones and see whether the work is being done or not. Now here in this case. When to go back first or when will the part of my answer become the first one when my k will also be zero What does it mean to be k0 that my number of elements which I can count in my combination is also completed and my target is also It will be zero i.e. my target is also It will be zero i.e. my target is also It will be zero i.e. after completing them my sum is exactly zero meaning my target is over or the entire target has been used, so I said if k equals to 0 and target equal to 0 and what have I written? Yes answer dot push back, what push should be After subtracting from the target, I will send the remaining target further, I have counted it, now you see the remaining target, how much is left, work according to the remaining target, okay, this much is understood, let's say that among these two, one person is If one person becomes zero or both, it means either my numbers are over and the target is left or my target is over but the numbers are left to count. In both the cases, I do not have to count my solution because that is my solution. No, I have to give exactly the elements, so if's equal to 0 and target equal to 0, then I simply return from here, I do n't want to count it, I would say find another combination, don't count it, okay that's it. We understood the thing, now from here we start our recursive work. I said for int i equal to start, why we have to start from start because all the numbers after it have been counted i &lt; = 9 because it is said. numbers after it have been counted i &lt; = 9 because it is said. numbers after it have been counted i &lt; = 9 because it is said. That can be counted only from 1 to 1, cannot be counted more than that, so suppose I had sent 'F' in the beginning, then I would have counted I had sent 'F' in the beginning, then I would have counted I had sent 'F' in the beginning, then I would have counted 4 teeth. Let's go from 'F' to 9, 4 teeth. Let's go from 'F' to 9, 4 teeth. Let's go from 'F' to 9, leave the one before that is already calculated. Before that Leave it, if and I plus, now there is a scenario in this, if my I becomes bigger than my target, then all the spoils are wasted, I become bigger than my target. So nothing should be done, let's say the target is what is left with us, minus hoha, what is left, let's say two is left and my ' say two is left and my ' say two is left and my ' f' has been given, so can I add five, if I ca f' has been given, so can I add five, if I ca f' has been given, so can I add five, if I ca n't add then go back from here. Okay, so in which case, if a is less than or equal to the target, in this case, either it is equal to the target, then one iteration, if it is not equal to the target, then it is less, then there is no problem. Because you will add further and see, there is no problem, everything is going well, okay, I said, my After that go call Solve again and tell him that he has been counted, this person has been counted, you count the others and show them, then I said ok brother, so what have I done, reduce one person from k. Given that I have taken one person's organ from my brother and I have minus the target, that is his value, then the target that is left is being given to you to fulfill and let it go as x is. And from here it goes 'i pv' And from here it goes 'i pv' And from here it goes 'i pv' why 'pv' because if you have counted this index i.e. if you have why 'pv' because if you have counted this index i.e. if you have why 'pv' because if you have counted this index i.e. if you have counted this number then you start counting from a number bigger than this. The second scenario is that I accepted that I counted mine first. Now I came back and said two. Whatever the scenario is, if it is not made from two or if it is made then in any case you have to come back. He came back and said that at least try from three, then to try from three. I have to first remove two from there and then try with three so what will I do If there is no target left then three, then if there is no target left, then nothing can happen, then check in the next iteration, if it happens, then add three, then try using three, then try again three. Take it out brother, we will check again in the next iteration, okay, so the work will continue in this manner, after that what will we do finally, our answer key will be updated here, where at this place, what will we do finally, if we return the answer. Return Answer: The return the answer. Return Answer: The return the answer. Return Answer: The matter is over, let's just run it and see once it is accepted. Let's submit and see that the submission is also very good. Yes, I hope you all have understood the solution. If you have not understood the solution, then one more time. Go to the website and see the editorial. Even if you don't understand, watch the video again. Ask doubts on Telegram channel. And if it is solved well, then definitely post the link. Thank you very much by all. Best
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
508
hello everyone today we are gonna solve most frequent substrate sum problem so in this problem we have a binary tree let's say our binary tree is something like s2 and what we have to do we have to find the most frequent substitution so first of all what is substitution so here you can see that this is my substrate this single node is my substrate so its sum is 2 this minus 5 this single node is also substrate so its sum is minus 5 this is a tree so what is sum of its so 2 plus 5 plus minus 5 so it will becomes 2 so i can see this 2 is the most frequent sum how many substitute we have which have sums to it is 2 how many substitute we have which has some minus 5 so it is 1 so here we can say that 2 is most frequent substitution so we will return 2 here now let's say another example if i have 2 and this in this case what will be my most frequent sum so you can see these two i have these two one time so some of this substrate will be two some of this substrate will be one so one is also occurred one string and this five and the sum of these wholes of three will be five plus two seven plus eight that is one time so in this case if all of them if or not all of them if my most frequent is one here most frequent is one so if i have many substitutions which have the same frequency in that case i will return whole every sum every number so in this case i will return 2 1 8. so now how do we solve that let's understand the intuition first so what we will do before finding the most frequent element i should know how to find the substitute so how i will find so if i have this tree so how do i find the first three sum so first of all um there are two approaches to solve our the trees problem by d trace problem so begin to top down on bottom up in recursion so here what should i do if i am here so how can i find what will the substitution what will be its tree sum so i can say i can simply say um whatever is returning from here let's say from here i get my left sum and from here i will get my right sum so whatever comes from here and here i will add my root value into it so i will have my left thumb i will have my right sum and i will have my root value and this will make my current substrate this substrate from this substrate so this is how i will find the substrate sum of my tree so for every node let's see if i have a single node so this null will return 0 so its sum will be 0 plus root value 2 so if i have a tree something like forms 2 and this is 1 so what will be its sum will be substitution so first of all it will be zero so this is one it subs this substrate sum is one and now from here it will get zero from here it is getting one so its sum will be 0 plus 1 plus 2 that is 3 so now i got this 3 as my final substitution so now let's understand this now what i will do i have to find the frequency so for frequency what we do generally when we need c frequency quotient we use map where we store the county frequency so what we will do when the sum is written when we find the sum before returning from here i am returning this one before returning this one what i will do i will add this sum into my map so now i will add this one and make that it is occur one time i will make this three and make it like it occur one time okay so now after doing this once my bfs dfs any approach i can use once my dfs is done then what i will do i will i trade through this should i trade through this no what i have to do this unorder map have this in random order first of all for finding the most frequent i will sort this so if i write down my steps so it would be look like so the first thing we have to do is we count the substitution and have to store that term in map and store it in map we will have another map okay then what we have to do we have to this sort this now sort the substitution according to the frequency according to frequency so once we done do this once we done these two steps in the last step will be the last step it will be if let's say our most frequent the most frequency substitution is k time our most frequent is k time so all the substitution which have the frequency k we will add that all that frequency or substitution into our vector and then finally return this vector so this is simple three step procedure so now let's check out the code and analyze the time and space complexity so first of all what we are doing is first of all we are using this anoder map for count the substrate sum and store it into our map so how do i doing this so using this wall function this whole function do a dfs this is a simple dfs where first of all it find its left sum and then we find it right sum once it find this left and right sum then it will find its current root sum and once it find that root sum it will store it into our map so if i do a dryer and so you can see here so first of all i am sending this pipe this five to this whole function so this five is gone and this five will call it left so it will be on this two and this will call we'll call it root left then this will return zero and its right will also return zero so its left and right is returning zero so what i will do okay so left and right is returning 0 what will be the root value current root value is 2 so i will return from here i will return 2 before returning 2 i am marking this 2 with 1 its frequency is 1 right now this 2 is done now is 2 is done once 2 is done it will call my right this is 1 and it will also get 0 from left and 0 close right and its current value is 1 so it will make my one sum as month and it will return one here so from left it will getting two from right it will getting one so its sum will become two plus one plus five that is eight and eight is one so now in this case uh right now where i am at this step now what will happen after that i will use i can use either thing i can use a vector and put my map values into the vector and then sort them or i can use simple priority queue so what does this priority will do this priority queue will count this and now what i will have this in i will count this frequency because i have to sort it frequency by so i have sorted this so i will have here something like this 1 comma 2 1 comma 1 and 1 comma 8. so after this will be in my priority queue so after that what i will do i will see that i have my vector answer and i will see what is my top frequency its frequency is 1 so if its frequency is one then i will pop all the element whose frequency is one i will pop all the element and store it into this so its frequency is one i will add two into my answer one also to my answer and eight ohms so in my answer once i have done this and now let's see if there are many more um right now it is empty if it is empty or if you can see is less than my current frequency in that case i will not work on the elements so once this condition falls i will return my answer so now let's understand what will the time and space complexity so for using this our time complexity will be off and for priority queue take logan for post and pop operation so here in max what we can do there can be and items so it can be hand and low and for popping also it can be and logan so overall time complexity will be and logan and the overall space complexity for this unordered map and this priority queue will be off and so this is the time and space complexity i hope you understand the intuition and the source code if it helps you do not forget to hit the like and subscribe button thanks for watching
Most Frequent Subtree Sum
most-frequent-subtree-sum
Given the `root` of a binary tree, return the most frequent **subtree sum**. If there is a tie, return all the values with the highest frequency in any order. The **subtree sum** of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). **Example 1:** **Input:** root = \[5,2,-3\] **Output:** \[2,-3,4\] **Example 2:** **Input:** root = \[5,2,-5\] **Output:** \[2\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105`
null
Hash Table,Tree,Depth-First Search,Binary Tree
Medium
572,2126
554
hey everyone welcome back and let's write some more neat code today so today let's look at a pretty interesting problem brick wall so the premise of the problem is that we're given a two-dimensional is that we're given a two-dimensional is that we're given a two-dimensional array that is supposed to be a brick wall every value in this two-dimensional every value in this two-dimensional every value in this two-dimensional array is an integer every integer corresponds to a single brick the value of that integer for example one in this case tells us the width of that brick right so this is a brick of width one now you can see that there's a brick of value two therefore the width of that brick is also going to be two and our goal is to take a line from the top of the brick wall right over here and then go all the way through the brick wall to the bottom of the brick wall and our goal with this line that we're doing is to minimize the number of bricks that we're cutting like take a look over here if we go through this way right we're cutting through all six layers of bricks right we can see the height of this brick wall is six layers right and you can see that every single one is being cut right we're cutting this one cutting this so that's bad right we're cutting six bricks but we want the minimum number of bricks that we have that we can cut right take a look at this red line that they drew for us over here now we're cutting one brick right this two but okay take a look there's a gap over here between these two bricks so we're not actually cutting these and again there's a gap over here so we're not having to cut through a brick okay but there is a brick here it's four we do have to cut through that right and then the last two there's a gap so we do not have to cut any bricks so in total when you look at it we cut this brick and we cut this brick so we ended up cutting in total two bricks and one last point that they mentioned for us is we cannot draw the line on the left and right side right basically over here right clearly we over here we wouldn't cut any bricks right that would be zero cuts but we can't do that and we also can't go over here right so that's pretty obvious i think but other than that's just our goal right we can cut anywhere we'd like but our goal is to minimize the number of bricks that we have to cut through so the good thing for us is we don't even have to draw a picture because they did give us this example brick wall so that's what i'm going to use and let's take a look at the brute force solution what that would possibly end up being notice how every one of these rows has the exact same width right that's always going to be guaranteed so we can see that this row the first row has a width of 1 plus 2 plus two plus one so that's in total six right and every uh corresponding row is going to have that exact same width so one thing we could try is for every position so at position one over here at position two over here at position three position four and position five right we can't cut over here and we can't cut over here but the other positions we can try to cut through right we can brute force it let's go through this see how many cuts we have to go through okay there's one cut two cuts three cuts so that took three cuts right what about this position how many bricks do you have to cut one two three darm to cut this four five so that's five that's definitely not the minimum and let's take a look at this one now we don't have to cut these two we have to get two over here and then cut one more down there so that's also three cuts let's take a look at this one we know that this is our solution we're cutting one brick and cutting one more and that's it so that's two bricks that we ended up cutting this last position we're gonna end up cutting one two three four bricks so from taking all these values right we just brute forced it pretty much and we're going to take the minimum it's 2 and that's going to be our output just like they tell us but notice how we're kind of doing a little bit more work than we even need to now imagine if instead we had a brick wall like this right let's say this was uh maybe a hundred right and maybe uh another hundred over here right we would end up if we did this brute force algorithm that we did we'd end up with like a hundred uh values over here right and then we'd have to go through the entire you know cut every single time and then do the same thing with over here right but how about we skip that how about instead of going through every single position in our brick wall we instead only identify the gaps in every single row that's available and we just count for every single row so we count the gaps we're going to use a data structure to count the gaps of every single row in total right so we see that there's a gap for example in position 1 over here right there's another gap over here in position three the reason i say this is position three is because we take one plus two add them together that leaves us with position three over here right and then add two again to that we see one last gap right over here right at position five so in our count gap data structure and by the way this is going to be a hash map because that's going to lead us to the most efficient the key of our hash map is going to be the position right the x position right so 1 3 5 in this case right and the value in our hash map is going to be the count of gaps right the count of gaps what do i mean by that let's just initialize our count gap so far so sorry about this being a little messy but remember so our account gap is going to be a hash map right so at position one which is our key right at position one over here what we're gonna do for the value is c is say that we found one gap so far in this position right and also for three we found one gap in that position right same thing with five we found a single gap so far so right now what all we did was go through the first row so we're done with the first row all we're gonna do now is go through every single row continue to update this count gap hash map and then finally at the end what we're gonna do is find the minimum value of it and that's going to be the number of the minimum number of cuts that we have to do and at the end we're going to go through our hashmap look at every single value and we're not going to look for the minimum value we're going to look for the max value in our hash map and the reason why we're looking for the max is because remember we want to minimize the number of bricks that we have to cut right so we don't want to cut bricks so in other words since we want to minimize the number of bricks we cut we want to maximize the number of gaps that we go through so when we can maximize the number of gaps right we find the max the position such that the number of gaps that we have to do is maximal then what we can do is take the total number of rows right the total number of rows and then subtract the number of gaps from that and then that's going to lead us with the total of the number of bricks that we have to cut right so that's going to be our result and let me just show you one last and so let's just take a look for this example we have six rows right so we want to subtract from it the total number of maximal gaps that we have and we know that the max number of gaps is in this position right so we see here there's two gaps and then there's two more gaps down here so the number of gaps is four right so six minus four gives us our result which is two right so this two basically tells us that these this is the minimal number of bricks that we're gonna have to cut right and i can show you that the cuts are happening with this brick and this brick up over here that i basically crossed out because i crossed out that row so i'm just going to quickly go through the rest of this example fill up our hash map and then it'll basically be clear what we're doing so we went through the first row let's go through the second row now so who's here we see there's one gap right three so again in our hash map we can take this two this one over here and replace it with a two because uh we're just adding one right over here we see another gap this is position four which is not yet in our hash map so we're going to say at key value 4 we have one gap that we've identified now we're done with the second row third row time at position one another gap has been identified so this one can be changed to a two so this is going to get a little bit messy and the next spot in our hash map over here right this is at position four three plus one is four so we're going to take this one value and now replace it with a two fourth row we see there's only one gap at position two so let's add that to our hash map position two we're gonna have one gap so far done with row four row three at position three we have a gap so let's replace this two and add one to it so we have three gaps at position three we have another gap at position four so let's replace this two with a three so now we're done with the fifth row on to the last row at position one we have one more so we can update the count and that's gonna be now three we see one more gap at position four so this three is going to be incremented into a four so i hope that this is readable this is a four over here and lastly we see at position five one more gap so let's just cross this out and say it's two but so scanning through our entire hash map what do we find that this value is the highest 4. that tells us at position 4 because that's the key position 4 right over here we had 4 total gaps right so that's the maximum number of gaps and we can basically now use our formula to compute the result just like i showed you earlier it's going to be 6 minus 4 equals 2 that's our result that's what we're going to return so this problem is actually not too difficult once you can understand this sort of equation and the need for a hash map let's get into the code it's actually pretty short so i'm going to have that count gap hash map just like i mentioned and i'm going to have one key value pair so far in it zero basically telling us at position zero we have zero gaps which makes sense and this is needed because we don't want our count gap hash map to be empty it's possible that it could be empty at the end and i'll show you why we don't want that but remember we're mapping the position to the count of gaps of brick gaps so now just like in the picture we're going to go through every row in the wall and i'm going to use a variable total which is basically going to tell us the current position we're at the reason i'm calling it total is because remember we're adding each brick in the row to tell us the position right so basically what i'm going to do now is go through every brick in this row so for every b in this row but i'm not going to include the last brick because remember we don't want to count the gaps at the rightmost position right we can't cut the rightmost position right so what i'm doing in python is basically going through every brick in this row except the last one i'm not including the last one so all i'm going to do is take every single brick and add it to total which is going to tell us the position that we're at right so the total is really referring to the position so and once we do that i'm going to go to our count gap say that position for that position i'm going to increment it by one so i'm going to say 1 plus what it already is and it's possible that this total has not been added yet to our hash map so i'm going to do a little python stuff so i'm going to get that value from our hashmap total is the key and if the key does not exist it's going to return a default value of 0 that's what i'm doing and this is a convenient way to do it in python so we're getting the current count of this position adding one to it and we're going to do that for this row and we're going to do that for every row in the brick wall and now what we're going to do is we're going to return the result but remember there was an equation that we had to compute that result so it's going to be the total number of rows how can we get that we can get the length of this wall basically the number of the rows and then subtract from it what are we going to subtract remember in our hash map in our count gap hash map we had a list of values and from those values what did we want we wanted the maximum value so we're going to take the max of this array now the reason why we initialized our hash map like this is basically what if our count gap hash map was empty what would we want it to return we just want it to return zero which is why i had zero over here right so this is the solution right it would there's nothing more that we need than that we had a hash map so really the time complexity of this is not too bad we're just going to end up iterating through every single brick in the wall so that's the time complexity the total number of bricks that were given basically the size of our 2d array and that's also going to be the memory complexity the number of bricks so i hope that this was somewhat helpful for you if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
Brick Wall
brick-wall
There is a rectangular brick wall in front of you with `n` rows of bricks. The `ith` row has some number of bricks each of the same height (i.e., one unit) but they can be of different widths. The total width of each row is the same. Draw a vertical line from the top to the bottom and cross the least bricks. If your line goes through the edge of a brick, then the brick is not considered as crossed. You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks. Given the 2D array `wall` that contains the information about the wall, return _the minimum number of crossed bricks after drawing such a vertical line_. **Example 1:** **Input:** wall = \[\[1,2,2,1\],\[3,1,2\],\[1,3,2\],\[2,4\],\[3,1,2\],\[1,3,1,1\]\] **Output:** 2 **Example 2:** **Input:** wall = \[\[1\],\[1\],\[1\]\] **Output:** 3 **Constraints:** * `n == wall.length` * `1 <= n <= 104` * `1 <= wall[i].length <= 104` * `1 <= sum(wall[i].length) <= 2 * 104` * `sum(wall[i])` is the same for each row `i`. * `1 <= wall[i][j] <= 231 - 1`
null
Array,Hash Table
Medium
2322
1,779
so lead code 1779 find the nearest point that has the same x or y coordinate with u so you're given an x and y coordinate of your location and an array of points and you need to find the point the index of the point that is closest to you according to the manhattan distance which is this formula right here and the point needs to be valid meaning that it shares the same x-coordinate or at least the same x-coordinate or at least the same x-coordinate or at least the same y-coordinate same y-coordinate same y-coordinate okay so the problem has actually a really simple solution so first of all we'll write down the formula for the manhattan distance which is this one and then we keep the current minimum distance that we have found so far and the index of the result and keep in mind here if you don't find any point that is valid then you should return minus one okay then what you do is just loop through all of the points and yeah we will return the result index and now we do what you do is you just loop through all of the points take their coordinates like this and now you check if it is a valid point so if the x is different if your location x point x coordinate is different from the point x and your y coordinate is also different from the point y then it means that at this point is not valid so we want to continue to the next one but if this condition is not met then the point is valid and so we can update our minimum distance so we check if the distance from our point to our location is less than the current minimum distance and if so then we update it and we also updated the result index obviously and that's actually it already so the time complexity here is o of n because you just go through all of the points once and the this function is o of one and the space complexity is all of one as well because you're not using any array or anything like that so that's it for me thank you for watching and bye
Find Nearest Point That Has the Same X or Y Coordinate
hopper-company-queries-i
You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location. Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`. The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`. **Example 1:** **Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\] **Output:** 2 **Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2. **Example 2:** **Input:** x = 3, y = 4, points = \[\[3,4\]\] **Output:** 0 **Explanation:** The answer is allowed to be on the same location as your current location. **Example 3:** **Input:** x = 3, y = 4, points = \[\[2,3\]\] **Output:** -1 **Explanation:** There are no valid points. **Constraints:** * `1 <= points.length <= 104` * `points[i].length == 2` * `1 <= x, y, ai, bi <= 104`
null
Database
Hard
262,1785,1795,2376
989
all right so this question is add to a reform of integer so you are given the array integer array and then the value K so basically need to add the value K into the nums so this is the idea right so the main purpose is what you Traverse from the last digit and all the way to the what to the left right so we need to also know when do we need a carrier and when do we not using the carry so we have to think about K as a carry so you know if K mobile came up at 10 is actually equal to 4 right so we know we are adding 4 with what the last value so I'm going to say 0 right and then uh just think about this if the numbers array at least index is what seven just think about it seven plus four is actually equal to eleven right it's actually equal to 11 but we don't need 11 right we only need one because one zero one two zero seven plus thirty four is actually equal to one two four one right so we need one right so we change them up by 10. which is equal to one right but we need to say one children I mean we need to carry one to the uh to the three right I mean to the next stage right so we have to know Norm say I plus with which is uh which is seven in this case Plus 34. the default value 34 is actually equal to what 40 is 41 right so we need to update the k equal to 41 nine divided by 10. so the next iteration you Traverse you will get what 4 is okay so uh and then you have to travel skip try version keep traversing until the entire array uh is done and also the carry is not uh it's not one so you have to travel something okay k equal to zero right so this is pretty much the idea and then we need to store the value into a linked list so when we add the value into the list we can say uh we can always add the value into the interest zero right so imagine this is zero and then now we have another value and then we keep pushing the value back to the last one right so this is pretty much the idea so I'm going to use a link list integer result equal to new linkless when I return I'm going to return the result and when I Traverse from the last digit so I need to add the value industry right and I need to what think about my mobile 10 right so okay and then more by 10. I need to what I need to update my carry right so if num say I plus K divided by 10 which has something then you just you know just update it right so this is pretty much the idea but what happened if k if K is equal to Y which means there's a carrier there is a carry so wow okay greater than zero and then result the add 0 and first one right so K divided by 10 right so this is pretty much your idea right so um let me run it oh sorry uh integer right so it should be what came up by 10. some sandwich right oh okay sorry I thought this is a stream but whatever all right so for the timing space this is a space so the worst case is going to be about all of N and represented end of the numps array and then the time is going to be all of them right Traverse every single one of the digits and definitely you have to depending on K right because K could be largest but I'm talking about ideal answer it's gonna be all of them so time and space and let's talk about the debug okay so imagine about and above and then let me see all right so this one start debugging uh you can pause at any second and I'm going to keep traversing all right so this is pretty much the idea right so uh I made a mistake say one but it's not one you have to multiply 10 depending on the value you mark right because K could be large right and then when you try this entire array so imagine this uh finish right so K could be largest so imagine K style is a large value right you have to mod by 10. even though you Traverse you finish the traversal follow numbers array you still have to Traverse the K the remaining value right so it has to be more by ten it's not always one right so this is the entire solution so if you have any question leave a comment below subscribe if you want it alright peace out bye
Add to Array-Form of Integer
largest-component-size-by-common-factor
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num = \[1,2,0,0\], k = 34 **Output:** \[1,2,3,4\] **Explanation:** 1200 + 34 = 1234 **Example 2:** **Input:** num = \[2,7,4\], k = 181 **Output:** \[4,5,5\] **Explanation:** 274 + 181 = 455 **Example 3:** **Input:** num = \[2,1,5\], k = 806 **Output:** \[1,0,2,1\] **Explanation:** 215 + 806 = 1021 **Constraints:** * `1 <= num.length <= 104` * `0 <= num[i] <= 9` * `num` does not contain any leading zeros except for the zero itself. * `1 <= k <= 104`
null
Array,Math,Union Find
Hard
2276
287
Hello hello everyone welcome back to my channel we are going to discuss the clean money problem shape is the problem find duplicate them this necklace one in teachers show statement but given allotment teachers containing and Laxman in teacher ok a career this in this One plus one is interior and it is a lot of things, it was released in Want to have the intrusion, it is okay, both are intrusions and thus one is in danger, it is okay because why is inch plus one because one is the number, it is repeated in Delhi. The Sun Was Repeated Number in Dance Better Returns Pen Number Four Batane Ki Beti Number Hai So See This Later Us Basically Modify Yours In This One Are Ko And Express News To Us We Can Only Take Conference Paste So This Is The Problem So many times it is asked in the interview, the problem was this, we will discuss the solution, the first step is to use this map, if we use it quickly, then it is a simple situation, okay, it is intuitive simple and in this, if we use it on express, then there will be a special point in it. If it doesn't work, it's okay, then this solution will not work for us, but still I will discuss something, after that we will use a solution in this, we will modify it, we will modify the gesture, but okay, then that one also for us because as given in Ghoshal that our If you can't qualify then that one also won't work, still we will discuss and see the solution, consider it red, it satisfies both our condition scores that we will not modify one and we should use quarter inch plus. Okay, we will not modify one. And if you use Constantius, then this solution is Math Solution of Math, I am so true, first of all, I accept this every day, so at once, I press this, will use cheerful, how today I, now look, we will make us in the cross like we describe, there is one in this. We have made it, we have put this 11:00 in it, here we have our value put this 11:00 in it, here we have our value put this 11:00 in it, here we have our value which is the treatment element, whatever you call it and here the value which is that its song is fine, as much as the account is, then the account of the first dam will be water or will you put two. The card will also be Vani by default and it will be created okay, then the account of three is also not of us Vani or even for, in the President House we will put our account as well as his, we will put five poets and is and six sometimes we will put one and then. When I go back also, see it is already in the map, meaning this is our repeated, so this is how this money approach was done and we are doing a single traversal at a time, so that time complexity got opened and because inch plus one element channel and also These teachers are there and we are ours, our exam will come, neither is the space, we have space in time, so this is the solution, there are 11 approaches, today I am using them, it is quite simple, so this process, we mean this one So now let's look at the second approach, in which we will modify the legs, that is, the actress that we are using today, we are getting that, then we read it, we reduce it, if we do not use that form, then this is our experiment. Off and time and their insult feet i.e. the time and their insult feet i.e. the time and their insult feet i.e. the problem in this on the costumes page is that it modifies my so that how it will be seen then we will press from here we have done this first we will just add it in this na from churu we will make our point that I Now we will run this drop here, which is one, follow it, that is, whatever our XUV value is lying on this area of ​​high, we will follow it, that is, whatever our XUV value is lying on this area of ​​high, we will take the offer and wherever I am, this value means this. Whatever description you see in Vansh on Intact, type it, okay, we will cut it, here it will go - okay, we will cut it, here it will go - okay, we will cut it, here it will go - You are okay, after that we will go, if it is here, then we would like - to bank here is here, then we would like - to bank here is here, then we would like - to bank here we are of porn, we will just put it and or RAW. What is there on two index, so index is restricted, so we will make it free here, it will come into three, some mangal - this is killed - okay and we three, some mangal - this is killed - okay and we three, some mangal - this is killed - okay and we will run it again here, so simply this is the folk custom, the area of Then that place of pimple - Ko Then that place of pimple - Ko Then that place of pimple - Ko A Similar that we will go ahead A And then what will happen on the whole lip Five then it was that if the point gets activated then the pipe - On the side Then we would go to the pipe - On the side Then we would go to the pipe - On the side Then we would go to the findings We will take water in the stomach Image Six - Tomorrow here But we will come, - Tomorrow here But we will come, - Tomorrow here But we will come, okay, and then see this Shiksha Bade Free Usko - 02 Now let's do the last, see Free Usko - 02 Now let's do the last, see Free Usko - 02 Now let's do the last, see here we agree, please friend, the accused is not on the option, friend is already opted, negative value is lying, a positive value means that the point is this. We have taken this chilli of ours, it had come somewhere earlier also, it had come somewhere earlier, due to which there are people with negative energy on the index, that they are thinking that this is our repeated number, so what will we return, where we are ours, whom we when we are here But we will check that the value of this one is already native, okay, then what will we do, we follow this one because this is our repeated number, okay, so you must have understood that this is also a The approach is fine and because look at America in this we are modifying that - If you do negative then modifying that - If you do negative then modifying that - If you do negative then this will not be our strength even every day. I take interest in the office that then I give it once on school dress. Let's write it again as 123. Warning toot three four five to six tu now this burn will support by the way introduction in this basically so now what we will do is we will list one and a half note it like this is whatever is this note so we were 123 like this four five fix 363 that means something We will fold it like this and return it, but here there is CR here, so now you send it, what does it mean, what is being made, in a way, this has become our bicycle, hence in English, bicycle has become ours without any bicycle, so we have basically made it, what to do? We have to keep this, we are volume engaged in converting it in English that it is like a leak and where the defeated element is play element here and then this belt here and so it will make a bicycle, okay. So what should we do, basically we know that a cycle will be formed, because we said that there will be a repeated number, so if there is a repeated number, then a cycle will be formed, by the way, we have found this starting point, why setting on cycle fighting, the shoe will either be the same or that, but Defeated element because this point from here will be Bhang which will be the repeated element here, so we have taken out this thing. Cashew is the starting element of this cycle. So you must have understood that we will celebrate in English. Babbar used to sleep on this thing, now in English. We will create June and now we will have to find out the settings, then we will use the cycle, we will use this product, I will copy the match preference from this point, now we will ask something once how it will work, take it in. If we have taken out the settings of the bicycle instead of English, then we use the same approach, one gift, then we paste it here, you see what we will do basically, so we have to take out this setting on, we have two points, one is always slow and fast, our two. There are parts S Law and Order Okay and one would be our first point Oh tomorrow I have a reminder there we will point at the beginning first element 90 i.e. and beginning first element 90 i.e. and beginning first element 90 i.e. and here too now don't look at this we will look at this We will go to both sides We are ours It was not there in the bus otherwise we will take it, you are number 0 and fast also, we experts in all things take it to a big maximum, zero one, why screen four five six, okay now look, we will drive till slow is not equal. Toe is fast and this work is done in 1995, we send people one text and another passport, neither will we do the same thing, whoever asks why the phone number is switched off i.e. the whoever asks why the phone number is switched off i.e. the whoever asks why the phone number is switched off i.e. the name is clear, whatever it is, take it, take a number of Numbers of Art Festival, that you are successful, number of 192 todo and here the name is soft outside, number two three, so let's go here, slow was here and even today, now slow which has gone one step ahead, here it has been made 212 and fast, look fast. Here I have a big difference from the next two, so I will do it like this, as long as I do it will work as long as I don't worry, okay, so let's look here at the name because if the name is slow, the name is fennel 203, then it is deep. And this name was Muzaffar Ali, Sahib's name was Asaf Khan. Poonam says, everything is fine again. Give other names as before, normal i.e. file, names as before, normal i.e. file, names as before, normal i.e. file, so this is our Ghaghra, if it is still there, then it will work again. People, now see, ours is here and fast. It is done, we have come here, if you want the name of your loved ones, i.e. handed over and if you want the name of your loved ones, i.e. handed over and if you want the name of your loved ones, i.e. handed over and passing name, give fast offer, i.e. passing name, give fast offer, i.e. passing name, give fast offer, i.e. number 156 and new born can learn. Okay, so you have come here. Now see, will you say this or not? So now this is ours which is the one above Okay now we will keep these five now which will add the English part back to us which is our starting element tree fast election me bill pass ho tum mein love scene was shot again we If you mix it with everything, then this bond of white or pitra, let us run till then, we will take both of them one step forward, not only that but also fast in the crops and when they remove it, then our settings will be in our show. You will get the bicycle that is tied here, the golden one has become soft and here this sorry vansh varchanam surfing this two, then after that the name becomes clear mor this and the norms of two this should be AP's after that the name boss- 5 it will be fine AP's after that the name boss- 5 it will be fine AP's after that the name boss- 5 it will be fine and the name the past name clear fast this of the phone or after this see here Navgachiya this tube will go and the matter then this fiber will go then we will move ahead like this and it will be completely done then this potato top of ours will go then this But if we make it clear then the norms of three will be taken, the fourth 95 sum will be unwoven like this, then the sum will be white and the number six sum will be free that this thread will behave like this and if you forget this here, then these people will return if you go. Okay, so take this and this water and once we complete it, this is the tuition that we had any and in this, if we take this duplicate three of ours, if we click on this, then this is what we need here, so this was basically this. If you liked our video then please like and subscribe if you want to see the next video.
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without** modifying the array `nums` and uses only constant extra space. **Example 1:** **Input:** nums = \[1,3,4,2,2\] **Output:** 2 **Example 2:** **Input:** nums = \[3,1,3,4,2\] **Output:** 3 **Constraints:** * `1 <= n <= 105` * `nums.length == n + 1` * `1 <= nums[i] <= n` * All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. **Follow up:** * How can we prove that at least one duplicate number must exist in `nums`? * Can you solve the problem in linear runtime complexity?
null
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
41,136,142,268,645
1,260
hey everybody this is larry this is day 11 of april uh let go daily challenge hit the like button to subscribe and join me on discord let me know what you think about today's problem shift 2d grid okay which one okay so you can k shifted k time what is one what is k so do you just move it okay so basically you i guess it's not a rotation but it's just shifting k times okay and i guess this is just i mean you could do let's look at constraints for a second i think if k is small enough you can uh yeah and k is a hundred so you can i guess just do it okay uh do a for loop and do it k times i think technically if you want to be a little bit smarter you can actually just copy it over um i don't know if you want to do it in place um i get i think if you do it in a in place then you don't have to use extra memory but and there's these just things that you kind of can think about um okay so let's get started how do i want to do it hmm uh would i ship it k times i just got a new one let's try to up solve a little bit and do a new one uh i mean it's not that much harder of an upself but i think it's something that i um i get wrong a lot is i guess is my point so um yeah matrix of i j is equal to okay so maybe you can do something like shift i j k and of course technically you can just keep on incrementing but um but it's okay uh for your live region i mean technically i kind of wanted the other way actually so maybe this way and uh is you go to a grid of ij now do i oops none of the way and of course the return matrix um and then you have to call this shift function so x y and k um this is not independent of rows or and columns so each row will have c columns so that means that it is x times c plus y um i'm trying to figure out which direction it is this is plus k or minus k uh let's because i uh this thing decides i guess we can just do it both ways and then if it's wrong then um then it is just wrong uh but yeah so then this is basically number it from left to right and i just call it position maybe and then of course uh after you mark due to the k then now you have position uh mod oh there by c position mod c hopefully uh it may be in the wrong direction but i think the idea should be right uh yep looks good try it some small numbers okay so that looks good so i think we should be good to just give it a summit hopefully this is right i wonder how what i did last time okay i guess i probably just shifted k time last time uh let's take a quick look yeah okay yep um yeah so uh the complexion is going to be off i want to say n because uh but that's confusing so the complexity of r times c which is the size of the input so it's going to be linear time uh this is also going to be linear space um yeah because we allocate obviously this memory you can actually do it in place if you're really slick and smart about it the idea is a little bit tricky um you can think about how you do it one at a time by shipping it one at a time by keeping track of the previous etc you can kind of do that except for that the cycle length uh may not be the entire uh matrix because it depends on k and r times c um but you can kind of think about it almost like a permutation cycle type thing where every number has uh a number that it's referring to and in that case you can do that to kind of get the entire matrix so uh i'll leave it up to you at home if you want to try absolving that using in place memory um but yeah that's pretty much all i have for this one happy monday happy sunday wherever you are um have a great week stay good stay healthy to good mental health i'll see you later bye
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
1,047
hua hai hello everyone welcome to day 28jun liquid sycophant appointed as westerners remove all parts in duplicate sunscreen inspiration to give in spring of directors and want to remove all the duplicates do viravar subscribe to and hadith 220 alerts and veervar ko remove damad se 0512 subscribe To remove all parties and implications ring lift 104 70 concept business this question so that last post andhe those subscribe schools subscribe to are next bihar be fennel but in the colleges subscribe and entry element subscribe to are let's move ahead with greater noida and this Time She Deserve Vidyapeeth Muslim Stock Unfit Certificate Format In This Will Give This Element And Will Lead You To Come On Let's Start Victims And Trick Ek Ansh Vihar Phase Paying The Top Most Element Will Not See One Another And Lord Yagya Notification More Sleep Subscribe My Channel Subscribe Will Ignore This Entry Video Subscribe Trees Grow Directly To Them One Message Slaughter Talk With Approach Now List Talk About Another Approach Will Not To Subscribe To 100 Dial Used Oil Usage Spring Builder Bigg Boss Delhi Edition Of The Last Character In String Veer One Time Complexity Oil Defined Stringbuilder Available for mid-day Available for mid-day Available for mid-day that Bigg Boss Katega Vihar Phase Stringbuilder Distributors Vihar Is MP3 200 Gram Boiled Pushp Minute Element Up and Elements in Distributor Next Nuvve and Singh Virwar The Video then subscribe to subscribe our New Delhi Station in String builder tax complexity of first tuesday the concept of the last month last updated on let's move ahead vibration greater noida and match with last director in the string and will reduce the play list move ahead Gagan Vihar Rahegi do subscribe day is next vihar phase for watching This Channel Subscribe Video then subscribe to the Page Ki Without Mazdoor Network Aate Ko Diction And Talk Less Cost Month According Path And Read Beautiful Post Zara Favorite Amused Me Solution Acid News Talk And Laugh With Now Scooty And Not It's Not Empty Adheen will take top most element subscribe with oo 116 try report approach that accepted lips planets and secret solution - created approach that accepted lips planets and secret solution - created approach that accepted lips planets and secret solution - created that aunt yo define stringbuilder news bank and divided over all the character done now input string in it length of The String Events and Last Character is Equal to Indian Idol subscribe The Channel Please subscribe thanks for watching this Video plz subscribe Channel subscribe kare do ki a
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
119
hello YouTubers in this video we're going to be going through lead code problem 119 which is pascals triangle 2 given an integer row index return the row index zero indexed row of the Pascal's triangle so in Pascal's triangle each number is the sum of two numbers directly above it as shown so 1 + 1 is directly above it as shown so 1 + 1 is directly above it as shown so 1 + 1 is two and the graph to refresh here so 2 + 1 3 and the graph to refresh here so 2 + 1 3 and the graph to refresh here so 2 + 1 3 + 1 4 3 + 3 6 so on and so forth so 3 + 1 4 3 + 3 6 so on and so forth so 3 + 1 4 3 + 3 6 so on and so forth so example one row index equals 3 so 0 1 2 3 so it's 1 3 1 in example two row index zero which is output of just one and in example three row index one is one and one okay all right so the way we're going to do this so let's say we want this last row well we can't magically get this row without knowing the values in the previous row so what we're going to do is rebuild the entire triangle down to the row that we need um and we're going to keep putting that in the same index we're not going to have every time I we get a new row we're not going to make a new array list we're going to just use the existing one and have a little tutorial here that shows that okay so here is our third row the first thing we're going to do is place a one at the end of the existing row then we're going to add three 3 + 1 to get 4 we're going to add three 3 + 1 to get 4 we're going to add three 3 + 1 to get 4 then we'll do 3 + 3 to get then we'll do 3 + 3 to get then we'll do 3 + 3 to get 6 then we'll do 3+ 1 to get four and 6 then we'll do 3+ 1 to get four and 6 then we'll do 3+ 1 to get four and there we have our fourth row so let's see how to code that all right public list of integers called get row passing in a row Index this is the method that lead code gives us for first thing we want to do is create a list of integers which is our return value and we're going to state that to a new array list and we're going to do row index plus one now throughout this problem we're going to have to keep dealing with the fact that indexes start at zero but Pascal's triangle starts at one so we pass in if we pass in row index zero well Pascal's triangle doesn't have a zero row so we add one we get the first row so it's just off by one so because Pascal's triangle always has ones on the left side and ones going down the right side we're going to add one immediately now we're going to go through and build each row to get to the row that we need down here so we'll have an internal Loop to build each element in the row we'll sign that equal to I and we'll always make sure it's greater than zero and we'll decrement J so here we're going to let's say we're down here on this last row so we're going to set J which will be let's see so if J is because we're working backwards here so J will be equal to I so this will be 0 1 2 this will I will actually be equal to four because we're on the fourth index which is the fifth row so J will be equal to four so 0 1 j0 0 1 2 3 4 so we're going to set J equal to row get J plus get J minus one so let's say this is J minus one and we're going to add those two together and we'll get the four and that's pretty much it we'll just Loop through until we get all the numbers and then we get all the rows and at the very end we're going to add one again and that is the method and then finally we're going to return the row and end the method so let's debug this which will clear up all the questions I am sure so we're going to do this last row here we're trying to get this last row index of four create a new array list and we're going to add one so very simple row size equal one array zero value one so now we're going to start looping through um each element in the row now if you look initially because we assigned I to J is zero and J is not greater than zero so we're just going to add one so this is how we get uh the second row is just one now we're going on to the third row and J in this case is 1 which is greater than zero so we're going to set J plus J -1 so this is so J is one which J plus J -1 so this is so J is one which J plus J -1 so this is so J is one which is one and J minus one is also the one and so we're going to add those two together and get the two then we'll add one at the end so now if you look at row it should be one 21 which it is so we'll just keep doing this until we get to the row we need okay so I is 2 which means J is two so zero keep in mind that we're still using the same array so 0 1 2 so J minus J is two 2 - one 2 so J minus J is two 2 - one 2 so J minus J is two 2 - one and two so two and one so 0 1 2 plus one zero I'm confusing the numbers with the indexes with index one which has a value of two so 2+ 1 is which has a value of two so 2+ 1 is which has a value of two so 2+ 1 is three and it's going to do that twice and then we add one at the end so now it should be 1 3 1 okay now we're on to the final row where I is three which makes j3 so 0 1 2 3 so we're going to start here with this value so this is J minus one so now we're going to add those two together and get the four now we're going to add 3 + 3 and four now we're going to add 3 + 3 and four now we're going to add 3 + 3 and get the six and now we're going to add 3 + 1 and get the four and at the very end + 1 and get the four and at the very end + 1 and get the four and at the very end We'll add the four or add the one all right so now you look at the index and it's 14641 which is what we want so I return that and that is the answer now if you look at the solution 14641 and that is exactly the result that we want so let's run this through lead code and see what we get success submit that faster than 77.99 and use less than 83.4 7% memory I 77.99 and use less than 83.4 7% memory I 77.99 and use less than 83.4 7% memory I always like to run it twice to see if I can get better oh less than 95% better oh less than 95% better oh less than 95% memory just because lead code can be wonky sometimes with the results all right the last thing we'll do is the time and space complexity the time to run this because we have to do two for Loops it's O of n^ s so if we increase Loops it's O of n^ s so if we increase Loops it's O of n^ s so if we increase the size of these Loops or increase the size of n it in increases the number of times we have to go through each Loop now space complexity is just o of n because we're reusing the same array so it doesn't matter how many you know the two Loops because the size the space needed to do that never changes and that is it so once again thank you for watching let me know if you have questions and we will see you next time
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
204
welcome to mazelico challenge today's problem is count primes count the number of prime numbers less than a non-negative number n so if we're a non-negative number n so if we're a non-negative number n so if we're given the number 10 we're gonna return four because there's four prime numbers less than ten two three five and seven so i believe it's inclusive um and they give you a ton of hints here it's a classic problem and i think it's good to kind of go through the basic intuition now the first thing that we need to understand is that 0 and 1 are not primes and that should be obvious but it's good to remember that now normally when you solve this problem say you were doing this in an interview you could probably just move from the numbers like 4 1 to n and for each one of these like check to see in range of like uh whatever this number up here uh if it's none of these are divisible for that number within this range so say that we had the number five um we could check to see all right is it divisible from any number between two three four uh if it's divisible by any of these numbers exclusive that means it's not prime now it should only be divisible by its number itself so five and one right but that would end up becoming like an n squared solution it's pretty inefficient it might be perfectly accepted in an interview but we can do better and i actually read about this recently there's an algorithm known as the sieve of aero themes okay and here's the basic idea what we'll do is build an array from zero to all the way to n the number that we're trying to check for and what we'll do is first mark all these index numbers as true now what we'll do is build up from the bottom up we'll start with number two because they're all in one or not primes and for every number that we can add two to uh other than the number itself two is a prime because we're building this top up we'll just mark that as prime immediately but every number that we add 2 to like 4 6 8 10 all of these are not going to be prime numbers so we have to mark all those as false now once we get to the end start at 3 now 3 has not been marked as false so we'll keep that and then we'll move for all the multi multiples of three six nine if any of those are not marked as false we mark those as follows all the way up to the final range we continue this algorithm until we've marked every single one of our numbers and the key thing is when we check the index number here if it's already marked as false then we can skip it because that should mean that everything before that was already marked false okay so here's what we'll do the first thing we'll check is if n is equal to zero or n is equal to one we can immediately return zero next we're going to create a array of primes and the index number is going to represent the number now i know 0 and 1 are already should be marked false so we'll do that as well we'll say okay marquee is always 1 for now making that true and then we'll say all right primes zero make that equal to zero and primes one also make that equal to zero okay so now we need some sort of iterator and we start at the number two so while let's see i is less than n what do we want to do well now we're going to have this nested for loop but we're going to check all the multiples right and what i'll do here is if the primes of i if this is marked as true right now that means we want to do our for loop so we'll say okay this is marked as true but everything else every multiple after that we're going to mark as false so we'll do is create a temp i will say all right let's temp here equal to the i and to the temp we'll say plus or equal i and all the primes of temp now we're going to make that equal to false and we have to do this in a while loop let's say while temp is less than n i'm going to mark it's not one of these like this once we're out of this we're going to increase our i one now at the very end we should have an array of all the index numbers either marking as marked as true or false so we're just going to return the sum of these primes right here so let me make sure i got this right here we'll test out number 10. okay times 10. okay so i think what i have to do is put it at the end and increase it just one time right before this violin all right so right here you can see two three five seven are marked as prime numbers and that's true right uh so this should work for any number let's go ahead and submit this and there we go accepted so time complexity wise it's going to be n log n although technically i think if you want to get really technical it's log or n log of n but you know that's it's really not that different so yeah this is the sieve of how do you pronounce it sieve of a wrathful thingy's algorithm pretty useful uh anything involving prime numbers this would probably be a much more impressive solution rather than the brute force method alright thanks for watching my channel remember do not trust me i know nothing
Count Primes
count-primes
Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`. **Example 1:** **Input:** n = 10 **Output:** 4 **Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7. **Example 2:** **Input:** n = 0 **Output:** 0 **Example 3:** **Input:** n = 1 **Output:** 0 **Constraints:** * `0 <= n <= 5 * 106`
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors: 2 × 6 = 12 3 × 4 = 12 4 × 3 = 12 6 × 2 = 12 As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n. Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach? public int countPrimes(int n) { int count = 0; for (int i = 1; i < n; i++) { if (isPrime(i)) count++; } return count; } private boolean isPrime(int num) { if (num <= 1) return false; // Loop's ending condition is i * i <= num instead of i <= sqrt(num) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i <= num; i++) { if (num % i == 0) return false; } return true; } The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple. Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0. We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime. The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia. public int countPrimes(int n) { boolean[] isPrime = new boolean[n]; for (int i = 2; i < n; i++) { isPrime[i] = true; } // Loop's ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for (int i = 2; i * i < n; i++) { if (!isPrime[i]) continue; for (int j = i * i; j < n; j += i) { isPrime[j] = false; } } int count = 0; for (int i = 2; i < n; i++) { if (isPrime[i]) count++; } return count; }
Array,Math,Enumeration,Number Theory
Medium
263,264,279
1,373
That a hello confusion idiots problem call maximum bases in the trees and bring to front and tasty something rich maximum of all BSC first year to that vijendra galaxy pocket despite qualities of ministry latest express and nod in this worship and point this first service team and Values ​​to the right this first service team and Values ​​to the right this first service team and Values ​​to the right side officer shoot beat a connix ladies always be right certificate this prohibition and factories a police present planets 12873 degrees benefit node in tree sentences for be id college in tight it will come that bandits zinc quality my voice mail messages dot x THIS DAM THE MAXIMUM ELEMENTS PRESENT IN ITS LAP SHAKTI SIMILARLY AXIS MONITOR MINIMUM Divya President Turn On Free Mode 102 That Run To Confirm That Angry Birds Him Loud Bigg Boss That Call Me To Check Is The Condition Discontent And It Will Destroy This Wall Street And are also beneficial to debit the laterite soil to be possible only when will be concluded at least 122 Rasool and tell English me to calculate the maximum all so let's see how to write come 122 Calculate distance between wash mint 10 feet and let's you all The Best That Newly Formed Sapoch Diya And Priya Career 10 More Latest Tour Yesterday Su Akbar How Distributors Routed Through This Very Best I Need To Find The Minimum Person Developed And Amazon Yesterday Morning Moving From Zaroor Load 205 Volume Minimum Balance Loop President In Elementary And The Volume Friend the maximum second you can be compared with 4 vitamin A history and avoid them where is the distributed with oo and hear awidget are let's see how they can also decided that do you need to do like a dab aged Add to all of you is this check this truth in the battle treated as they celebrate c ajwain it's not and you need to sources minimum and maximum value committee discussed bluetooth chapter condition now sleep latest beginnings from against now half to 20 body huge only One Element The Amazing Pilot And Condition Diet Business subscribe our YouTube Channel and subscribe this Video like and subscribe the Channel - 121 kaun gali paar ki setting on shree navdurga mixing ball deficit and right now and will update you reside at a private end Let thumb down 0 ki boat latest want to the next mode tips tree loop child shoulder reduce hair dry sector-9 located in this mode on the hair dry sector-9 located in this mode on the hair dry sector-9 located in this mode on the minimum balance it's right street light 720 condition from this side loud discretion is always satisfied and take off history Develop even the slightest interest in monitoring and come in the streets and maximum organize an adult heartist let's do this trick of computer labs and subscribe to and the tree and tree to avoid you and monitor smallest element Twitter The Amazing element this enters element this channel That Surya Vidisha and Plut and Dasham do Saathi all people but it's 28th to impossible there next diet preluts children always bse saw na dharma - 120 saw na dharma - 120 saw na dharma - 120 plus 2 and then she gives no 786 ki side in this great dan the largest and oldest and smaller And Smaller on this person 800 to 1000 cc and small s well who encountered it is - more than 120 who encountered it is - more than 120 who encountered it is - more than 120 interest soya and bt juice name let's move to on this day from it 0tweet 12218 dh a silent want to download latest to come word the small Baby Pump To Z Till Tree This To Classes Attend Dowry 100 Written Complaint Na 2010 Present Conditions Element Black And Smaller Each Element Will Do It Inside Dowry Tasty And Commentators Who Had Amazon Counter Statistics 10 We Shape Decide Status Boys Twenty-20 10 We Shape Decide Status Boys Twenty-20 10 We Shape Decide Status Boys Twenty-20 That Don't Orchid Na ho let's move to the next month at school Dasham is mean by four plus to dentist 6 and not only summary and vestige so let's make this preparation for it is not better the a large s element collect it means late evening elements of kill 40 Condition Violets The Properties Of Binary Search Tree Sweep And Clean Remaining This Is Not To Validate T&amp;c Validate T&amp;c Validate T&amp;c That Demonetization Declared That Does Not Have Done As Really Don't Need To Care About Kashmir Valley And Modifications 9 And Sisters Of This Country Is This Mode Bigg Boss t-20 Properties Invited Them Bigg Boss t-20 Properties Invited Them Bigg Boss t-20 Properties Invited Them With Sonu And Sister Of Four Person Suede Shoes But That One Point Dub The Smallest Element Benefits 0 Maximum Element Is Achhi Ki Side Hai Ke Daag Movie Collection Mode Set From This Dynasty To Half The Amazing 6 Plus Minus Z - 819 subscribe and subscribe the - 819 subscribe and subscribe the - 819 subscribe and subscribe the protest venue also not the minimum balance - 121 ki charit aa jaao divas not updated with your complaint middle of the bottom row in notes only to-do middle of the bottom row in notes only to-do middle of the bottom row in notes only to-do list - this Video list - this Video list - this Video ki Surya Network Problem List 2 And I hope you understand this approach side the complexity and cleared from where and when number of deaths due to english 108 like this video to separate and subscribe our channel till 2018
Maximum Sum BST in Binary Tree
maximum-sum-bst-in-binary-tree
Given a **binary tree** `root`, return _the maximum sum of all keys of **any** sub-tree which is also a Binary Search Tree (BST)_. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,4,3,2,4,2,5,null,null,null,null,null,null,4,6\] **Output:** 20 **Explanation:** Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3. **Example 2:** **Input:** root = \[4,3,null,1,2\] **Output:** 2 **Explanation:** Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2. **Example 3:** **Input:** root = \[-4,-2,-5\] **Output:** 0 **Explanation:** All values are negatives. Return an empty BST. **Constraints:** * The number of nodes in the tree is in the range `[1, 4 * 104]`. * `-4 * 104 <= Node.val <= 4 * 104`
null
null
Hard
null
101
hey everyone welcome back and let's write some more neat code today so today let's solve the problem symmetric tree we're given the root of a binary tree and we just want to check if it's a mirror of itself so what that really means is we're just comparing the left subtree of the root and the right subtree of the root itself doesn't really matter because think about it a node is pretty much symmetric with itself so then analyzing the subtrees for them to be symmetric well the roots have to be equal so we have to check are the root values equal in this case yes they are 2 is equal to 2. now this is where things get different from leak code 100 which is the same tree problem I believe where we're just comparing the two trees and checking if they're equal and this time we're doing it slightly differently we're not checking if the left child of 2 is equal we're not checking if these two nodes are equal we're checking if the left child of 2 is equal to the right child of 2 on this side we're looking at them on opposite sides and similarly we're going to compare the inner Childs as well so here the right child here the left child are they the same and this is a pretty small tree so we don't know for sure if the way I'm kind of explaining it right now is going to work for the entire tree so let's draw a bigger one so this tree is similar to this one but we've added another layer so let's see recursively if our previous algorithm will still work so starting at three what are we going to do we're gonna compare opposite children so we're going to compare the right child of this guy and the left child of this guy and yeah that is going to work in this case because yes these two sub trees are symmetrical so you we can see that this algorithm is recursive in nature just like the tree so our algorithm is going to hold and looking at the left child here it's null and looking at the right child over here it's also null so that's going to be our base case so for a tree to be symmetric eventually we're going to have to reach null nodes and null nodes will say are symmetric so I didn't draw all of these but we're going to assume that there are null children for each of these now going back to four we know that these themselves are opposite nodes we knew that earlier but now running our symmetric recursive algorithm on this sub tree we're going to check the left child of this four with the right child of this four they're the same and the right child of this four with the left child of this four they're the same so we can see yeah the algorithm is going to hold its recursive in nature we're going to have to pretty much run a DFS on the left subtree and a DFS on the right subtree at the same time simultaneously to compare nodes in both trees which means we're going to visit every single node in the entire tree so it's going to be an O of n algorithm where n is the number of nodes and the memory complexity is going to be the height of the tree just like with any DFS algorithm so now let's code it up so like I said we want to run this recursively so I'm going to Define an inner function which I'm going to call DFS you don't necessarily need to make this an inner function but you do need to Define another function because we're going to need to pass in two parameters which are going to be the roots of each of the sub trees left and right because our outer function only takes a single parameter so we need both parameters and with DFS you always want to start with a base case what's going to be the base case well what if both of the nodes are null so if not left and not right so both nodes are null what does that mean well basically the tree is symmetrical if both of them don't have a node in that position so we're going to return true in that case now what if only one of the nodes is null and the other one is not first of all how do we know that well if we get to this point we know that both of the nodes can't possibly be null so we're going to check if one of the nodes is null I do we do that well if not left or not right we know that one of the nodes is not null in that case we have to return false because the trees are definitely not symmetrical we want to compare these two nodes left and right if one of them is null and the other one isn't we can't compare them so we have to immediately return false now if neither of these is true that means both of the nodes are going to be non-null by definition because if one of non-null by definition because if one of non-null by definition because if one of them wasn't all we would have returned so now we can finally compare the nodes we want to compare the values of the left node and the value of the right node we can do that just like this they have to be equal for us to be able to return true from this DFS but not only do these nodes have to be equal we have to compare the sub trees how are we going to do that we're going to call DFS on the left node and it's left subtree and we're going to compare that subtree with the right subtree from the right node because they are opposites and then we also want to compare the inner nodes or the inner subtrees so we're going to call DFS on left dot right and we're going to compare that with right dot left I know it's a bit confusing because the sub trees are called left and right and the trees themselves that we named are left and right as well but I hope that this is clear we're clearly comparing the Opposites left with right and right with left so this will evaluate to a Boolean and not only that these two recursive functions won't execute if this evaluates to false because if this is false since these are chained with an and operator this whole thing will be false if this is false that means we won't end up executing any unnecessary work so what I'm going to do with this is turn it into a Boolean or well it's already a Boolean but I'm just going to wrap it in parentheses and then return the entire value and before we try to submit our code make sure to actually call the DFS that's a step I usually forget so calling DFS on root dot left and root dot right so now let's run the code to make sure that it works okay my brain is lagging a bit we have an extra and operator I don't know how that got there sorry about that but as you can see it works and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neetcode.io it has a ton of free neetcode.io it has a ton of free neetcode.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Symmetric Tree
symmetric-tree
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-100 <= Node.val <= 100` **Follow up:** Could you solve it both recursively and iteratively?
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
501
According to Adarsh ​​Mishra, this is the According to Adarsh ​​Mishra, this is the According to Adarsh ​​Mishra, this is the nation code you are seeing and today we are going to talk about the list flight mode in binary search tree appointed to subscribe got upset there are some duplicate elements inside it village again to turn on the subscribe most frequently appointed to subscribe It is said that if we have a possible, we can add any of them, we can add it to this, the first thing that you have read the question, but the first thing that you have to notice is that the binary search tree has been given to you, then the lineage. You should come here, you have to understand that question, before that the second one is given here that due to death, now duplicate spelling can happen inside the ministry, then what you have to do is to remove the most frequent element inside it and if there is more than one element in it. Ghr and subscribe to it in any here property ghran ghrin ghrun subscribe to that if I say that my root note this is the first note avatar ruk is not lying then if you want to subscribe like and subscribe for this then this In this way, you subscribe, the same condition for that also means school Shubhendu ESA, here I am going to tell you something old about Tasty because before getting this basic hatred, you should know this much, now test any question subscribe to and subscribe that If you subscribe here means school, then now here and here appointed Note 3, if you are separating then again subscribe home, it means that the war is flying, if I have 19 inside me, do not fall in its left or right, it means its left. Need and right side is only one note in this whole if subscribe this channel subscribe has been appointed this appointment subscribe the channel that youth work like this minimum wages have seen minimum present government coming if maximum notes in gift It is possible that the value of this note will be affordable and can be positive, so you need a question here, now to think about it, now first of all, as you can see, first of all, in this, we Subscribe here means war subscribe once again you subscribe again appointment um so then you will come away from here to office and for this see on time no subscribe see there is nothing but it will go up then your entire travels will be done time Click on the whole and see which element repeats how many times. You came to know that this is our Ghaghra, it is repeating twice here and Padhu, you are able to see this value of note and second, how many times it is repeated. So Meghnad's note is to enter here, subscribe here, we will talk to him about the thing, we will find out some cases that how can we think about this, so the first test is that how can we make a dictionary. The draw was that I told you that if you put this value of this thing in front of it and its value in front of it, then you have to create something like this, how to make it, then you have to think something for it, then create that Meghnad Subscribe that it is in front of that. Brother, what is twice, this little or whatever is here, so now what we will do in this, we can find out the value of the note. Subscribe that in your finaly, we will do it here. If we return then something like this, here we are thinking logically, so the first task is how to make a dictionary by using the method and here you will get a good one. Now to make a dictionary, we will make another one and before that let's talk about something like this. Very like let's say you have the value of only one note then if this is given to you trick root ghee this question subscribe like this then you will come to know that this subscribe also does not mean that this which This means that there is a single note in this, if any one becomes single on August, then we know that it will be my answer and if the time of giving has come before one time, then the answer comes in for, then first of all we have to give a The condition is, now we have to check because whenever I have a single element in the military, I am alone. How will we say that brother, is the life image value of Ruth, not Indian, or the value that is there in the rights of Ruth, if this is also a nun. It is like that, so we will cut off the village that I can search here. Okay, and this means that there will be war and hatred because here we will be appointed function in this village. You are angry with us at home, you are here. Do some code and finally what we have is when you go all the way, after this we will get another one in which in front of each note, how many times it has happened if we have got things like time to time in front of we should subscribe. If you subscribe then there is something for him, a good one, if his left or right, how do you know because you are the first condition but you are worried that it is not that our game is not in the dormitory, if he becomes soft then it means We are the people, we are appointed here, appointed, I am not needed, it means the value of the root, after coming in front of it, put the forest in front of the forest, what is life, here we can say root, the value of the note is okay, remember this. It is good to keep it, so if this is our ghagra, it means appointed on behalf of the appointment, now we turn off the gas and if it is sexual till the appointment of the village, now what will we do in it, if it breaks like this, then how can you It will happen because how will friends change in the village, we will be appointed here we have appointed here, so if you subscribe, what value is there in front of Roadways, in front of the value of Route B, here is the life introduction, you are subscribing to this 212 this is this Appointment on the route soon subscribe this subscribe appoint here a little bit subscribe on our place subscribe that turn off my mode then a if you want to stop making yours then after you when he comes to this note then he will click on his next Amazon subscribe here then click on that means score is good like this ghee and subscribe then we have appointed here first here that the value on the right side of the end root is soft if the girl also gets up and replaces the value on the left side. There is no right side of it means that we have come to the lift note that and Father, we do not need to be ordained, the persons to update the dictionary have come on occasions, okay, what are we here in this ? They will say that brother, please return it, there is ? They will say that brother, please return it, there is ? They will say that brother, please return it, there is a simple condition of Ambedkar Mission, but brother, Kabir resides, okay, we are better than anywhere from here, if we accept that it does not happen, it means that Subscribe to us, do n't subscribe here, friend, it is not like that, click on the subscribe button on both sides, subscribe, it is there is a value in the left subbar of my note, we will call the function, it is ok for the next value. So subscribe now, so first of all, please note that if you have not subscribed, it means that not only one for us to appoint, as usual, if it is not so, then what will we do, subscribe one by one, let me know that in this How many against is every person, every value, how stingy is the meaning of every note, see how much time is there, how many against the note, we subscribe to call this appointed person, as soon as he subscribes, if this happens in front of him, then its value is there, let him have a big one. If you have done so then do it now and subscribe to my channel that brother if there is no side on the left side of our note and note there is no side in it on Thursday next report meaning and below function no call can be made we are back here because to appoint Do subscribe and subscribe to our channel and subscribe to my channel subscribe to the channel if there is something on the left then call the scene function, it is ok for the fruit and at the same time we will do this on the right side of the channel. Subscribe Our function is if we are pregnant then subscribe that as soon as our dictionary is made, what will we do? In this case, the above example was standing in front of them, this is the accused running away, some people have been appointed here. Now what will we do in this Aloe Vera that soon it should be like this, it means that before the scheme, create it through the account, pick all the values ​​in it, that before the scheme, create it through the account, pick all the values ​​in it, that before the scheme, create it through the account, pick all the values ​​in it, do subscribe, then I have added in it the maximum frequency of whatever note will be, my channel subscribe appointment appointed two To to 112 change will go on and check will break, value is there, meaning is to me, maximum free mode of appointment and appointment, definitely subscribe, what will we do from time to time. But Distic is going to make a dictionary of this, he is going to make a dictionary of value trees here, what will be the welfare, what will be our North and I will do their values, what will happen to Akanshu, see this, okay after making this, we will meet and subscribe like this If you keep ghee here then it is very easy subscribe to jhal
Find Mode in Binary Search Tree
find-mode-in-binary-search-tree
Given the `root` of a binary search tree (BST) with duplicates, return _all the [mode(s)](https://en.wikipedia.org/wiki/Mode_(statistics)) (i.e., the most frequently occurred element) in it_. If the tree has more than one mode, return them in **any order**. Assume a BST is defined as follows: * The left subtree of a node contains only nodes with keys **less than or equal to** the node's key. * The right subtree of a node contains only nodes with keys **greater than or equal to** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[1,null,2,2\] **Output:** \[2\] **Example 2:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` **Follow up:** Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
98
1,905
On do hello guys welcome to taste absolutely problem or 120 problem account all islands so let's do the problem and 315 views like what does unique Dhundhi 10111 fan more subscribe to one day some things skin hair and such a dam in this country new Version Lecture With Six Humans That Man's President Electricity Distribution Corporation Effect Incident One Flat to Half Inch Thank You Two All So Much for Peun Subscribe Considered to Be Considered to Give Thanks Oil Android Group Length Right Through Thick And Consider Life But Everything From Water Should Never Be In One Connected To Gallery This One Is Now You Can See The Great Wall To Correspond In To-Do List Everything Is Wall To Correspond In To-Do List Everything Is Wall To Correspond In To-Do List Everything Is One Such A And Is Ireland All The Self In All Forms Are Also Having A Great example of great to 9 Subscribe to channel Also been destroyed but not the least 90 Solved is the definition of what is the island All the self at one of that together One grade for this island One to three brothers problem is clear 999 * First shift search for the island in 999 * First shift search for the island in 999 * First shift search for the island in great to Patna flight history of planning into the rolling took up the recent floods droughts and so and doing a normal in matrix hydration from this is the festival and Jitendra index of the robot is currently at knowledge click here to Dead over the matter into being is representing this point check grade two of its elements one or two and inter function two check inside leadership quality the basic condition president given below witch cylinder price of this water will not do anything about this MOUNTAIN MARTIN LIGHT CONDITION RESTAURANT LATEST WALLA FUNCTION IS MIDDING SIMPLY FANCY Shirt IN THE FUNCTION MANJU LIKE AND LATEST PASS GRADE WIRELESS PASS GRADE 2ND EAR AND WEST SIDE IT AAPKE CHOLESTEROL SE PASS NA 10 LAKH DATE WILL TELL ME IF IT IS IRELAND AND NOT SUPPRESSED Is Mike Hai Initial Loot Kishangarh To Make Kite Flying Squad Ismail Dekh Changes Sentence 2018 Effect Tell Me The Time Products Amendment Bill I Will Not Counted Otherwise I Will Contact You First Form Calling Is Function Us Chapter Is Function Returns Is My Flag Is This Still One Reference Lok Change Zameen Se Dip Ko Interviewer White Account And Finally It Can Be Reduced From Me Quite Vinay Answer Soon Will Declare Account Is Rather Real Me2 Written Test Will Regret Not Have Written So Let's Do Subscribe My Water Residues Digital Copy From This Experiment Amazing At midnight in and tagged election 2014 pimpodi five times different service changes now elected from here to bank 9 david b our simple approach the das problem android types of problems and share and subscribe and after doing this problem solve problems liquid blue subscribe to Withdraw from here not to withdraw 2010 and greater noida to greater noida hansi rog tod sis sundh acid going to consider that will also its values ​​in new consider that will also its values ​​in new consider that will also its values ​​in new delhi on 2days visit will just want to be content with ireland satire return value subscribe to subscribe value in value In The World Is Equal To New Delhi-110021 Problem To Make To Do The Delhi-110021 Problem To Make To Do The Delhi-110021 Problem To Make To Do The Thing You Can Stop U From Within Quiz Time That Ravan Brings Fears Of Applied Zero This Incident Hide Sliders 132 A Prostitute 112 But Being Slightly Different Zip Equal To Zero No What Will Happen After Which You Have Too Very Important Thing You How to Make the Current Person Emphasize Her Inter College But You Don't See the Problem of Traversing That Basically Posted in The World 102 You Will Never Know One Will Dare Attack You Robert Winners Never Okay This Love Rings One And What Will Happen And You Will Call You Back You Will Call Like Sexual College Life Never Again And Will Contact You Will Enter Into Infinity Kar Save Loop Which Is Not Right For Adding That You Have To Back Tracking Somvanshi Atray Oriental This To Make Sure Battery Swar Important Contact On This Tube White Writing And Make Kids That Person Don't Finally Bigg Boss Instruct Indore Developed Falls Again And Again Swar For Very Important For International Decide Question Setting The Point Will Avoid A Reminder To Make a Call to the Self 2012 Subscribe Grade One Based Media Grade One Grade Two ID and Black Pepper Oil Increase Why One Should Go Into the Next Few Days Will Remember Say My Flight Building Same Novel Based on Which I'm Going to Call My Next Labor Smilex Naval This I Will Decrease I Will Go Up Of An Am Going To Sleep Everything And See What Is Another Thing Another Dependent Is Veer Want To Increase The Index Of China And Don't Forget To Subscribe To This Video Channel I Will Add One To This Problem Daughter Electronic Voting Switch Off
Count Sub Islands
design-authentication-manager
You are given two `m x n` binary matrices `grid1` and `grid2` containing only `0`'s (representing water) and `1`'s (representing land). An **island** is a group of `1`'s connected **4-directionally** (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in `grid2` is considered a **sub-island** if there is an island in `grid1` that contains **all** the cells that make up **this** island in `grid2`. Return the _**number** of islands in_ `grid2` _that are considered **sub-islands**_. **Example 1:** **Input:** grid1 = \[\[1,1,1,0,0\],\[0,1,1,1,1\],\[0,0,0,0,0\],\[1,0,0,0,0\],\[1,1,0,1,1\]\], grid2 = \[\[1,1,1,0,0\],\[0,0,1,1,1\],\[0,1,0,0,0\],\[1,0,1,1,0\],\[0,1,0,1,0\]\] **Output:** 3 **Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands. **Example 2:** **Input:** grid1 = \[\[1,0,1,0,1\],\[1,1,1,1,1\],\[0,0,0,0,0\],\[1,1,1,1,1\],\[1,0,1,0,1\]\], grid2 = \[\[0,0,0,0,0\],\[1,1,1,1,1\],\[0,1,0,1,0\],\[0,1,0,1,0\],\[1,0,0,0,1\]\] **Output:** 2 **Explanation:** In the picture above, the grid on the left is grid1 and the grid on the right is grid2. The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands. **Constraints:** * `m == grid1.length == grid2.length` * `n == grid1[i].length == grid2[i].length` * `1 <= m, n <= 500` * `grid1[i][j]` and `grid2[i][j]` are either `0` or `1`.
Using a map, track the expiry times of the tokens. When generating a new token, add it to the map with its expiry time. When renewing a token, check if it's on the map and has not expired yet. If so, update its expiry time. To count unexpired tokens, iterate on the map and check for each token if it's not expired yet.
Hash Table,Design
Medium
null
938
hey welcome back to another lady called problem and today we are going to solve an easy problem called range some of BSC is binary search trees and last time I made a video about validating at my her search tree so you know if you guys are not familiar with my newsletter you can read more about it here so it's basically like a tree which has an additional property that the values on the left sub trees are smaller than the root and the values on the right sub trees are larger than the root for example in this case 8 is all 3 1 6 4 &amp; example in this case 8 is all 3 1 6 4 &amp; example in this case 8 is all 3 1 6 4 &amp; 7 here this is my left sub tree which is smaller than 8 and all these values 10 14 and 20 are greater than 8 so what makes this problem interesting is because here we have it's a little bit tricky it's easy problem but it's a little bit tricky because of the range so when you're solving the problems of treating problems it's a recursive data structure so try whenever you ask some questions try solving using recursion is one of the ways to solve problems when it comes to trees and think about what is going to end because it's recursion you have to think about what is going to be my base case that's first the second thing you want to be thinking about is what a single node is going to do so for example in this case the question given the root node of a binary search tree return the sum of values of all nodes with value between l and r inclusive okay so let's say here Ln R is 15 okay Ln R is 15 so let's look at a tree example here so if you look at this tree this know you don't think about any node don't think about what is this left subtree is doing what is this right subtree so just focus on one node because one function call always focuses on one single node and then what we do is because it's a recursion we passed States we pass States to each and every subtree think about this the single node so I know this aid for example here is in the range I can say that okay I can take aide and I can calculate the song and I can do that for each and every note so always focus on one note what it's going to do and then you can think about what I need to do after that okay so this is important thing about recursion allows you to abstract and focus on one single note and that's also one of the reasons why you should if you haven't been asked and the default way of solving problems should be when it comes to traces using recursion unless until you're attending an interview and if they say that okay can you solve a teasing nitration you can you have to nitration you need to maintain the state you need to really use additional storage which is sometimes can be tricky when you're learning so the default way of solving problems is using recursion so in an interview scenario the important thing is about you understanding the problem and logically solving it that's the priority number one don't try to pre you know pre optimize things recursion has its recursion the call stack uses more storage more space and don't go into too many details if you're three minutes all right we try recursion is one of the best ways to do it only unless I know they tell you that okay if you solve it using recursion then they tell you to optimize it more than you can use a night raider method I traitor method is generally much more faster than recursion because there's no call callback stacks and all those you don't have to maintain but recursion allows you to pass state that's one of the biggest advantage of recursion iteration you need to maintain that state and also recursion allows you to go you know allows you to use methods like backtracking so you can go to that you can go to a state and then come back from that state so that is one of the few advantages so we'll see solve those types of problems there you go to a state and then come back from it okay so that's one of the advantages of recursion so let's solve this problem using and let's see how to do this okay so because I have this all this isn't recursion one of the best ways is to create a function which you can call recursively or a method okay so I'm gonna call this function this is left and right are my range and I can just change this to be more descriptive okay so let's call this function and then that's my tool initially the total is I need to return a sum so it's going to be zero so what if my note I don't have any notes so it's simple that's gonna be my basis at some point because I'm using recursion at some point I will return I go to a node I will go to a nil node so what should happen when I go to Anila I just retired so okay now in normal scenario for example in this know what am I just need to focus on one node now I know the value of this node needs to be in the range that has been given to me let's focus on this node eight so let's say if I ate is in the range so I need to check that range okay so there's my if my last and it's inclusive so right if it's in the range the value of that node has a value and it is in the range that I just added okay now because it's in the range then this is a binary search tree because I know that it isn't arranged I need to think like this so this value is in the range but I need you now there for this value is in the center I know the left sub trees might contain values it satisfies this condition okay and the right sub tree might satisfy values between this range okay so I want them also so to do that I need to recursively call so what should i do is i need to recursively call the left subtree on the right subtree so what's gonna happen is that this total is dominated this node and then i go to the left node and then it's gonna mutate little when returned back the total value so here in passing estate this function has a different state and this called this function this method when it was called has a different state and this has a different state I went back there it allows me to abstract focus on that subtree okay and then I return back so it doesn't matter if the tree is very big or large it doesn't matter because this is recursion I just need to focus on a part of a subtree I don't have to focus on the full tree I can go from one sub tree to the other sub tree okay so that's one of the advantages of recursion and I pass a state total and then it returns me the tool as I have specified here so okay now I need to go to the right sub tree to focus on values between this range okay so because this a binary search tree I know that this right sub-tree me have know that this right sub-tree me have know that this right sub-tree me have the has values between this and this node value and the right range that has been given to me okay so this is good now what I just did here is that first thing I focused on one single node here and as I'm checking whether that node contains it the value that it contains is in the range is in the given range if the gameand range then I just add it to my total okay now I need to focus on this left range this range from left to all the values to the node are value here I need to focus on that and then I have to do the same thing for the right subtrees which has values between no value hold to this between this range okay now what if I reach a subtree and it doesn't have the value that is let's look at this example here so here the range is given to me is 7 and 15 let's take an example here so when I go here 3 doesn't satisfy what 7 is here okay so that's a problem because it's still in the range because 7 and 15 if you take this example this is 3 I go to this node it doesn't have the value of 7 so I know that I have to go till this node then this includes that value so I just counted eight and the next value I want to count is 7 because it's in the range and then next value will be 10 14 and 15 for eggs 4 for this if you consider that tree that was specified in the wikipedia this in the you're passing this range okay so what if that value then what happens is this condition is getting false okay so when does this condition gets false this range gets false when this node value is greater than the left okay then I need to go to its then I need to go to the right okay because I cannot go to the left because that left has already has a larger value okay so I need to do here is if my note Davao has a less than the left if I go to the left and I see that my value on the left this note has it has to be in between this range but it is smaller than this left range then I need to go to the right so I just call the function I go to the right sub-tree out this of this note I right sub-tree out this of this note I right sub-tree out this of this note I don't need to go to the left sub-tree don't need to go to the left sub-tree don't need to go to the left sub-tree here because if I go to the left sub-tree obviously the value because sub-tree obviously the value because sub-tree obviously the value because it's a minor so sorry it'll be even more smaller than the current node dot val okay so and then it changes the value of this total and returns back the total value so and I do the same thing for this range of that node our value is lesser than is not equal is not less than right then it has to be supposed to be greater than if it's greater than I have to go to its left subtree and I just so all these functions are mutating the value of this total updating the value here so total and this total gets updated and yeah and so on I just returned over here let's run this code oh yeah cool it worked now let's see if it passes all the test cases yeah it does so one of the things you have to keep in mind when you're solving three problems is focus on one of ways if you are using tree solving three problems or one of the basis focus on what a single node is going to do don't focus at a whole tree it might get confusing and you might you know get yourself confused and you might say okay you might that might ruin your interview you know so focus on one single node ask yourself this question what is the one single node is going to then focus on sub trees always focus on a small part of a tree what its gonna do and one of the ways to solve three problems is using recursion allows you to pass States which you can later use for your advantage for example here I passed the state total whatever the value of total is I update it and I pass it back again and I've returned back the updated value of trouble so I did that again for when I call this node right when I went to the right sub-tree I did again passed to the right sub-tree I did again passed to the right sub-tree I did again passed the state so that is one of the few advantages of but it's very easy advantage of recursion and it's very easy to you know convert a recursive function calls into an I traded way so sometimes the in during interview you might be asked try solving you know take a recursion twice all it's awesome treat problems using recursion and then try to solve them using I trade a method so in niterói two methods are generally more if efficient but there's a lot more code you have to write okay so I guess this video helps thank you for watching and like and do subscribe
Range Sum of BST
numbers-at-most-n-given-digit-set
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
Array,Math,Binary Search,Dynamic Programming
Hard
null
1,743
hello everyone so welcome back to late code 1743 problem so the problem is there is an integer arena that consists of n unique elements but you have forgotten it however you do remember every pair of patterns in the element in the line so this is the problem statement so basically what they are trying to say is suppose it's the one two three four in the avenge and you have forgotten this heading but what you have to do is this because these two are at the center okay three comma four so you have given this array and you have to find out is so we will move uh right-hand side uh right-hand side uh right-hand side and for each value we are going to store now has mapped so the hash map contains the value like this so for the zeroth index he has map of it to element plus one and for the one element it is again for the one number index for this index we are going to create before now for this index we are going to add and you will notice that uh you there are two keys which contains a value one or the size of the adding is one so here it's one and four so we will use dfs after that so let's try to put so um um is and okay after creating the hashmap i am going to check we will find each key value size is one so doing this f start for each so i will start with so if you go through the dfs problem so uh so um so try to underscore diamonds missing so yeah so one more thing you have to so you have to take the length of the existing pair and plus one let's put it will start might not let me see once yeah so this is the question not the answer yeah so it's fast and it's faster than 68.7 68.7 68.7 so thank you for watching this video have a nice day
Restore the Array From Adjacent Pairs
count-substrings-that-differ-by-one-character
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`. It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**. Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_. **Example 1:** **Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\] **Output:** \[1,2,3,4\] **Explanation:** This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs\[i\] may not be in left-to-right order. **Example 2:** **Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\] **Output:** \[-2,4,1,-3\] **Explanation:** There can be negative numbers. Another solution is \[-3,1,4,-2\], which would also be accepted. **Example 3:** **Input:** adjacentPairs = \[\[100000,-100000\]\] **Output:** \[100000,-100000\] **Constraints:** * `nums.length == n` * `adjacentPairs.length == n - 1` * `adjacentPairs[i].length == 2` * `2 <= n <= 105` * `-105 <= nums[i], ui, vi <= 105` * There exists some `nums` that has `adjacentPairs` as its pairs.
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Hash Table,String,Dynamic Programming
Medium
2256
1,961
hi friends welcome back to the channel uh today we are going to solve lead code problem 1961 check if string is a prefix of array so given a string is an array of string words determine whether s is a prefix string of words a string s is a prefix string of words if s can be made by concatenating the first k string inwards for some positive k no larger than words length so return true if s is a prefix string or return false otherwise so if you look at the example first then we can form this i love lead code prefix by concatenating the first three words in the array i love and lead code so we can return true here and if you look at the second example uh here we the iris starts with word apple so we cannot form i love lead code prefix string so um here is the solution that i uh implemented so i just use the string builder here and i will just keep appending the word from the words array to the string builder and keep checking it against the string s that is given to us whether it's a prefix or not if it finds it if it finds after concatenating a string as a prefix then it will return true otherwise it will return false so i use like a two test cases so the first one is the given one i love lead code and the second one i am just using i love lead co so the lead co is not there in the array so it will return as a false so let's give it a shot right now yeah so it's accepted and this solution is also accepted with 90 percent 95 percent of uh run time and 96 percent faster than the others for memory usage so thanks for watching uh consider subscribing to the channel and give it a like for the video if you like this solution thank you
Check If String Is a Prefix of Array
maximum-ice-cream-bars
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`. A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`. Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_. **Example 1:** **Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\] **Output:** true **Explanation:** s can be made by concatenating "i ", "love ", and "leetcode " together. **Example 2:** **Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\] **Output:** false **Explanation:** It is impossible to make s using a prefix of arr. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `1 <= s.length <= 1000` * `words[i]` and `s` consist of only lowercase English letters.
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
Array,Greedy,Sorting
Medium
null
43
hey everyone welcome back and let's write some more neat code today so today let's solve the problem multiply strings so we're given two non-negative integers so we're given two non-negative integers so we're given two non-negative integers num1 and num2 but these could be extremely large numbers and because of that these integers are going to be represented as strings as you can see down below and the good thing is that these integers are always going to be either positive or they could be zero and we want to just take these two numbers multiply them together get the product and then return that product as a string and we're not allowed to you know actually do this with integers right we can't just convert these two strings to integers we actually want to do this with strings themselves because you know there's no guaranteed that an integer this large could actually fit into a 32-bit or a 64-bit integer and into a 32-bit or a 64-bit integer and into a 32-bit or a 64-bit integer and they don't want us to use any kind of big integer library so there's going to be two parts to this problem the first part is going to be to remember how you actually multiply two numbers in the first place you probably learned it in elementary school but you may have forgotten so that's the first thing we need to figure out how to actually multiply two numbers and the next part is how can we actually take that idea and then translate it into code in a readable and you know somewhat concise way and that's going to be the second part that we have to figure out and just to go through an example real quick you can see 123 456 you multiply those two together you get this value and we are returning it as a string so let's go back to elementary school how can we take two numbers like these and multiply them together in a formulaic way that we can translate into an algorithm well remember we usually first start with the ones place over here right and then we just take this value and then multiply it by three multiply it by two and multiply it by you know the more significant digit and then we add those three together you know we also do have a carry which is something we're gonna have to keep track of and you can kind of tell that you know if we take six multiply it by these three integers then we're gonna go to four we're gonna go to five multiply it by these three integers then we're gonna go to four multiply it by these three integers that's something that could probably be translated into a nested for loop right so we're kind of learning that as we go but let's just start with this so six times three that's going to be 18 right but normally you know we just take the first digit eight put it over here in this ones place then we take the one and carry it right so the one is going to go up here it's going to be added to whatever goes down here but in the code we're actually going to be putting that one here immediately because you know when we're keeping track of a carry we could keep track of it over here like in a single variable but it's kind of just easier to just put it here because we know it's going to be added with whatever next value that we put over here so next we're going to look at 6 multiplied by 2 that's going to be 12 right so we're going to take 12 add it with the carry right that's going to give us 13 in this position right so we have a 3 digit here and we have the 1 which is going to be the carry in the next position now notice how when we were multiplying these three together we put the digit in the first spot but when we multiply these two together we put the digit in the next spot and when you multiply these two together we're gonna put the digit over here so basically the way you know how we decide where we actually put the digit when we multiply two digits together is basically going to be the sum of the indices of these two so basically consider this is zero this is one this is two these are the indices uh if we're multiplying these two together we're gonna put it but we're gonna put the digit in the zero position if we multiply these two together we're gonna take zero plus one we're gonna put it in the one position over here now if we multiplied these two values together we'd say one plus one you know these two multiplied together we'd put the digit over here because this is the two spot i know that's kind of tricky to you know recognize immediately but i think it makes sense because you know when we're multiplying six by one we're not actually multiplying six by one we're multiplying six by a hundred right because this one's place is in the hundreds place so that's kind of the intuition behind that but yes now we take six multiply it by one we get a six right so this is where we would put the six we clearly have a carry over here so we're gonna actually put a seven over here so far this is our result but we only went through this six digit next we want to go through this five digit and multiply it by these three values so we take 5 multiplied by 3 we get 15 right the 15 is going to go in this spot over here right but of course we have a carry one over here so what are we gonna do well we're gonna take these add them together and we're gonna take these add them together right so we're gonna get an 8 over here and we're going to get an 8 over here next we're going to take 5 and multiply it by 2 and the position that's going to go in is going to be in this position right because you know that's just kind of the math of how these indexes add up so 5 times 2 is going to be 10 so we put a 10 here right 0 plus 8 that's just going to stay 8 but that one carry is gonna go over here in this position notice how the result when you multiply two numbers the number of digits in the output could be greater than the number of digits in the input now what's the maximum number of digits the output could even be well if we took two numbers suppose 99 multiplied by 99 right these are kind of the biggest integers we could have for two digits each how big would the output be well the output would be four digits i think it'd be something like this i'm not 100 sure on that but basically you can see that you know if we have two digits multiplied by two digits the max the output could be is the sum of the digits of each of these right so if we have an example like this one three digits multiplied by three digits we could have an output of up to six digits but it might it could be less than that right for example you know you take 10 multiplied by 10 we just get a three digit number 100 right even though two plus two is four digits this is the output happens to be three digits so it's basically going to be less than or equal to the sum of the number of digits but okay so where did we leave off we were gonna now multiply five by this one and then put it in this digit position because this is that index two this is at index one so the output is going to be at index three over here right these are kind of the indexes of the output so five times one is just going to be five so we take a five here add it with the one that's already there so we're going to get a 6 in this position by the way notice how when we count the indices where you know this is 0 this is 1 this is 2. so basically the integers themselves we're going to be iterating through them in reverse order similarly we're going to be building our output in reverse order as well and then at the end we're gonna take this and reverse it okay so now we took five multiplied it by all three of these digits so we're done with five lastly we're going to take four and multiply it by all three of these so four times three is going to be 12 right we're going to put a 12 here you know we take these two add them together we're gonna get a zero in this spot right a zero and we had a six here we had a one here now we're gonna since we got a zero here we're going to have another one carry in this position so when we actually add these together we're now going to have an 8 in this spot so we took 4 multiplied it by 3 now take 4 multiply it by 2 which is going to be 8 and we're going to put that a in this position because that's how the math for these indexes adds up so 8 plus 8 is going to give us a 6 so we can put a 6 here but of course we're going to have a carry right 8 plus 8 is 16 so this is what we have we had to put that carry over here so we took 4 multiplied it by 2 lastly we're going to take 4 multiply it by 1 and then put it in this spot so 4 plus 1 is or 4 times 1 is 4 so we take a four add it here add it with one we get a result of five and then we're done right because we took four multiplied it by this and multiplied it by this we finished our nested for loop and this is the result that we got and as you can double check that matches exactly with the output that they expected so basically how i ran through it is similar to exactly how we're going to code this up the only difference is we're going to pre-create we're going to pre-create we're going to pre-create we're going to pre-allocate the result array in this pre-allocate the result array in this pre-allocate the result array in this case we have three digits by three digits so we're gonna have an output array and we're not gonna keep track of it in terms of strings even though the input is given to us in strings we're gonna build the output as an array just because it's a little bit easier i think you could do it with a string but then we'd have to do a lot of conversions you know converting a character to an integer and vice versa doing it as an array is a little bit easier and then at the end we can take the array and then convert it back into a string you know pretty easily so that's kind of what we're going to do and like i mentioned we're going to start at the right position of each string at the right you know in reverse order we're going to iterate through the input strings in reverse order and when we build the output you know this is kind of the order of the value we're gonna build it opposite we're gonna put the eight here because this is index zero we're gonna put another eight here zero six five right so as you can see this is basically built in reverse order to this so we're going to do that but then at the end we can take this array reverse it and then convert into a string which is going to look something like this and then we can return the string in the format that they actually wanted and the last thing is when we're taking two digits and multiplying them together consider if we had the largest digits consider if these digits were actually nine and nine right we're only multiplying one digit by one digit so the max that this could possibly be is a two digit value in this case nine by nine is going to be 81. so when we take when we're always going to want the ones place right to actually put it in this spot right so when we take a value like 81 we can mod it by 10 to get the ones place which will give us 1 and we can divide it by 10 to get the carry right so if we divide this by 10 we'll get 8 because it always rounds down in most programming languages right so that's how we're going to do the math on that we're going to put the 1 here then we're going to take the carry put it in the next spot right add it to the next spot and in terms of time complexity the since we're going to be doing a nested loop it's basically going to be let's say n times m where n is the number of digits in the first value and m is the number of digits in the second value that's overall going to be the time complexity i think the memory complexity is going to be something like n plus m because we're going to be using an additional array just to have all of the output digits inside of it then convert it to a string at the end with that being said we can go ahead and dive into the code so now let's finally write the code and the first thing i want to do before actually dive into the actual algorithm is basically uh if either of these digits or these numbers happens to be zero then we can just return zero itself right but then we don't actually have to execute our code so one way in python i can check that is if this is in the array with two values num one or num2 basically i'm checking if either of these values happens to be zero in which case we can return zero right any value multiplied by zero equals zero the other thing is allocating that array right so i'm going to allocate an array of all zeros multiplied uh or basically the length of this is just going to be the length of num1 plus the length of num2 and as i mentioned we're going to be iterating through both numbers in reverse order so before i actually iterate through them let me just reverse each of them and this is basically how you reverse in python i'm sure you can do it in your own language of choice and we're going to iterate through both of these keeping track of the indices right because we know that the index is going to be useful for some of the math that we're going to have to do so for i1 in range of the length of num1 so i1 is going to be the pointer for num1 and i2 is going to be the pointer for num2 now we want the digit right so we're going to take the numbers or the digits from each number and then multiply them together we know the digit itself though could be a two digit value so let's keep that in mind so the digit from num1 multiplied by the digit from num2 and so where exactly are we gonna store this digit well you might remember i mentioned in the drawing explanation we're going to take the indices i1 add it with i2 which is going to tell us what position to put this in the output result so we can then store this digit there but remember we have to mod this digit by 10 before we actually store it here and we might not just be storing it there might have already been a carry in this position so we're going to add whatever this one's place is to whatever is you know this target position so that's where we're gonna add the ones place digit now we might have a carry the carry might be zero or it might not be zero either way we're going to put it in the i you know the position plus one right so just the next position over is where we're going to put the carry value so we can add the carry value to this position we can calculate the carry value by taking digit dividing it by 10. and the last thing is i didn't mention but suppose we were given two values 10 times 10 in this case we would have our output end up being something like zero a hundred the reason we have a leading zero is basically because you know when we allocated the output array we took the digits two digits here so we would have a four digit result so we basically want to get rid of any leading zeros which is something we can do pretty easily so before we try to get rid of the leading zeros let me actually reverse this result so result is going to be set to itself except reversed and the beginning pointer is going to be set at the beginning of this result and we're going to keep incrementing beginning while it happens to be zero so while beginning is less than the length of the result and the value in the beginning position happens to be equal to zero basically while we have leading zeros we're going to increment our beginning pointer until the point that we don't have any leading zeros anymore now we do have an array of integers not an array of strings so in python at least there's a way that we can convert this we can use a map function and basically convert every single a value in this result from the beginning pointer all since we calculated the beginning point we're just going to be you know we're basically removing the leading zeros by doing this uh operation starting basically taking the sub array starting at the beginning pointer and we're converting each integer to a string at least that's how we're doing this in python i'm sure you could write out the two lines of code that it would take in other languages so once we convert the array to an array of strings then all we have to do is just join the strings together and python you can do it something like this just join it with an empty string and one thing i forgot is first of all i named this num i just changed it to num2 and since these are actually you know characters we have to convert them to integers before we can multiply them that's something i usually forget i don't know if you guys forget that as well but let me actually convert them to integers first and actually one other thing that i forgot and this is actually a good example what if we had a let's say we had a two in the ones place and then two this two we're adding a digit of we had an eight and we're adding a digit of two right so you know that's kind of what i'm doing with this line of code in that case we would have a two digit value here right a ten so we'd have to take this whatever stored here and then mod that or rather divide that by ten to see if we have a carry resulting from two ones place digits that's something we were handling in the drawing picture but i forgot about that when we were actually writing out the code so the way we can remedy that is basically when we're going here uh we're gonna take just the digit itself and add it to this position right the digit could be a one digit value like two or it could be a two digit value like 12 right either way we're adding them together and then it could be possible we have a two digit value stored here right so one thing we'd want to do if we did have a two digit value and stored it here we would want to take it and mod it by 10 right so basically set this equal to itself but modded by 10 we can do that pretty easily right so we're just taking it modding it by 10. if it just happened to be a single digit value like 2 then it would remain the same if it was a 2 digit value like 12 then we'd get the ones place and put it here but notice how we're doing this after we're doing this line because this line of code actually is going to be similar because before we do that we have to take the carry that could be stored here right like i said it could be a two digit value like it could be something like a 12 in which case we'd want to take this value divide it by 10 and then add it to the next position over right so we're taking the carry adding it to the next position we can get the carry by taking this two digit value dividing it by 10 and then adding it to the next position i know this might have made things a little bit more confusing so sorry about that but you know if you kind of do go through these three lines of code run it on an example on your own you'll see that it's pretty much exactly what i was doing in the drawing explanation so as you can see this code does work so this is the entire code i hope that this was helpful it's definitely not super easy to get here but i do think being able to understand you know how multiplication works is a very good first step in being able to tackle this problem i think using an array also makes things a lot easier so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
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
1,419
Hello Friends Producers Question From Heat To Beat Contest 180 Minimum Number Of From English Video give From Which Represents Combination Of Strength From Subscribe To My Channel To Hai To Aadmi Logic West Indies Questions Page Will Probe And Super Soft Can Benefit from another subscribe our Channel subscribe this note miles 300 entertainment and this cold not get 100 subscribe And subscribe Video subscribe si hai ki and allied youth promise parents set speed on maximum keep it on low that 10th September is on Thursday September 9 is Danish number So you have clicked on a picture volume Vikram, it is absolutely fine, enter problem solved in this position is on 132 test one increment C Virvar district on this one subscribe button click on this front side 2050 new I just two that ahead Bittu On the orders of That time This thing is the same time A nice pick up Sid Love On Hi Hoge Na How Can I Tell Speakers and Electronics Already Subscribe 90 Subscribe To I Travel Deeply Drowned After Traveling In Maximum On To Id 2nd Test Series Page 4 Tags Page 5 Hai MP3 Episode Number Incident Avoid A 208 That I Late Science Present Lokpal Bill Answer Is This Cream And Middle-Sized Answer Is This Cream And Middle-Sized Answer Is This Cream And Middle-Sized Farms New Delhi Aap Record Yeh Tractors And Accounts To Aap Pet String Doon Tractor Have To Wish Birthday Ki handi a hotspot c 10000 hai coffee date do ki aap ki a main aapke show ra feed reader in more copy-paste posts and share and subscribe to ki shahrukh khansark death record electronics and smog and improvements and subscribe to MP3 copy like a kar do mein 3000 1000 for 10th according to idli entries 2004 to pocket vest chapter 17 entry is equipped Ajay has a quarter inch pick up Sulabh started but this project comes in condition and is it 1000 hu is the introduction of point commission Equal to zero and yo vansh yo vansh yo vansh jo woh time change it's all the gift 13000 ka one person record seat to o ki and main aa jaane phir is great and you know it means android points 102 hai yeh set reminder kar do They are the same or they are torrent a president 0 that roads are built in the construction of roads, vitamin zero is done, dinner is satisfied with the elections and this is tomato this look business Subscribe Previous Song You to Surat Ko Band Kar Do Main Mere Yoga 50 ko turn on e-mail profit vitamin e hua hai ki picture aani minus one so let's check whatsapp 19 minutes ago 116 send photo of polish and yagnik MP3 in chat a and this is the reason school hua hai looter hai a simple fact paani Add submit effective to-do list feel free to contact that to-do list feel free to contact that to-do list feel free to contact that 10.01 assistant
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,048
hey what's up guys uh this is chung here so today at today's daily challenge problem number 1048 longest string chain right so you're given like a list of words right and then and this it defines like a word one is a predecessor of word two you know even only if we can add exactly one letter into word one to make it equal to word two right for example abc is a predecessor of a b a c because we add a uh between the b and c okay and then our task is to find like the longest possible chain of sequence in a given word list basically a change that you know each of the word is a is the predecessor of the next one right and we just need to return the longest the length for example right we have this one here you know the longest chain we have is like is four because we have a b d a and b bdca right and that's it so and the constraint is like it's like this it's not very strict constraints only uh 1000 words at most and each word is only at most a 16 length so you know actually the moment i saw this problem you know the first thing stroke came to my mind was like this one was it's very similar to that very classic problem it's called lis right which represents for the uh the longest increasing subsequence right where in this problem you are given like a bunch of numbers integers right and you need to find the longest increasing subsequence among those so this one is similar basically you know um because you know the basic since the chain could end up end at any location right that's why you know we have to try all the possible scenarios you know but in order to try that you know first thing first we have to sort it so that we can only i mean we'll look back because you know if we don't sort it you know if the current one if the word one is longer than the word two right then obviously there's no way uh this word one can be a predecessor because we need to add like one letter to the predecessor so after sorting this these awards here you know so what's left basically we can uh we can use the dp you know so the dpi here so this one means what the dpi means that you know ending with the ice world what's the longest chain of predecessor we can get so a little bit about this dp here you know so the reason we can use dp for this problem is that you know let's say we have a dp we have a uh i word so we have a word i here right word i here and then before the word i let's say we have word j1 and the word j2 right so if we know right you if we know the j the j2 is a predecessor of the current i word it means that you know we can basically create a bridge right or change this word in this problem from the j2 to i right so if we know the dp of j2 here right so if we know this one if we know by the end of this j2 if we can like make if the longest chain at the end by the end of this j2 here is let's say for example if this one is two then we know if we build after building the bridge from j2 to i the longest one we can get the long number i mean the bridge so the length of the chain we can get from for this path is three because we're gonna add a three add one here right so similar from j1 here right so if we have another one if j1 is also predecessor of the i here we can also build uh like a bridge here right so let's say this one the dp of this one is three that's why you know we'll have like three here i will have four here and we always get the longest one so and the reason we can use dp here is that because we can break this problem into a smaller problem basically after we're getting the longest one after previously of the previous word here you know we can use that to calculate the current one because the current one you know the current one will not affect the previous one right as long as if this one is fixed but if the longest one is fixed and then we can certainly use that to calculate the kernel and once we finish calculating current one we can also use this one to calculate the later one right and that's our log that's our logic right so at each of the eyes i worked here we go back to check all the previous words right if any word if any previous words is a predecessor of the current one then we'll basically we'll try to update the current one with the previous is that words dp value right so in the end we can get the longest one here and this one i this one is exactly the same logic as our s which is like this using the same logic here the only difference for the current for this one is that you know in our eyes we can simply compare the value of the two integers to determine if you can if we can build a bridge an edge right but for this one we have to create like hyper functions to determine if uh if this one is a predecessor of the current one right so um i guess we can just start implementing that you know but uh but the one we are implementing here it's not the fastest one uh we start from this one because this one is like the most uh solution came to my mind and after this one we're gonna implement like i improve this uh this solution into a better one so first let's define the uh the hyper functions as card it's predecessor right predecessor so we have a word one and word two right i mean there they're like out of many ways you can define this uh implement this hyperpurpose i'm just showing you guys the one i have here and it's a little bit long here so and first we check if the n1 plus 1 does not equal to n2 right so if the diff is not 1 then we simply return false otherwise i have a find the div equals to false and then we have i dot j dot i equals to j equals zero right we need two pointers to loop through to compare the lighters one by one right so while i smaller than one and j is smaller than n2 so we check if the y uh word1i is not equals to word to j right then we check if the if we have already find the difference before then it means that false right elsewhat else we increase the j plus one and then we mark this fine difference equals to true so here so if we if this is the first time we find the difference right we simply just we just uh increase we just add like one letter to the first word to match with the i mean this is j that's why we only increase the j here and else right so else uh we increase the pointers for both okay and if everything works fine return true that's it all right so that's the helper functions and then like i said we're gonna sort this word first right by the length right so which means we're going to leave neither like lambda function x dot and then x is going to be a length of x right now we need the enough length of words okay then we get dp right to store the uh the value right at each index here and we start from one because uh a word itself can at least form a chain with length one okay and then we just look through each word right and then for each word we go back to check all the words if the predecessor right predecessor it's predecessor of words j of words i right and then we update the current dp right dpi is going to be the max of dp i and the dp j plus one right that's it and then in the end we simply return the max of dp so here you know this is because you know because the chain can end at any low at any index that's why we have to check all the dp's remember so the dp we're defining here is that you know ending at the current one right the chain ends at this index that's why we have to check all the dp here okay let's run it okay accept it let's run it so cool it passed right but as you guys can see this one only beats ten percent the reason being is the time complexity because so we have an acid photo here you know that's why time complexity for this one is like n square right let's define let's see the length is n and the words length is m so which means uh this time complex is n squared times m because the predecessor we have two pointers and right we look through the entire world and yeah that's why this one is it's a little bit slower you know the reason being is we have n square on this along on this end here right so what can we improve that actually there's like a better solution which is you know since you know this word is much smaller the length of what is much smaller than the length of the words list so instead of looping through looping back each word here you know what we can do is that you know we can try to remove delete each letter on the current word and then we get a new word right and then we see we just need to check if the new word exists in the words we have seen so far if it is then we know okay we know we can build like a similarly we can build the ad from that word to the current one right yeah so which means uh let's do that right so like i said instead of looping through all the previous words we can just loop through try to remove each letter from the current word so the current word is going to be the words of i here right and then oh and you know with the new word here you know we're gonna have like we will need to have like the word as a key to store the uh the length of the chain ending with that word because here we're using an index here but here we're using a word which means uh we can change this one from a list into a dictionary okay so basically for each of the word here you know the current max number is going to be one right because we don't have a default value for this so this one means the same similarly because the word itself can be a chain right and then for j in range of length of word okay we try to remove the current json letter so the new word is going to be a word of j plus one right and then if the new if the own word is in dp right because you know since we're processing the words from left to right so currently so at this line here you know the words in dp are the words on the left of the kernel word right which is the word which is smaller has smaller length of the current one so if this new word is in the dp which means that you know this new word exists in the previous word then we can just uh build it like an edge right bridge so which means we can update the current max uh with that from that word from the new from that n word it's going to be current max of the dp of n word plus one right and then here we just update that word which is the max right so that's it and here since we're using like a dictionary which into two values right and that's it if i run this code here accept it and if i run it again so boom right so now it's much faster only 100 milliseconds and the reason is also very obvious because now the time complexity is we have n here right and then here we have photo but this time the for loop is what form is m the length of the word and in each of the for the loop here we concatenate the word which is another amp that's why this one is n times m square which is much faster than the previous one right cool i think that's it right i mean it's very classic like db ios problem a little bit of variation and yeah thank you for watching this video guys and stay tuned see you guys soon bye
Longest String Chain
clumsy-factorial
You are given an array of `words` where each word consists of lowercase English letters. `wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`. * For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`. A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`. Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`. **Example 1:** **Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\] **Output:** 4 **Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\]. **Example 2:** **Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\] **Output:** 5 **Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\]. **Example 3:** **Input:** words = \[ "abcd ", "dbqca "\] **Output:** 1 **Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains. \[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed. **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 16` * `words[i]` only consists of lowercase English letters.
null
Math,Stack,Simulation
Medium
null
952
Hello Various Welcome 2020 - Have you moved to Mumbai Hello Various Welcome 2020 - Have you moved to Mumbai Hello Various Welcome 2020 - Have you moved to Mumbai Professor Vinod Great Time with Box Today's Question is Largest Company in Size by Common Factor in this Question Near Giddy to Identify the Price of the Largest Connected Components in Craft How can they Identify Connected Components After Food 12 Minutes Our Connected With This Is Well All Is Well Connected With Other Component With Example Solar Dryer And Form Group The First Elements 2850 The Connected With Each Other Backward G Of Density Of 20 Two Elements And Connected With Each Other Backward 3:00 pm of Connected With Each Other Backward 3:00 pm of Connected With Each Other Backward 3:00 pm of 963 original 99999999 largest company in size by common factor leetcode 952 hard level questions only for 20 unaware of union find approach for 200 hours with the crisis in to the medium ticket 493332 video sex free 352 indirect relationship with each other result of 203 element form single-group result of 203 element form single-group result of 203 element form single-group proceeded next p77 connected with any three elements 2369 notes from different island 44236 connected with all its not support island to lucknow by next pcs 21217 interesting case new element makes a bridge between diwali and how check the top abcd of countries Which Are Taken Out Office Bluetooth Connected With Each Other 133 Result Also Connected With Each Other Word Of The Complete Get Connected With 9233 Voice Part Of The Particle Only Bed Making Connection Of Every Element Present In The Pin Code Is Considered As Are The Parent Child Relationship Here two is the present of air port the period of tourism connection Hatim star plus default's create all elements of independent I love you two on connection right now tooth on parents 3366 paint all to two to under-19 the Father of 2 states under-19 the Father of 2 states under-19 the Father of 2 states capitals in independent 333333 connection is create another cable connection vihar-3 hair create another cable connection vihar-3 hair create another cable connection vihar-3 hair oil in a 5 6 with three not even if I will make the part of the same island show the result of 1639 all points 218 updated to vihar 3 And Vihar Sex Power Point Into To Now And To Sell Point Table 2.2.2 Lucid Is Next Pc S Well S Defined Factor Of 12th 1st 2nd 13.16 Civil Unified 13.16 Civil Unified 13.16 Civil Unified 12315 Sex With One Another Girl Top H12 8.22 Welfare In Ijhar Been Updated To All Third Operation 3.2.2 3.2.2 3.2.2 Literacy Day Head Next Element Now 4 Plus 21 Plus C How Many Factor The Present Of 21-23 The Second Vice 75003 Between The Second President Of Software Update From To Post Island How Do You Do Modern Serlimante 3636 Not Part of This Answer Selected Completed The Equation of All the Element and What Do We Have Received at All The President of the Princess Two and Parents Are Not Come Out B Are A and B Equal to 2 Expensive Example Undertaker's Swaravihar Next Element Of 41 And What Is The Prime Number Is Not Part Of This Island Country Because Of What Is Not Divisible By Any Elements And It Will Be Treated As Independent Company 41212 Company All The Elements Of The Princess And Prince 108 Na Utara Uncodified Of Lbs Jacqueline 10 * Na Utara Uncodified Of Lbs Jacqueline 10 * Na Utara Uncodified Of Lbs Jacqueline 10 * 10 Laptop Divine Updates In The Print Are Every Time And Price Albee Sharing Urgent Template Will Help You In Long Run Turn On The Template Buy Bye Bill For You In All The Union Finance Show Fear Of Death In Marks Variable And Is Treated Complete Are Identified Maximum Elements Present In Water And Create A New Union Finance In Tattoo Shop In 2.7.22 E Want To Update Date 22 Play Major Started Uber Hero Rise To Do After Payment Details For Girl In School Code 20 Page Views And Access To Representative Parents 9044 And Input Constructor And Winter Let's See What Happened Accepted In 60 Times Better with Pretty Good I'm Satisfied with Time Complexity They Bring Me to the End of Today's Fashion I Hope You Enjoy Repeatedly Engaged in Lights of India Return of the Day God Bless You Tomorrow's Weather
Largest Component Size by Common Factor
word-subsets
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Array,Hash Table,String
Medium
null
224
Hello friends, welcome to my YouTube channel, today we are going to discuss all the problems of the lead, you give 24 which is in the basic calculator, you do not have to do the banana function like velvet, you do not have to do it, after doing valuation and giving us the output, then like. We will call them otherwise we will go out We will do this in the function which I will make Equal you i plus one three which output And in this we will check the condition if output = output this is the output means negative divide by Here what we are doing is we are doing and dividing so we are converting it into brick, this one in the value sting. Given if it is smaller than this then we will run it means plus minus for star and divide then we will update here and then update here the new value that if we will openilize there to net or else we It will be easy for us to calculate for dividing. If not, then we will close it here and reduce it. If we do it plus one, we will do it and update it here. If this is the return, then first we will reduce it by 4 + 5 + this is the return, then first we will reduce it by 4 + 5 + this is the return, then first we will reduce it by 4 + 5 + 2 11
Basic Calculator
basic-calculator
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_. **Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "1 + 1 " **Output:** 2 **Example 2:** **Input:** s = " 2-1 + 2 " **Output:** 3 **Example 3:** **Input:** s = "(1+(4+5+2)-3)+(6+8) " **Output:** 23 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`. * `s` represents a valid expression. * `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid). * `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid). * There will be no two consecutive operators in the input. * Every number and running calculation will fit in a signed 32-bit integer.
null
Math,String,Stack,Recursion
Hard
150,227,241,282,785,2147,2328
392
hello today we're going to be doing lead code problem 392 is subsequence and this is one of the top 150 questions that lead code has put together uh the most popular interview questions this problem States given two strings s and t return true if s is a subsequence of t or false otherwise a subsequence of a string is a new string that is formed from the original string by deleting some can be none of the characters without disturbing the relative positions of the remaining characters Ace is a subsequence of a b CDE e because you can pull the B and the D out and get A's or a e is not first example ABC so you can take out the H take out the G and you can take out the D and you have ABC example two axc there is no X in here so it can't possibly be a subsequence of t okay the way we're going to do this is use two pointers one is going to Traverse string s and the other one is going to Traverse string T and we're going to compare the first character of s to the first character of T and if those are equal then we're going to in increment a counter and at the end if the counter is the same length as s then we have a subsequence so let's start coding make a counter I assign that to zero I'll make another counter J also equal to zero that's going to Traverse the T so while I is less than S length and J is less than T length we don't want to go outside the bounds of either of those strings oh okay so what are we going to do first of all we're going to spell W right okay so we're going to compare the characters so s using the charet function in Java and we're going to do SUB I is equal T charet of J so if those are equal we're going to increment the counter which the counter is also the counter we use for S and we're always going to increment counter J because we always want to verse t uh the entire okay so then that's pretty much it and then if we're going to return if I is equal to the length of s and we found all the characters in t then we turn true else turn false let's run that okay looks like case one was accepted and as well as case two returns false submit okay looks like it was accepted beating 60% of users the time complexity beating 60% of users the time complexity beating 60% of users the time complexity of this problem is O of n where n is the input parameter T the size of that and then we're just going through SN T so there's no need for additional space so o of one is that complexity and that's it thanks for watching we'll see you next time
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
1,859
1859 leads with sorting the sentence so essentially the question says that we'll take the first example and understand you will be given a string as follows right s would be the string so this is what the string is that would be given to you something similar to this and we need to take these are this is a string made out of shuffled words right so and the position at original position is also given after the word okay so we need to take the word and take the position after the word and use this to reconstruct the sentence in its uh in its proper form so we need to put the uh positions back into place so this would be something like this is a sentence this is what we want right how to go about it so what I'll do is I'll first of all split the words into different the entire sentence into different words and put that in an array now I'll iterate through this array and do some and put it all together to do that I'll create a answer array okay where I'll put in these words in their original in their proper position okay remember this position is starting from one while I our index for in this array starts at zero so we will reduce we'll take this value and reduce one from it and update it so we'll go from left to right so first one we get is s two so we take the position to subtract one so we know where we need to update the word and we'll take the word and update it there we go to the second word the index is position is four which means index three index 3 is here so I'll update it here then I'll go to the third word it is this with it position one means index zero I'll put it at index zero and finally I'll go to the last word take the word it tells me that it's at index 3 so sorry position three so it would beex 2 and I'll update the word over there once I have this I'll just return the joint version of this array and that would be my answer okay let's do this in code how would I go about this so first of all I'll split the sentence s. split wherever I get a space after that I will go through for word by word for word n s and I'll initialize answer here answer to be initialize with none multiplied by length of s so it would be of same size as s and then I will update word by word so I'll take I'll update answer at index word minus one and set that to word from start to the last ex except for the last character I need to take the rest of the word so this will be updated and finally I return the join version of answer so let's run and see the index okay so this word index it's a character it's a string so I need to convert it to an integer here again I need to subtract one because that gives me like we discussed that gives me position I need to convert it into index so let's run and see now and that worked for the two test cases let's submit it and that worked for all the test cases 15 milliseconds
Sorting the Sentence
change-minimum-characters-to-satisfy-one-of-three-conditions
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each word consists of lowercase and uppercase English letters. A sentence can be **shuffled** by appending the **1-indexed word position** to each word then rearranging the words in the sentence. * For example, the sentence `"This is a sentence "` can be shuffled as `"sentence4 a3 is2 This1 "` or `"is2 sentence4 This1 a3 "`. Given a **shuffled sentence** `s` containing no more than `9` words, reconstruct and return _the original sentence_. **Example 1:** **Input:** s = "is2 sentence4 This1 a3 " **Output:** "This is a sentence " **Explanation:** Sort the words in s to their original positions "This1 is2 a3 sentence4 ", then remove the numbers. **Example 2:** **Input:** s = "Myself2 Me1 I4 and3 " **Output:** "Me Myself and I " **Explanation:** Sort the words in s to their original positions "Me1 Myself2 and3 I4 ", then remove the numbers. **Constraints:** * `2 <= s.length <= 200` * `s` consists of lowercase and uppercase English letters, spaces, and digits from `1` to `9`. * The number of words in `s` is between `1` and `9`. * The words in `s` are separated by a single space. * `s` contains no leading or trailing spaces. 1\. All characters in a are strictly less than those in b (i.e., a\[i\] < b\[i\] for all i). 2. All characters in b are strictly less than those in a (i.e., a\[i\] > b\[i\] for all i). 3. All characters in a and b are the same (i.e., a\[i\] = b\[i\] for all i).
Iterate on each letter in the alphabet, and check the smallest number of operations needed to make it one of the following: the largest letter in a and smaller than the smallest one in b, vice versa, or let a and b consist only of this letter. For the first 2 conditions, take care that you can only change characters to lowercase letters, so you can't make 'z' the smallest letter in one of the strings or 'a' the largest letter in one of them.
Hash Table,String,Counting,Prefix Sum
Medium
null
1,711
hello everyone so in this video let us talk about a medium level problem from lead code the problem name is Count good meals so the problem statement goes like this that you're given a good meal and a good meal is defined to contain exactly two different food items with a sum of deliciousness equal to the power of two now yeah you have to pick any two different food to make a good meal now give an array of integers deliciousness as you can see in the input where deliciousness of eye is the deliciousness of the is food item you have to return a number of different good meals that you can make from the list modulated by nine plus seven that you have to make different food item meals okay and the meal consists of you can say two different foods uh now what you can say here is that the consider pretty long so you cannot do this in a very brute first way to take every two possible let's say food items but what you can also observe is that this is to 2.20 which is because the this is to 2.20 which is because the this is to 2.20 which is because the total sum of the two items that you will pick should be a multiple of two if it is a power of two they are only finite amount of power of two till this point because see the very maximum case let's take a very maximum case example the very maximum will be at 220 because again according to the constraints and the next is also 2.20 if you add them 2.20 21. if you add them 2.20 21. if you add them 2.20 21. so what you can see is that the very maximum it's like the very maximum case here 2.21 so this here 2.21 so this here 2.21 so this as you can see is a verified number like you can easily calculate them and because it's an exponential which means that you just have to find a 21 numbers that are like 2.2 there are one to Diva 2 to 2.3 so 2.2 there are one to Diva 2 to 2.3 so 2.2 there are one to Diva 2 to 2.3 so what you can see is that for every number you just have to check that to make it a power of 2 like whether the other pair of it exists what I mean by this is let's say I have a number equal to 5. now if it should be a power of 2 because I have to take two at like two full items and then some of them should be a power of two then the only case can be it can be two it can be four it can be let's say 8 16 32 and so on till 21 numbers so if can it be a power of like if I add this plus X like the other number let's say the X if both of them can power out like can this total sum equal two no can it total sum equal to four no can I total sum equal to eight if it holds up equal to eight then the other meal should be equal to three okay that is the simple idea that the other will be equal to three if the total sum will become below 16 the other will be 11. so there are only 21 numbers that you have to check so you just have to check that the whether the other X exist and you just have to do it for all the N numbers because then you just have to do an O of n for iteration iterating all the numbers and then there are 21 numbers that you have to check and then for all the 21 numbers you will do login time you just check out that whether that number or you can also do this you can say uh using a hash map also but it's better to take like a map only so it is or n log n you can also do unordered map as well but in like in without that you can take it is O of n log n time complexity that will take you just find the answer that's it that is the idea that you have to use to particularly solve this problem or nothing much computed here itself so let's move on to the code part now so we have to first make an array you can do it without the array itself but like I've just made the array so because we have 21 numbers that you have to do I will push back and create all the power of strand two okay so to do I want to divide two to a three and so on it should be also doing two to power let's say 0 also which is one answer that is also family so all these are two to the power are inserted and pushed inside a vector now what you can do add create a map and then what we'll do is that we will iterate our all the elements one by one and then what we'll eventually have to find out is that for every number let's say for every number whether the other part of it okay exists in the map itself so what we'll do is that for taking every number you will check that whether the other part of it should be such that it should it can be a power of two so I will redraw all the powers to in checking that whether the other half of it that is I minus X exists in the map okay if it exists in the map then how what is the value how many times it exists so let's say as you can see it can be like uh duplicate as well so that will form the total number of page that we got and as we increment and take more elements We'll add them inside the map so that we did not double count it because you have to take double or as you can see we have to take different means so that we will not take the same meal again okay that is why this actually happens very like this is a very good technique in which if you don't want to double count anything again what you can do is that you will not update the map initially I have not created the map using a for Loop before this but I am dynamically creating the map inserting the values after finding out the values itself so that I will only add or find out those pairs which are uh like before it so I will only take this element and NAB it before it okay and not after it so that uh different values will be taken and that's it in the end I will have to final answer more head over and plus seven simple so for that you will just take this as a long log so that this will not overflow and the end will just do another 9 plus model result that's pretty much it so that's the whole idea to solve this particular problem out if you still have any doubt you can mentioned a good word for this partial problem I will see you in aspect footing and bye
Count Good Meals
find-valid-matrix-given-row-and-column-sums
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of food, return _the number of different **good meals** you can make from this list modulo_ `109 + 7`. Note that items with different indices are considered different even if they have the same deliciousness value. **Example 1:** **Input:** deliciousness = \[1,3,5,7,9\] **Output:** 4 **Explanation:** The good meals are (1,3), (1,7), (3,5) and, (7,9). Their respective sums are 4, 8, 8, and 16, all of which are powers of 2. **Example 2:** **Input:** deliciousness = \[1,1,1,3,3,3,7\] **Output:** 15 **Explanation:** The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways. **Constraints:** * `1 <= deliciousness.length <= 105` * `0 <= deliciousness[i] <= 220`
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Array,Greedy,Matrix
Medium
1379
306
hey what's up guys this is john here again so today let's take a look at it called problem number 306 additive number it's a media level problem but it's kind of tricky you know okay so an additive number is a string whose digits can form additive sequence and a valid additive sequence should contain at least three numbers and except for the first two numbers each subsequent starting from the third numbers each of the numbers should be the sum of the preceding two numbers and given a string containing only digits 0 to 9 write a function to determine if a given string is an additive string or not and note that you know the number cannot have a leading zero so which means 0 3 and 0 2 will be invalid so what does this mean for example we have one two three five and six right so this the entire string is additive number so why is that because one plus 1 is equal to 2. so 1 plus 1 equals to 2 and then what and for each number right remember so for each number not which means that you know starting from the third numbers here right so 2 is become is equal to 1 and 3 equals to 1 plus 2. 5 is 2 plus 3 and 8 is 3 plus 5. so this one is obviously an additive string here but this is just only uh the most the simplest case because each number only has one digit and example two is like it's a more complicated case so in example two here we have one nine one zero one nine so the additive sequence number is actually this is 1 99 and 100 and the one 199 because with these four numbers right so 1 plus 99 equals to 100 and then 99 plus 100 equals 199 that's why these four numbers will make an additive sequence here but as you guys can see so the difficulty for this problem is that we don't know how many digits and a number can have right because for this one if you choose one and nine for the first number for the first two numbers right if you choose one and nine and then the next one is what is like knight one something right and this one will not make an additive sequence that's why this one will not work so how can we solve this problem right and so the way we're the way we solve the we're solving this problem is just by using a what you can call it like backtracking or dfs basically what we do is that we try all the possible combinations for the first two numbers right try all the possible combinations for the first two numbers and then we would try to verify if the first two numbers plus the remaining numbers can config conform an additive sequence if we can't if any of the if any none of the combinations can confirm additive numbers we simply return false as long as there is a one case one combination that can form an additive sequence then we return true so what does this mean it means that like this so for example right we try all the possible for example let's say we try the first number the number one is one right and number two is what is 99 assuming we have we are at this we're at this state right now and then the number three is what so number three is always everything that's after the number two in this case it's going to be 1 0 1 9 and 9 right and we're going to have like a dfs function here so we have three numbers here number one number two and number three so this dfs is simply to check given this number one number two and number three can these three numbers 23 numbers form like additive sequence so how can we know if these three numbers can form a negative connective sequence they're like there are two major cases so the first case is what if number one right number one plus number two is equal to number three if right if that's the case of course this one will be a true right so this is the first case and how about the second case the uh you know of course the answer will be this one plus this one that's not equal to number three right but does this mean it's it will be false not necessarily because that's the exact this is like the second case scenario here you know so one plus 99 equals 100 as you guys can see as long as this target let's say this target is a prefix of the number three then it means that okay so it's because up to this 100 right we it's it could be it could still be a additive number so we know that we know the up to this 100 is additive number so we just need to check if the remaining part if plus the remaining part is still additive number but okay so that's and but if we if the if 100 is not even a prefix then we can we are sure that this thing is not it cannot form an atom number we can simply return false but so this one is the tricky case here so with 199 and this 100 is a prefix of number three how can we continue right so the way we're continuing is that you know we're just calling this the same dfs but instead of number one number two and number three we have to shift that numbers to the right which means that you know we have dfs now the as you guys can see now we're checking if the this 199 it can still form like item number which means that now the number one becomes tonight becomes to 99 and number two becomes to 100 and then the remaining parts is whatever remaining parts becomes to number three so as if like you know once we're once we have find the answers here right part of the answers here we're basically we're shifting this number one number to a number three to the right by some position and then we continue doing that until we have find a true answer right so in this case like i said the number one will become to number two and how about the number two in this case the number two is like this is it's the number one plus number two in this case it's 100 right i'm and then the number three is what number three is then is whatever the num previously number three subtract remove the this one the 100 parts which will be the remaining parts the remaining of three yeah so that's basically the main idea for this recursive dfs you know okay cool so with that you know let's start we can start coding so but here as you guys can see here so we have follow-up here right so we have follow-up here right so we have follow-up here right so how would you handle overflow for very large input integers as you guys can see you know even though the numbers the number length is only between the uh 35 but i think the follow-up 35 but i think the follow-up 35 but i think the follow-up saying something like what if this lens is it's pretty big which means if we're doing like number one plus num1 plus num3 num2 here if we do an integer uh add it will it could be got overflow if the string is long enough so the way we're handling it is like at least for me i just instead of using an integer plus an integer i use a string plus string so basically i'm not conv comparing the 100 to 100 with the integer i'm comparing the 100 string with the 100 string so the string will not be overflow okay that's how i handle it all right so with those being said i think we can start coding it so where should we start you know and so the first thing first is we need like the n right n will be the length of nums so the first step right find our num1 and num2 combinations okay so how can we find it so the way i'm finding it basically i just look through all the this entire string from what from high and range of n so this is how i find it assuming we have the string here so i just looping through from zero to i here so it means that you know the i up to eyes are it's my two is my two string here um and i will just use a different j in between here different j to cut this i into num1 and num2 and whatever after i will be num3 that's how i uh iterate all the other combinations okay so it means that now we have a j in range i okay i mean we could start from one here where here we also start from one but you know it doesn't it won't affect our final result because with the empty string it will never it won't find a match yeah so that's why i have num one equals to what num1 is the from the starting point to the j right which will be num j plus one okay so that's the first one and then we have a num2 equals to what num j plus 1 2 to i plus one right and then we have a we have num3 as well it's whatever after the uh then the i the plus one actually you know we can do a little bit in pruning here in for example you know if the num1 plus if the biggest if the longest num1 or num2 is even longer than num3 and then obviously we will never get the announcer right but it will not improve the total time complexities and i would just leave it here i will not change this for loop range here i will leave the uh to the leave it to the dfs to return false for us okay so and if the dfs if the df has num1 num2 and num3 right it's a returns true then we know okay we have true else if none of them confirm an additive sequence in the end we return fast so now it's time for us to implement this dfs right so for the for to implement dfs the fs we have num1 num2 and num3 okay so and first we need to handle this the leading zero case for all of those three numbers here so which means that if the length we can either check it either here or in the dfs doesn't really matter i just choose to check it inside the dfs here so if the length of nums one is greater than one right because if it's just one numbers i think zero should still be counted as a valid number right that's why we only check if the length is greater than zero and right and the num1 zero is zero okay or right that's for number one i'll just copy and paste for num2 and num3 so i'm checking all three numbers if any of them is true i return false it means that it's not a valid case right so now we have a target sum right so we have target sum is what i'm assuming we have like helper functions like i said to do a string sum given num1 and num2 so this target sum is a is also a string okay so the now is the base case right basically if the target sum is the same as the num3 string then we know okay we find a base case which is true so that's this is the base case where we have find a final answer right where then we need to return true otherwise you know if it's if this one is not true we have to check two things first we check if the uh if the length of the num3 is equal to smaller than the okay then the uh outdoor n here n is equal to the length of the target sum right so we have target sum here yeah so why i'm using a length of target sum because target sum could be bigger than both num1 and m2 because we might have like a plus one digits right and if the current number right is equal or smaller than the n it means that there's no way this num3 could uh could form like an additive sequence because here we already checked if the we already know that number three is not does not equal to target sum and if it's a if it's even smaller or even the grid the same length then we know we can simply return false right now here we have what we have like now num3 is longer it's longer than the target sum so we check one thing we check if the target is the pre is a prefix of num3 right if num3 if target sum equal to the uh to the num3 if it's a prefix so to prove the length of the prefix if this is the prefix then okay we'll we can continue right continue dfs and now the num1 will become to num2 and the num the num2 is become to the target sum right and then the last one is the what is whatever left for num3 which would be anything that's starting from n right so that's that else we return false right because if the current target is not even uh is it not even a prefix we can safely return false because we know this will not form a narrative sequence cool so that's that all right so this is the main dfs now let's implement the sum2 here uh okay i'll just quickly implement that sum too this part is pretty standard right basically we have our answer equal to zero right and then and we have p1 pointer one is length of the num one right minus one right because we want to do the plus from the end to the start okay and then we have a plot a plus one equal to zero okay this will help us to record the uh the carryover right so first we have one p1 is equal greater than zero and p2 equal greater than zero right and then we have what we have plot we'll do a div mod right so we for the uh we have int we have to convert since we need to do a div mod we have to convert it in of num one to p1 right this is the p1 the number one plus end of num2 p2 right and then we do we always do a plus one right and then we do a div mod by 10 and then the first one is our new plus one right and the second one is the current value right equals to that so we have to answer that append the current values right and then we do what with p1 minus 1 p2 minus 1. okay so now we have calculated all the uh the common parts for the for num1 and num2 now we have to calculate whatever is left this one is actually similar like merging two sorted list right we use two pointer techniques here so while p1 is greater than zero i'll just copy it here you know so now if there's still something left for number one i'll just use this one so at this time because we don't have like we don't need a p2 here that's why we can only have like p1 num1 plus s1 and then we have p1 same thing for p2 right i'll just copy and paste here for the case that p2 has something left i'll just uh do this so no now we have num2 and p2 we have p2 here okay and in the end right don't forget if there's still something in the plus one here we just we still need to append one at the beginning to the end and then we return what we return a string but we have to reverse the answer you know okay because we are like traversing from the end and when we are but we're adding the answers from the beginning that's why in the end we have to reverse this answer and then convert it back to a string yep i think that's it okay let me try to run the code here uh okay we have a invalid syntax here if this one and okay so we are missing like equal sign here all right oh line 50 there's no nums i think there's only num okay uh dot join answers dot so what sequence number extreme sense in defined oh sorry here since we're concatenating a string side we have to convert this integer back to the string i know this conversion pi is a little bit annoying but that's the way it is okay so we have to add convert this one to a string otherwise it will complain okay run all right so accept it submit all string index line 57 string index oh sorry here i'm missing a colon here which means that i'm not getting this i plus i'm getting whatever left right so submit cool all right so it's accepted uh yeah how about time complexity right i mean here we have a n square here for the nested for loop here and then we have a dfs so the dfs is like an n here because every time we'll be moving forward by the worst case is by one all the time i mean this sum too might increase the uh the time complexity but i'm not counting it in here because this is this one is just to handle the follow-up so follow-up so follow-up so without this one here i mean the time complexity will be close to n square uh an n cube here we have a n square plus n here that's why we have an n cube cool yeah i think that's it i mean just to recap right i mean this is like not a traditional backtracking or the uh or the dfs you know with the traditional like the normal dfs or backtrackings we usually have like what we already have like a dfs we have a starting index right we have an index here and then from the index we'll have some current card numbers right something like that and then from the starting index will loop through from the starting index to the end and then we'll update the current index and then we'll continue so on and so forth right but this one is like there's like a rolling the recursive which means we you if we find a match we will have to move this we have to move this our index i mean partially right partially we have to switch the variables right from num1 to num2 from num2 to the target and then from the remaining parts we cannot simply just bypass to the num3 here because the reason being is we is because for the new for the remaining parts we need the previously two numbers to check that to know to be able to find out if that remaining part is still can still form like a additive sequence that's why we have to do a switching here right or a rolling dfs recursive call here cool yeah i think other than that i mean just uh it's just like this special hanoi right for the stream comparison yep cool i'll stop here thank you guys for watching this video and uh stay tuned uh see you guys soon bye
Additive Number
additive-number
An **additive number** is a string whose digits can form an **additive sequence**. A valid **additive sequence** should contain **at least** three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. Given a string containing only digits, return `true` if it is an **additive number** or `false` otherwise. **Note:** Numbers in the additive sequence **cannot** have leading zeros, so sequence `1, 2, 03` or `1, 02, 3` is invalid. **Example 1:** **Input:** "112358 " **Output:** true **Explanation:** The digits can form an additive sequence: 1, 1, 2, 3, 5, 8. 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8 **Example 2:** **Input:** "199100199 " **Output:** true **Explanation:** The additive sequence is: 1, 99, 100, 199. 1 + 99 = 100, 99 + 100 = 199 **Constraints:** * `1 <= num.length <= 35` * `num` consists only of digits. **Follow up:** How would you handle overflow for very large input integers?
null
String,Backtracking
Medium
872
1,664
hi everyone so i uh i'll be discussing uh date code 1664 problem we used to make a fairly so in this problem we are given input integer area numbers and we can choose exactly one index and remove the limit and arrays of fair if the sum of odd indexed values is equal to the sum of given indexed values and we have to written the number of indices that we could choose such that after the removal announces so let's discuss what the problem statement is trying to convey so for example in this case 2 1 6 4 if we remove 2 which is index 0 you would be left with 1 6 4 now even index is 0 and 2 and all index is 1 so sum of even index is five so sum of e1 is five and sum of obvious six both uh these both values are not equal so if we remove two we would not get this uh fair array condition now if we remove this one we would be left with two six four now here sum of e1 is 2 plus 4 which is 6 and sum of odd is also 6 this is fair this is not so we found one index for which the area would be fair now if we remove six there would be two one four and some off even would be six in some off all not equal and if we remove this four we will be left with two one six sum of even would be um eight and some of all even is also not equal so only for um index one we got fair array so which means that we would return one only for one index we got this off here everything so we would return this count so one way to approach this problem is to basically apply the brute force approach which means that um we would basically be um removing this two index so when we remove this two index we would be left with 164 and we will count loop through this array and count the odd index and even index sum you did the same thing for this also and this also now when the time com if we look at the time complexity of this truthful solution it would be of n squared because when we remove this two basically we are removing n elements uh because first we are removing two then uh for after removing uh two we are looping uh n times n basically that means the uh length of this array it would be n minus one so and then we remove one so it would be again n minus one so on till n minus and this would happen for n indexes so the total would be n minus one plus this would be the total time and this is n times so total time complexity would be international which is also order of n squaring so brute force approach here would not be the optimal um solution to this problem so um a better approach to solve this problem is to use prefix some uh array for both even index and odd index so what i uh let's see if the input is this two 6 4 now i would create even some input one array which is let's see which would basically have um sum of all the elements all the even index elements and or some would have some of all the reduction so this is currently 0 1 2 3 now 0 is an even index segment so you put 2 here so basically and 0 here so the sum um so basically the sum of uh even indexed elements till index 0 is 2 and some of the odd index elements till index zero is zero now here also we put two only because this is an odd index and this one be added here now this six would be added to this previous two which would give eight and this one would be carried on from this device index similarly this three is an order index so this eight would basically be carried forward from this index and this 4 would be added to this one because it is x now this these are the two arrays now there are three conditions then basically we would look what is the um odd index on an even injection so if we uh look at these two areas now when we remove this two we would be left with one six four now we see um basically um the autism would basically be uh since um we are removing an even index element all these odd index element would be shifted to even index and all the even indexed elements would be shifted to alt index elements from that what i am trying to convey is that um let's say initially it is two one six four and this is zero one two three now when we remove this two we'll be left with one six four which is zero into here now this one which is odd index is now even index this six which is even index is now ordinals this four which is our index is now even index so um now odd sum would simply be uh obtained from this even sum only so we would look what is the even sum at the final index so even sum is eight which is uh eight and since we are removing this zeroth element so we would subtract this and uh we would obtain autism as six which is also true because if we look at this array or sum is only 6 now if you want even sum it would simply be this or some last index only which is five because um and if you also see from this um one six four area this one plus four is five so and this is the even index now the second condition is that if i equals to n minus 1 where n is length of lumps so in that case um what we would basically say is that um if there is whether the array is um whether the last index of the array is even or called now if last index is even then basically what that means is that here it is also let's discuss that so if it is odd now last index is hot which means that uh even some would be put simply with this eight only because last index uh is odd which means that um or sum which is 5 would be subtracted by this 5 will be subtracted by this last element index which is one so in the other case it would have been e1 equals index minus whichever the number is present in the last index and option would have been same and as the ordered last index only so these are the two conditions and the third cases when none of these two cases are true which means that if there is um present a little bit basically uh not in the end point so in those cases basically so for all the other cases so let's see if uh in this else condition if the array would happen to 164 and we would want to delete this six now if you see we have two one uh we would be left with two one four now if you see this zero one two three now here this zero is at zero index here only and this one is at one index only but this four which is an odd index is now converted to even index because uh i element before it was removed so all the elements after this removed element would basically uh all um all the or some and even some would be swapped after this deleted elements so now here even some would be this um basically if we are removing the second index we would see what is the even sum before this which is two we would keep it because that remain uh intact only and after that we would see what is the option total option which is five and we would subtract um what is the sum um before this element which has to be included in or autumn and shouldn't be included in events so which is one here obtained this obtained before this index which is two um and index before it is one and the sum or sum here is one so this has been removed uh from this autumn and would be left with six and for autism um we would have um one plus eight minus here instead of removing this two we would want to remove um this six also um just second uh because we are removing the second index also so we would want to remove the sum corresponding to it also so would remove eight minus eight which is one only and which is true also if we see the even sum is two plus four and autumn is only one so this is the explanation to this uh whole code which is um over here the time complexity of this solution is simply often and space complexity is also often because i am using this perfect or even some and on some areas
Ways to Make a Fair Array
find-users-with-valid-e-mails
You are given an integer array `nums`. You can choose **exactly one** index (**0-indexed**) and remove the element. Notice that the index of the elements may change after the removal. For example, if `nums = [6,1,7,4,1]`: * Choosing to remove index `1` results in `nums = [6,7,4,1]`. * Choosing to remove index `2` results in `nums = [6,1,4,1]`. * Choosing to remove index `4` results in `nums = [6,1,7,4]`. An array is **fair** if the sum of the odd-indexed values equals the sum of the even-indexed values. Return the _**number** of indices that you could choose such that after the removal,_ `nums` _is **fair**._ **Example 1:** **Input:** nums = \[2,1,6,4\] **Output:** 1 **Explanation:** Remove index 0: \[1,6,4\] -> Even sum: 1 + 4 = 5. Odd sum: 6. Not fair. Remove index 1: \[2,6,4\] -> Even sum: 2 + 4 = 6. Odd sum: 6. Fair. Remove index 2: \[2,1,4\] -> Even sum: 2 + 4 = 6. Odd sum: 1. Not fair. Remove index 3: \[2,1,6\] -> Even sum: 2 + 6 = 8. Odd sum: 1. Not fair. There is 1 index that you can remove to make nums fair. **Example 2:** **Input:** nums = \[1,1,1\] **Output:** 3 **Explanation:** You can remove any index and the remaining array is fair. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Explanation:** You cannot make a fair array after removing any index. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104`
null
Database
Easy
null
649
hi guys good morning welcome back to the next video so basically in this problem in this video we're gonna see this problem Dota 2 scene uh firstly I really be apologies for the inconsistent videos of our Bob graph series but for sure like it would soon pick up the speed for now like it's a too much work apart from this that's the reason the frequency is a bit low but yeah it now increase soon apart from that let's look at the problem pretty quickly it's a pretty easy problem it's just that okay you have to get one way that okay all these other problems is solved by using the some kind of this method and we have to just think of a data structure which can actually implement the same kind of concept let's see what I'm gonna say uh in the world of Dota 2 there are two parties radiant and dire R and D I'll just say uh consists of cylinders coming from two parties which is party one r partitude d uh now the Senate wants to decide on a change in the game the voting for this change is a round table round based procedure in each round basically what happens is each Senate can exercise one of the two rights mentioned below what is the right ban once in its right which means if I am standing on a senate s of a party R then he can ban any other Senate after him of any other party maybe his party or maybe the day party cool uh a senator can make another Senator lose all its rights and all the following rounds which means once like kind of it's he's banned completely banned cool announce the victory which means if the Senators found that the Senators who still have the rights remember ultimately whosoever is not banned which means they still have the rights are of the same party which means all are RR or all our DDD right he can announce the Victory and decide on the change in the game okay now the victory will be decided by that giving us strings in it representing each senator's party belonging thus character RND as I said okay the party of R and party of D represents the r party and the D party then if there are NS Senators which is the size of the given string will be in okay Round Table procedure will start from the first cool uh to the last person and this person will repeat until the each round of voting until each round of voting all the Senators who have their who have lost their rights will be skipped during the proceed which means who have been completely banned will be skipped suppose every Senator is a smart enough and will play the best strategy for his own party what if they want ultimately is which party will finally announce the victory to finally announce the victory we remember that all the members should be of the same party which means ultimately if I am the senator of party r i want to announce the victory then all the members should be the remaining numbers should be of the party are itself if I am sick I am smart enough and see the one right I have is to actually ban another person another right I have to announce the victory announcing the victory is limited to the condition that all of them should belong to the one party which is my party announcing a ban is on my hand what do you think if I'm smart enough and I want the victory which means I want all the people of my party to remain so what I will do I will always try to ban the person of other party if I am of R I'll ban the person of D if I am of D I'll ban the person of R it is entirely because of I am smart enough and I want to finally announce the victory I won't finally answer Victory and denounce the victory I need to have all the members of my party changes the total game uh the output should be radiant or higher depending upon which party wins let's see the example r d so basically I'm standing at r a person of R party he has two options either he can announce the victory or he can announce okay right now all the members are not office party because these also here so for sure option two will come entirely in the end when all the members will be of the same party but now right now our half power K he will just ban d now in the next round only R means he will announce Victory a radiant events same uh r d r standing here no worries of announcing Victory right now just saying okay R will for sure Bandy okay cool our balance d cool our man's D this D is gone it is not it is no more here so in the next round he will have a chance to act okay what he will do is he will ban him as it is said it's a round table it's a round Table Right it is said it's a round table in the rounds in the or a center can make another cell reduce all its rights and all the following rounds right so basically in the next round what happens is this D will actually ban R now ultimately what happened was this D remains ultimately the party which will have Victory is there that's what you have to do Jesus that you have to print the same thing which means what we want is we want the X party like he wants his party to win so he will for sure try to ban other party members as soon as possible it's nothing but greedy okay I'm starting at the location I'll try to ban my next person of other party just ban it just ban him because ultimately if I don't ban him right here let's say if I was standing at r I had an option okay just ban him okay for one thing I for sure no key I can ban I will always ban D other party members I will not ban my own party member for sure cool then I have an option I will ban this D or this D what do you think which D should I ban if I had banned the D right here then what would have happened okay he would have gone and my next R would have again banned this day so entirely my R would have won but if I would have won the D right here then in the next iteration this D would have banned my right d here maybe next iteration again it will ban this D but still you got the point right what can worst case happen is I should not I should try to just ban my consecutive my next consecutor D opposite parties fine cool you can just replicate with if it had again a one more D then what would have happened but it's just that okay I'll just try to kill the next party members as soon as possible now okay we just got to know that if we had R then we must ban its next closest D if we have D we must ban its next closest r the same process as I replated in words just replicate that in code which means we grab each Senate r find its next closest Senate D and ballot keep repeating the process which means we have multiple rounds right until our Victory is achieved victories achieved when entire R is going to entire D is gone that means all members are remaining of the same party now writing the same thing in Gold grab each senate or have a queue where you have each Senate are yq let's see find its next closest thus we are using a queue because in a queue the elements are stored in order they are stored I want to graph if I just grab this particular D I want to grab the next d so I want okay next closes so I can just grab from the front of the queue that is now one of the next closest I will just place every element side by side I will have a Q of r q of D I will place every element of index of Q of D which means every party member of d side by side so that I can grab the next closest d as soon as possible that's the reason I'm just grabbing a q okay to place the Senate D I will have another q for D to place the members of Senate D and ultimately to ban it which means okay they are no more useful which means just remove that from the queue as simple as that keep on repeating which means until my queue is empty while loop simple Banning of Senate removing that from the queue a victory is achieved when and when one queue is empty which means only one queue is remaining and that is non mtq either it can be of R either it can be of D whichever is remaining a right now will be the person who will actually win that is interesting if you have to implement let's see the code pretty quickly it's exactly very easy firstly I have a queue of R and D representing two parties party arm party D members of RTR party D exactly uh now I just go on entire Loop and grab okay I will just push in the party R members in my QR and party team members in the QD I'll if it is R I'll push in the QR queue and I'll push in if it is D I'll push it in the qdq now comes the interesting part I need to go on I'll explain you what's the complexity of this problem but still just imagine just think of the same thing okay what the problem is saying after you've been the same thing I just keep on going until my one party is exhausted and what my party represents party members are represented by this QR in QD so until this QR and QD is there just keep on going as soon as any one of them is empty which means the other party has one if let's say QD becomes empty so QR has one if QR becomes empty so QD has one which means ultimately at the end of this Loop I'll explain what the loop is doing but at the end of this Loop if my q r is remaining so which means QD is dead the query is entirely gone then I'll just say okay it's radiant who has gone if Q D is remaining then I'll just say okay it's that is the thing you have to do now comes the while loop is the most interesting part what I will do is I will just grab the front member as I says okay if we have r d indexes one two three um four and five my r q will have index 1 3 4 my D Index my DQ will have indexes 2 and 5. so basically I want to grab this and whosoever is lowest maybe D has come or maybe R has come grab the initial twos R and D because it is what I want grab the initial Tools R and D and kill either r or D because of R either D will kill or because of d r will kill which means if the if let's say index 0 is here and the T would have been here so because of theta R would have killed so basically grabbing the first two R and D and then killing one of them which means Banning one of them I just grabbed R's ID like uh the r party person ID D ID which is the a passive party person's ID basically pop both of them because both of them are not required at this position right now one of them will go which means either here if the e was here so he would have killed r has one for sure the D has also gone it will come in the end now you remember what happened this D was actually being implicated as you saw above in the example the D as soon as it was gone the example was R rdd right r d because of this R the D was one cool but now this R cannot affect this D right here T right here so it would come in the end because it was a round table as I said it would just go in the end and which means it has if it is standing at R the elements are 0 1 2 it needs to come at 3 right as I said it's a round table so it just goes this particular index plus number of elements so I plus n it is how a round table is designed in an array if you just want to replicate the round table we just replicate entirely put the RS side by side if it is A1 A2 A3 A4 then to get A5 which is actually A1 A2 A3 A4 which is if it's in that is 0 1 2 3 then its index is four five six and seven you see is 0 plus 4 1 plus 4 two plus four and three plus four to get the round table thing we just add the index n to actually get the same thing afterwards it can come that's the reason we have to remove both of them but the next D would come where is the example gone yeah the next D would come at the index which is I plus n because it can't remain here it will come afterwards so that next D could actually kill him that is the reason we will just remove both of them we just popped both the members but if my R is less so R will kill D which means my R will still remain R Kelly d r band D so R still remain and it will just be pushed as R of ID plus n for the next round evaluation and D has gone while in the vice versa if our D would have been more so it would have killed band r o yeah R and then my D plus n would have been gone that's the reason just remember at every step one of the members is being banned from this q and one member basically what happens is two members are being gone and one member is being added so ultimately in this entire one Loop procedure one member is for sure being banned in this array does its complexity is often because ultimately we have n elements n members in this two queues entirely they're n members but at every step one member is being banned so this Loop can entirely go up to n times that is the reason that the time positive open and space is also open because we are using a queue and that is pretty much it so you got what's happening we just grab two cues just to replicate okay we just have two think of banning because of this initial R what is the initial D we can ban because of what Initial D because of what initial r i can ban that is why I use a cube and then to replicate the round table thing I just pushed in the next element which is if R is spanning B then R will actually go on in the end that is how we do by I the index of R plus n it is a very important concept the SoundCloud concept it's used a lot so please remember that and the codes of C plus Java and python is down below for your reference exactly same code so yeah the fact that was there so yeah that was pretty much it I hope that you guys liked it if yes foreign
Dota2 Senate
dota2-senate
In the world of Dota2, there are two parties: the Radiant and the Dire. The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights: * **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds. * **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game. Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`. The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure. Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant "` or `"Dire "`. **Example 1:** **Input:** senate = "RD " **Output:** "Radiant " **Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote. **Example 2:** **Input:** senate = "RDD " **Output:** "Dire " **Explanation:** The first senator comes from Radiant and he can just ban the next senator's right in round 1. And the second senator can't exercise any rights anymore since his right has been banned. And the third senator comes from Dire and he can ban the first senator's right in round 1. And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote. **Constraints:** * `n == senate.length` * `1 <= n <= 104` * `senate[i]` is either `'R'` or `'D'`.
null
String,Greedy,Queue
Medium
495
413
hey my friend welcome to choice dynamic programming tutorial you are watching the 100th video of dynamic programming on my channel joey's tech thanks for all your support your comments and acknowledgments really encourage me to keep going and work harder so that i can bring out instructional videos for you on programming and algorithms that really help you succeed in this video you will be learning the arithmetic slices problem which i have taken from the lead code website let's see what its problem statement has to say you must have heard about arithmetic progression this dp problem is very much related to that the problem says that if an array consists of at least three elements and if the difference between any two consecutive elements is the same then that array is called arithmetic so you are given this array nums over here you need to find out the number of arithmetic sub arrays from this array for example 1357 is one arithmetic sub array and so is 135 we'll find the solution of this problem using the classic dynamic programming technique but before we do that do subscribe to my channel if you haven't done it already and hit the bell icon as that way you won't miss out on any of the videos i release as you can see that i have put down the problem array over here beneath it i have created another array which goes by the name dp this will help us determining the solution the clue that the problem statement provides is that the array has to have at least three elements to be arithmetic hence in the first two cells of this array i'll simply pour zeros and will start the operation from this cell the third cell let me put zeros in these cells now to fill the value in this cell we'll do a simple operation of checking whether the result of the subtraction of 5 and 3 matches the subtraction result of 3 and 1. this is what is going to make it a simple arithmetic survey right so 5 minus 3 is 2 and 3 minus 1 is 2 they both give the same result so all i'll do is add 1 to the value stored in the previous cell and store the calculated result in this cell why we did it you will find out in the next sub problem one thing is clear that we have got an arithmetic slice over here and for the purpose of clarity let me write that arithmetic slice down here moving to the next cell we perform the same operation here the result of 7 minus 5 is 2 and the result of 5 minus 3 is 2 so they both match in this case what we are going to do we'll add one to the value stored in the previous cell and store the calculated result here in this cell does i populate two here now this two means that there has to be two arithmetic slices shouldn't there be the first arithmetic slice will obviously be 3 5 7 which we already checked just now but which is going to be the next one so let me tell you that it will be one three five seven this particular arithmetic slice we got from the previous sub problem which already found out 135 and the new addition is 7 to the series now if you consider this sub problem till here you can see that we have three arithmetic slices in total which can be simply calculated as a result of the addition of 1 and 2 let me write a variable here and store 3 as its value let's perform the same operation for this cell as well as we are very close to finding our final answer so here the subtraction result of 9 and 7 will be 2 and the subtraction result of 7 and 5 will be 2. they both match so in this case what we are going to do we will add 1 to the value stored in the previous cell as a result of which we are going to get 3 and i will store 3 in here in this cell this 3 denotes that there are 3 arithmetic slices or three arithmetic sub arrays involving nine so the first one is very simple it will be five seven nine which we just checked the second one can be found out by simply adding 9 to this arithmetic slice over here which is going to give us 3 5 7 9 and the third one can be found out by simply adding 9 to this arithmetic slice over here that is going to give us 1 comma 3 comma 5 comma 7 comma 9 so there you go so the total number of arithmetic sub arrays that we are going to get out of this array nums will be 6 so this 3 over here will be added to the value of the variable risk which is already stored over here and it is going to give me 6. there you go we have solved this problem using dynamic programming technique you'll find the github link to the java solution of this problem in the description box below i hope you enjoyed watching this video like it share it tell people about it i look so much forward to help you with programming and algorithms thank you and take very good care of yourself
Arithmetic Slices
arithmetic-slices
An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. * For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences. Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 3 **Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself. **Example 2:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 5000` * `-1000 <= nums[i] <= 1000`
null
Array,Dynamic Programming
Medium
446,1752
188
hey guys welcome back to this video now we're going to solve a coding interview problem best time to buy and sell stock five this is a liquid problem you're given an integer array prices where prices i is the price of a given stock on the eighth day design an algorithm to find the maximum profit you may complete at most k transactions notice that you may not engage in multiple transactions simultaneously that means you must sell the stock before you buy again this is the problem statement for example if you're given this array and k equals to 2 now we have to find out the maximum profit we can make from this array by doing at most k transactions here two transactions if we buy at two ntp sale at four then we'll have profit two if we buy at four if we sell at one then we will have lots okay so here we can made profit two by one transactions in the problem statement we see we can make at most k transactions okay here we are doing one transactions to find our maximum profit so for this given input we have to return to if you are given this array and k equals to 2 we have to find out the maximum profit we can made from this array okay we are allowed to do at most two transactions if we buy at two if we sell at six then we have profit four then if we buy at zero and sell at three we'll have profit 3 so we are doing here 2 transactions and we get 4 plus 3 equals to 7 so for this given input we have to return 7. if we are given this array and k equals to 6 we have to find out the maximum profit we can make from this array by doing at most k transactions if we buy at 1 if we sell at two we have profit one if we buy at two and sell at three we have profit one if we buy at three if we sell at four we have profit one if we buy at four if we sell at five we have profit one if we buy at five if we sell at six we have profit one then if we add all the profit then we get five so for this given input we can make maximum profit five by doing at most k transactions here we're doing five transactions now how we can approach this problem gonna be a little bit critical to understand let me explain every single details that you need to understood this problem if we are given this array and k equals to six first we're gonna check if the value of k is equal to the length of the given array or greater than that means if k is greater than or equals to the length of the given array then we can solve this problem exactly same at the liquid problem 120 best time to stock by cell 2. okay now let's see how we can solve this problem when we have k is greater than or equals to the length of the array okay first we'll iterate through this array from the second element to the end then we're going to check the current element and the previous element if we see the current element is greater than the previous element then we'll buy at the previous element and will cell at the current element so here if we buy it on a pcl at two we have profit one then we have current element three if we buy it two we sell at three we have profit one then current element four if we buy it three if we sell at four we have profit one then current element five if we buy at four epsilon five we have profit one then our current element is six if we buy at five and if we sell at six then we have profit one now if we add all the profit then we get five and this is the concept that used to solve the liquid problem 122. i'm not going to go through the pseudo code for this problem i will attach the source code to this video you can check the link in the description this is the a sketches for this problem when we have k is greater than or equals to the length of the array then we have to apply the concept of this problem best time to stock by cell two all right now if you're given this array and k equals to two here we see k is not greater than or equals to the length of the array then how you can solve this problem now this problem going to be difficult to understand don't worry i'm going to explain you as far as i can now i'm going to go through the intuition to this problem now let's see how you can solve this problem using dynamic programming when you have k is less than the length of the array first we're going to construct dynamic programming table and this is our dynamic programming table for this input we're going to use this formula to fill up the dynamic programming table t i j equals to max of t i z minus 1 what does this mean it means that what i can do best if we do not sell at the current price and this means that what we can do best by selling at the current price here we have our array right 326503 and here we have our transaction zero one and two at zero transaction we will have always maximum profit zero so here zero all right if we sell at the first index that means if we sell at this index zero we will have no profit so let's fill up this first column as well with zero now our goal is to fill up this dynamic programming table and we'll have our answer right here okay now let's fill up this dynamic programming table using this formula now we're going to fill up this box if we do not sell at this current price to what you can do best we can do best zero okay then if we sell at the current price what we can do best two minus three so minus one plus our profit by selling at index zero at zero transaction and that is zero so minus one plus zero is minus one so max of zero and minus one is zero so let's insert here zero now let's fill up this box okay here if we do not sell at this current price six we can do best we can the best zero okay by just copying value from the left if we sell at the current price what we can do best six minus three so three plus what i can do best by selling at price three at zero transaction that is zero so three plus zero then we have another option if we buy it two and sell at six minus two equals to four plus what i can do best if we sell at two at zero transaction zero so four plus is zero so max of zero three and four is four so let's insert here four okay now let's fill up this box now what i can do best if we do not sell at this price five and that is for by coughing from the left now if we sell at the price five what we can do best so pipe minus three two 2 plus what i can do best by selling at price 3 with 0 transaction 0 so 2 plus 0 then 5 minus 2 is 3 so three plus what i can do best if we sell at price two at zero transaction and that is zero so three plus zero okay then five minus six that is minus one so minus one plus what i can do best if we sell at six at zeroth transaction that is zero here we see max of four two three and minus 1 is 4 so let's insert here 4 similarly for 0 and for 3 will be evaluated 4. you can go through using this formula okay now let's fill up this box what we can do best if we do not sell at this index 2 that is 0 by copying from the left what we can do best if we sell at this index 2 and that is two minus three minus one plus if we sell at one transaction because we're doing here second transaction we have to get the value by the first transaction as well because we're allowed here two transactions for this row so minus one plus zero is minus one so max of zero and minus one is zero so let's insert it zero then let's fill up this box what i can do best if we do not sell at this price six and that is zero by copying from the left what i can do best if we sell at price six and that is six minus three so three plus what you can do best buy the first transactions at three there is zero three plus zero then six minus two is four so what i can do best episode at two for the first transaction and that is zero so max of zero three and four is four so let's insert here four now let's calculate the value for this box what i can do best if we do not sell at this price five four right by coughing from the left what are gonna do best if we sell at this price five that is five minus three two plus by selling at three for first transaction zero then five minus two three by selling at two for the first transaction is zero then five minus six minus one plus the max profit we can get by selling at six for the first transaction and that is four so max of four two three and three is four so let's insert here four now let's calculate value for this box here we have price is zero if we do not sell at this sprite we're gonna do best four right by copying from the left then if we sell at this price then we have minus three plus by selling at three by the first transaction that is zero then zero minus two plus by selling at two for the first transaction that is zero then zero minus six plus a profit by selling at price six for first transaction and that is four so minus six plus 4 then 0 minus 5 so minus 5 plus the profit we can make by selling at price 5 that is 4 so max of 4 minus three minus two and minus one is four so let's insert here four now we're on the final box here we'll have our answer here what we can do best by do not selling at this price three that is four by copying from the left okay then what you can do best if we sell at this price three minus three is zero plus by the first transaction the property can meet by selling at price three that is zero then three minus two one plus the profit you can make by selling at price two by first transaction then three minus six is minus three so minus three plus the profit we can make by selling at price six that is four for the first transaction then three minus five is minus two minus 2 plus the profit you can make by selling at price 5 for the first transaction so by selling at price 5 for the first transaction we can make profit 4. so minus 2 plus 4 comma then 3 minus 0 is 3 plus what i can do by selling at price 0 for the first transaction and that is 4. so max of 4 0 1 2 and 7 is 7 right here the value will be 7 and this is our answer that you needs to return all right if we have more transactions like three transactions then we'll do the same process and for ease calculations we will get the profit from the previous transactions okay if you're on the third transactions then we will add the value from the second transactions okay and that's how it works for better understanding go through like this i'm showing you here by k equals two three and four then you will see how logical it is okay and this is my solution to this problem at the end we'll return this value 7 the solution will takes big of n k time complexity where n is the length of the given array and k is the given integer and it will also takes big of n k space complexity to construct the dynamic programming table hope you have understood this problem and the source code is attached to this video check the link in the description all right guys hope you have understood this problem if you aren't clear on this concept let me know in the comments below i'll be glad to health let me know what type of video i should cover in the future if you haven't subscribed to the channel please subscribe to the channel like this video share this video your feedback will inspire me to create new video content all right guys thanks for watching this video i will see you in the next video till then take care
Best Time to Buy and Sell Stock IV
best-time-to-buy-and-sell-stock-iv
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`. Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** k = 2, prices = \[2,4,1\] **Output:** 2 **Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. **Example 2:** **Input:** k = 2, prices = \[3,2,6,5,0,3\] **Output:** 7 **Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. **Constraints:** * `1 <= k <= 100` * `1 <= prices.length <= 1000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Hard
121,122,123
4
has been asked by Facebook Amazon Bloomberg Google Tik Tok Microsoft dman sax yendex London Adobe turning Uber Oracle Apple eBay Yahoo Walmart Salesforce and the list goes on and on hi guys welcome to day eight of 100 days 100 challeng in which 100 days 100K plus local placement in this we'll see number of land Islands we have already discussed this problem so you can just see the link down below now let's go on to day number nine a pure torture question as by Amazon Apple Adobe Google Goldman Sachs Microsoft Bloomberg Facebook Yahoo ripling eBay Uber LinkedIn TCS service now PayPal Morgan Stanley Zoho and the list goes on and on again hi guys welcome to day nine of 100 days 100 plac challenge in which 100 this is again a torture question again it might be easy for some but in the beginning as soon as you optimize it you'll start feeling oh something has gone very wrong so it says that as simple as that median of two sorted arrays you will be given two sorted arrays nums one and nums two again you can just imagine we have two arrays which are sorted we might be using that part twoo nums one and nums two of size m&amp;n respectively and we have to return m&amp;n respectively and we have to return m&amp;n respectively and we have to return the median of the two sorted areas and they are just mentioning that it should be nearly about log m + n that is the be nearly about log m + n that is the be nearly about log m + n that is the most tricky part we will try to obtain so it just say is that a sample example we will take because the above examples are very small so we'll take some sample example just bit bigger so nums one and nums two we want median is nothing but the mid element so if we have even number of elements as you see if we have four elements here so for sure the median will be the average of the mid two elements right the average of the mid two elements and the mid two elements as you will see firstly I just got these elements in one array I just sorted the entire array down I got this AR array after sorting which means I just combined nums one plus nums two I got the array added and then I sorted that array I got the new array now I can just say that okay I have num one plus which is the sorted AR array and then in the mid I'll go and find what of the mid elements that will be and I'll take the average of them if it is even if it's just odd I'll take the mid element if it's even I'll take the average of the elements and I'll get the my median okay so you can see that I'll just simply merge the arrays I simply merge these two arrays I to find the median I just took the average which is 3 + 5 by 2 took the average which is 3 + 5 by 2 took the average which is 3 + 5 by 2 answer is four so median is four for this specific array so you will see as I combine two array which is O of n plus M operation and then to sort o of n plus M size it will take a m plus n log M plus n time and the space will be of m+ n but n time and the space will be of m+ n but n time and the space will be of m+ n but for but you me a new array oh yeah you me a new array for that the space required will be of n plus n all you can combine in existing are itself but yeah in toal space required will be n plus n for sure this is not even using our concept of sorting as in the AR sorted so let's try to see that okay what if we try to use the AR sorted itself so ultimately if we look back we have to figure out okay if we just say that um we have an array of eight elements right so I for sure know that I will be requiring my fourth and the fifth element which means that if I just bifurcate that array into half which is four elements on the left four on the right so you will see that I am just needing the two elements so I just need this portion only at Max this portion if I go from the go from any end either left or right I just need one portion so okay one thing I got to know that okay it is sorted this array is sorted nums one and nums two are sorted I just have to reach to this point now by what is the point of reaching this point so what I'll do is I know that my AR are sorted right so I can go and use two pointers one on my nums two and then we'll keep on incrementing but by what will happen I know that I will go up to this point only but what I will do meanwhile I will make sure that I am saying okay this is my maximum element one this is my maximum element two so in the last when I would be reaching at this point I will have my maximum element one which is the current maximum element up to this point and the maximum element two which is the current maximum element like next maximum element which is the second smallest or second maximum element I will have as M2 with this I would be knowing at this point who is maximum and second maximum and with this I can take the average of these two and get the answer so it is only possible because these two were sorted and I can just in two pointer way move on both the arrays which is nums one and nums two so I'll do the same thing now by what is this point if you just closely look at it will be nothing but n + m by 2 n + m by2 because index but n + m by 2 n + m by2 because index but n + m by 2 n + m by2 because index from 0 to n + m by2 so okay that index from 0 to n + m by2 so okay that index from 0 to n + m by2 so okay that is great um so as you saw that if I am standing here so I'll just compare the values so I'll just say okay if both are comparable at least I can compare both of them so if I can compare both of them which means both are in Bound of myss 2 but what if it is outside oh if it's outside then we will see the case but right now I can compare both in are valid so it says in both are valid now if both are valid I'll just say Okay whosoever is small now if nums of I is less than my nums of J if nums of I is more than my num of J else will come nums of I is less than my nums of J so whosoever is less as you'll see nums of like nums of one of I it is lesser than nums of ons of I is lesser than my nums of num one of I is less than my num two of J so I simply as you'll see I am simply assigning my new upcoming element to my M1 and by but you were saying that you'll assign the maximum element to M1 and then next minimum element to M2 yeah true but you'll see that okay I'm only assigning in every comparison I'll only assign M1 so whoever is smallest right now okay one is smallest assign it to M1 here you will see M M2 is smallest like M2 is smaller right so assign to M2 sorry assign to M1 I'll assign only to M1 I'm assign but what about M2 when you will assign that so basically I'll just say in the end as in the end which means at every iteration I'll be saying okay M2 assigned back to M1 assign M1 assigned back to M2 M1 back to M2 so basically M1 will be okay right now if I just compare okay right now M1 will be one then my I will go here as soon as my I go here so M2 will become one now M1 will become minimum of them two okay great now it will go again further so now as soon as I'm starting to compare the next one I'll firstly assign my M2 okay now my M1 will again minimum of them which is three anyone so I can just take any one let's say I move this or this anyone it doesn't matter now I just I before comparing we'll assign my M2 to M1 now I'll compare okay it is again M1 so again uh I will have to move which is for sure I'll move my J because this is what I compared so okay again uh it is about to compare assign this to M2 assign again minimum M1 so you saw with this my M2 is the second smallest and M1 is the small like M1 is the maximum and M2 is the second maximum and with this I can get these M1 and M2 so again what if my I is finished which means as what if my J is finished then my I is still remaining right if my J is finished I is still remaining this is the case when my J is finished but there is no condition for J yeah I'll put this condition first and then if this is not satisfied I'll put this condition which means if I is less than J then you just say Okay M1 is so F but what if my I is not there okay then if J is less than n then try for this so this is how we can split the functionality of a code and the same way I showing the code although I have explained it with writing down but yeah the same way the code itself look like I will have i j M1 and M2 again you know M1 and M2 M1 is the maximum M2 is the second maximum I will be going in from count equal to 0 to count is less than equal to n + m by2 it is not less than equal to n + m by2 it is not less than equal to n + m by2 it is not less than it is less than equal to because I have to go up till this point I have to go okay great then for sure as you remembered that as soon as I do the next ceration I have to assign my M2 to a M1 right I have to assign my M2 to a M1 so as I can now modify my M1 here itself so what I'll do I just say okay if both are actually valid which means if I is not equal to n and J is not also not equal to M then I can just simply say that assign depending upon whosoever okay if nums one of I if nums 2 of J is smaller then assign M1 if nums uh one of I is smaller then assign to M1 now when this is done else if condition okay by what if my J has reached the end no worries if I still there then okay now assign my M12 num one of I else my assign my M12 num 2 of J now with this I have assigned my nums one and nums 2 that is done now simply just you have to find what median so what I'll do is I'll just check if the actual median if just odd number which means I have just one element I it's just odd number so simply assign your M1 if it's an even number then you will assign the average of M1 and M2 and that's what you will do if it is odd if it is even and that's how you can simply solve it in O of n + how you can simply solve it in O of n + how you can simply solve it in O of n + m time in space and O of one and that's how most companies are always like okay that's great for you but if you remember the problem says one thing the problem openly says that can you please solve it in log of M plus end time so we are forced to optimize it much more further now if it is something is sorted and we kind of start thinking of binary search I'm not saying it is important that we should apply but we'll IND think okay B search can be applied but the major fact is on what thing you will apply binary search okay you have to apply binary search that's true I'm not denying that so binary search can be applied on a number usually what you do okay my range is from 0 to9 so I apply on that range which means I'm applying on my range itself which means the number let's say if my nums array has values 1 2 3 4 5 6 7 8 so I'm applying on those number okay what if my value is 8 what if my value is 10 I'm trying for that number value itself other option is what you usually do you apply the bin search on the length itself which means okay by my array is of length 10 I'll try for smaller length array that is the other way you can apply binary search now let's see can we apply B search on the number now number is nothing but we'll just try to find mid one and mid two now how Q will find okay apply binary search on a number My ultimate aim is to find a median is itself some number which is in between it has no relevance with the value of a number let's say if you have an array 1 2 100 and 101 and 102 so 100 is the median so you saw the number difference can be a lot I'm just concerned about the length so for sure I will have no criteria okay how much number can be bigger how much can be smaller it's just that the location the length from where okay either left or right the length of that number will matter so I know that okay my length will actually matter which means the length of let say if I combine this entire array so the length of this part now how this length is obtained for sure this length is obtained half like a small portion from the nums one area of left itself and small portion of the nums two are of left itself with this I have combined this left portion and got this part so I'm just only concerned about the left portion which means I'm only concerned the length so that is one IND which we have got right now okay uh I cannot B and search on the number itself I have to search B sech only length now still we are not sure because binary search is something which is applied on that okay I have a wrong right so basically it is saying that for these lengths which because now we have to make sure okay I have to apply B search on the length itself but now I have to again make sure that okay binary search is something which we apply on okay it should for these lengths which means my length will be actually increasing or decreasing so I'm justly saying okay for smaller length it should not be valid for bigger length it should be valid so either it should look something like this or I should be able to anyhow figure out the conditions that if I'm standing on some length let's say my mid is my length so I have to increase the length I have to decrease the length I have to figure out with the help of my AR itself so let's see how we can do it now my ultimate aim has now figured that okay I have some left portion now this left portion is the length this left will be for sure fixed by how it is fixed because your entire length is of size eight so for sure your left part which means if your length is eight forget for now that if you have OD odd elements right now just imagine that you have even number of elements so if you have even number of elements for sure the left portion will have for sure four elements for sure so this will this is fixed but the thing which is variable for you is that how much of it has come from the nums one how much of it has come from the nums two that is variable for you so that is what we will apply try to apply binary search on okay that we will do but byya what you said okay left which means you will try to figure out this portion so you will say okay my it is N1 it is N2 so N1 + N2 by 2 so it is N1 it is N2 so N1 + N2 by 2 so it is N1 it is N2 so N1 + N2 by 2 so basically you are saying that left is four so did you find this four by saying 4 + 4 which means N1 + N2 by 2 how this 4 + 4 which means N1 + N2 by 2 how this 4 + 4 which means N1 + N2 by 2 how this is how you found your four I'll say yes but partially because here we only considered length as even what if the length would have been odd so if you would have done N1 let's say here it would have been five elements so still you would have got a four but you will see that okay you might have a 10 also so in the right part you will actually have more elements but you remember your median will actually be five remember because here are four so basically in case of all number of elements I should consider my left portion as this portion which means okay the elements which are actually equal on the same side and also that element itself so in case of even odd number of elements I should say that this should be my left portion size and how this is possible but just by simply saying that I will instead of taking n N1 + N2 by 2 I'll take N1 + N2 + 1 by 2 N1 + N2 by 2 I'll take N1 + N2 + 1 by 2 N1 + N2 by 2 I'll take N1 + N2 + 1 by 2 with this I'll considering left okay like if I just say N1 Plus plus N2 by 2 I will be considering only half elements let's say 5 by two would have been a two which is saying okay I have only two elements but now I'll say no worries I will have + 1 by2 which means I have will have + 1 by2 which means I have will have + 1 by2 which means I have three elements so this is the three elements so with this one formula it will handle both even and odd cases for us so that is a bit part which might be tricky again this is a problem which if you have not solved it earlier in a 45 minutes interview it's a very hard to come up it and code it at the same time because it explanation is itself very tricky and long now coming on back our main aim was to binary search on the length of left part from nums one and nums two so you will see the pink portion is the left portion from nums one pink portion is the left portion from nums two red portion is the right portion from nums one right portion red uh right portion is the right ption of the nums two now if I choose any one of them if I just choose any one of them let's say I choose this as three for sure everything else will automatically be set which means if I choose this as three right I know for sure that my length is actually a four half length is actually a four so for sure this next if it is a three it should be one to actually sum up to a four and the same way if this is three its entire length is four so for sure remaining portion is a one so for sure if remaining portion is one this is again a half length so should also be a three so I just need to do a b search on just one length any one of out of these four lengths which is this length of the left part of nums one right part of nums one left part of nums two or right part of nums two I just have to do a b search on just one of the lens that's it so now I will choose to do my search on my nums one left part now let's see that V how we can actually do it so we have just said okay uh we like we ultimately we are just trying to figure out the final array left part so for that I'll just do a binary search which means as you see mid one is after doing a binary search on the left length of nums one and indirectly I will always be able to find the left length of nums two which is left minus mid it will be the mid two which means the left length of like I will be able to figure out the left length of num two obviously the mid two I will be able to figure out with actually mid one so I just need to figure out this only with this I can easily figure out my mid to now comes the interesting part I have to start doing my binary search let's do that binary search itself so as you can see B search which means okay you will find mid but remember I am doing B search on length if I'm doing length can be either zero or the entire AR itself so my length again that is doing on nums one I will do my B search on nums one with nums one I will derive my mid two for nums 2 remember that fact okay now this low equal to Z is saying okay my length is zero this High equal to N1 saying my length is N1 remember this fact okay and it is to just showcase because I will actually play I will actually drive my mid and mid I will place at some location so that is the reason I'm just pointing okay zero is actually showing you okay it is at this index but indirectly you will see that okay it I'm doing a b SE on my length itself great so zero says I have zero length in the left portion of nums one N1 says I have N1 elements in the left portion of namsa now if my low and high are derived let's go and find our mid so simply low plus High by two again you can also say by why not low plus High minus I like low plus High minus Low by two that formula but yeah still your low and high are very small so you can just simply do this also now low and high by two you get your two now two is your mid one okay mid one now this says that in my left portion I have two elements but I will have to handle indexes right I have to handle indexes like my array is index based so the that's the reason I just plotted my on the indexes itself mid one is mid one came out to be a two so I just plotted here itself two now you remember that your left portion has only two elements right so now I and again because of this mid one I will always be able to figure out mid two so mid two is left minus mid one because mid one is saying okay in nums one left number of elements are mid one so for sure in mid two left number of elements will be total elements in the left minus mid one which is 4 actually two so again my mid two has been there now I have figured out my mid one and mid two by just mid one now comes the interesting part I know my mid one is here I know my mid2 is here which means my left elements are two elements my left element El are two elements in nums two which means my right elements are these now comes the interesting part that if you have to plot these elements how will you plot this you have a one two right so let's imagine that you are you like you will have these left part as sorted right part as sorted and you have to combine that part why we bifurcated this part we just said okay I will sort my left part I will sort my right part can I combine them so imagining if my left part is sorted okay it is 1 two it is 3 4 I have sorted this left part right 1 2 3 4 1 2 3 5 it is sorted let's say my right part okay 3 77 9 it is also sorted as but you will see it is num one it is num two so just to you for you to imagine I just put it like this now to actually know if I combine them now combine them which means now after combining I cannot sort them I'm just saying okay this part sorted this part is sorted is it possible to combine them which means this should be less than your three right that is what it case and also byya again okay for now your nums two part is like in the end but what if it would have been some smaller number one then you would have said okay it should be less than this number so now we have imagined that we will have two conditions our L1 should be what is L1 simply you remember your mid was pointing here so nums one of mid one will be R1 right nums one of mid 1 minus one will be L1 and the same way nums two of mid2 will be R2 and nums two of mid2 minus 2 will be L2 so basically I'm saying indirectly that okay this is my L1 element it is my L2 it is my R1 it is my R2 now I have got this L1 L2 R1 R2 now when I have this L1 L2 R1 R2 I just say Okay condition for after combining for it to be sorted should be that L1 should be less than equal to my R1 and also L2 should be less than equal to my R2 only then my array after combining will be my sorted array so now I have said okay this is the condition for it to be sorted so now I'll check is this above thing B which I have made by doing a binary search on the length ex said this valid or not so I'll see um maybe it is not but I'll see that okay five is not less than equal to 3 5 is more than three which means it is not valid this is not valid so what we have made right now it is not valid so because you remember I was planning something like this and for sure this thing is not valid only and only because of five is more than equal to three and it should have been less L2 should have been less than equal to my R1 but by why you did not check L2 is than equal to R2 because L2 is sorted this thing is already sorted so for sure you don't need to compare that you just only need to compare the diagonals because horizontal are already sorted so this is the condition now byya depending upon the condition how would we know that where we have to move left or right because ultimately buying SE is okay you have this value where are you planning to move left or right that is what you have to figure out so I will just say that um I will have a low I will have a high I got a mid with this above scenario I have got something like this now here you remember my L1 was less than equal to my R2 now this was not following right which means for sure that I have to shift my left to this part such that three should have come here then I would be comparing with my nine so oh you and again by why you did not moved your n to like why you did not moved your like your value in nums 2 because if you remember I was saying I'm applying my operation on nums one itself so if three is there I can like I can apply operation on above nums one add itself because I have just want I'm just doing a B on nums one with nums one help I'm applying or basically saying for nums 2 that is what I was doing so I can apply operation so if this is not handling if this is not being handled which means if you're L L2 is less than equal to your if L2 is less than equal to your uh R1 then okay but if it is not which means you have to shift your value to the left which means your left will come here right because it's a pointer left will come here so now your left portion will actually be increased so I'll just do the same thing if my L1 is less than equal to L2 which means okay L1 is less than equal L2 now because if it is invalid so for sure if this is less than equal to L2 which means L1 is less than equal to L2 which means it's a valid condition but I am I'm counting for invalid ones so for sure I will compare and I will see which means this would have been invalid so simply move your L1 to the right so I'll do a low as mid plus one and vice versa true for high equal to Mid minus one again a recap that I will be doing a binary on the nums one so I have to move my L1 and high like low and high of the nums I know that if L1 is less than R1 so for sure it is correct which means this would have been incorrect this L2 less than equal to R2 would have been incor in incorrect thing so for sure what I will do is I will have to move my low to mid + one low to mid + one and low to mid + one low to mid + one and low to mid + one low to mid + one and same vice versa will happen for if L1 is more than equal to R2 then I'll move my as midus one and that's how I can simply solve it so now we saw that because of our L1 is less than equal to our R2 which means for sure L2 would have been more than equal to R R1 so I will have to move my low forward such that the new Left range would have become the further range what we mean by that is our low will move mid Plus one mid was actually if you remember it was two like it was pointed to a location two index two if we go up it was a two so I will do a mid + one so my low will become a mid + one so my low will become a mid + one so my low will become a three high would for sure be as it is so my new MID would be a three again because of my new MID I can easily find my new MID two again left minus mid 1 4- my new MID two again left minus mid 1 4- my new MID two again left minus mid 1 4- 3 actually one so now my mid one is three seeing I have three elements in the left pointing to our index 3 and mid two is a same one El in the left and po to our index one now mid one is here mid two is here now let's see that how will our new array look like as I said I will have left elements 1 2 and 3 left elements 1 2 and three left elements just a three left element just a three right elements from here is 577 57 7 right elements from here is a nine so now you will see okay what happened because of moving my low pointer in forward number of elements here increase because of increasing number of elements here number of elements in nums to decrease number of elements in nums two decreased and because of decreasing of elements the value will be lesser because elements are decreased which means elements will go leftwards if they go leftwards which means elements are decreased as in I have less number of elements which means I will have lower smaller number of elements here and I will have larger number of elements here so for sure you will see that three is now less than equal to 9 like less than 9 and same way I also have to check L1 because it might happen because of this decrease this might end up increasing that's also happening so that's reason I'm using a binary search so I just say okay this is less than this that's true this is also less than this that's also true which means it is a valid case now if it is a valid case I would know that if L1 is less than equal to R2 L2 is less than equal to R1 which means it's a valid now if it's a valid again we have to condition we have to find mid right mid will be nothing but if it's odd which means if it is actually a odd length so I'll just do a maximum of l1a L2 else I'll just do a maximum of l1a L2 Max minimum of l1a L2 and then I'll just do a by two now byya uh what you did here okay we understood that okay it is odd or even so you will do uh you will just get one element and you will take the average of two elements but how you wrote this formulas so if you remembered I said specifically that if my length is odd 1 2 3 5 let's say if my length is odd so I will be taking my left portion like this right when my left portion is like this so one thing is for sure that I will be having my L1 and L2 which means if I bifurcate this array let's say it is becoming like okay 1 2 3 and let's say 3 5 let's say I IET this array so for sure my L1 will be here L2 will be here or maybe L let's say the entire thing is here so for sure my let's say here is L1 and below is L2 so my L2 is actually null which means Z so one thing is for sure I am taking the maximum of what L1 or L2 would have got because L1 L2 are pointing to the left portion now left portion is nothing but this entire left portion so L1 or L2 left portion if just left portion I'll just get the maximum what's the maximum will be this element extreme left element in the left bar so I'll get the maximum of left one left two but by what about this simple as you remembered if I had this array in the left so I will have L1 here I will have L2 here if I have L1 here L2 here simply you remember these elements if I have to write oh that's a three and that's a five so what we can do is okay we know that this is the left portion so I will just simply go and grab the maximum from the left portion okay it will give me the maximum from the left portion because you'll see left portion is this maximum from Maximum from the left portion is this is the right portion this is the minimum of the right portion so I will go and grab the R1 and R2 and take the minimum of the right portion and thus my answer will become maximum of l1a L2 and minimum of r1a R2 I was actually like that's a type in here but yeah that's a minimum of R1 R2 and just by two by this you will get the answer for you now what we have seen in this is now we'll Club the entire code how we Club the entire code we will say that I have N1 I have N2 now if my N1 is more than my M2 then simply I can just swap it which means I'm just saying that I will just always try to make sure that my N1 is less than N2 so that is just for my safety so that I can I will have lower number of comparisions but why because you saw that you are doing a binary search on your nums one so if nums one you will try to keep it small so your binary search length which means log portion will also be small so here I'm just trying okay I'm doing a b search on the smaller length itself that is a small optimization again that's not a big optimation that's a small one which interviewer might actually feel good if you do it now comes the interesting part I will find my left it is a left length as I showed you it is again I had options of N1 + N2 by2 also again I had options of N1 + N2 by2 also again I had options of N1 + N2 by2 also but then I said N1 + N2 + 1 by2 will but then I said N1 + N2 + 1 by2 will but then I said N1 + N2 + 1 by2 will handle both the cases for all and even so I did like this okay great now I have my low I have my high low is the length left nums one left portion minimum length it can be zero nums one right portion minimum length can be N1 but I wanted to have indexing that's the reason I will just showed you as indexing also and also so like showed that okay it's actually a length now I just went on a simple B search now how B search works you just do a y low is less than equal to high again it depends if you do a less than then you have to modify the conditions but I usually do a less than equal to I do this then I find my mid and the condition comes here and if it is satisfying then it is either mid plus one or mid minus one that is the B search standard template now comes on that what are the changes which we have done we have just found out our mid one is nums one portion saying okay mid one is nums one like mid one which is low plus High by two same mid two I can drive from mid one which is left minus mid one okay now I have got mid 1 and mid2 now I will have to find my L1 L2 R1 R2 so L1 L2 minimum R1 R2 maximum because I want to maximize this I want to minimize this that's the reason now these conditions as I showed you in the beginning also that if your mid is less than your N1 then only you can just say okay your R1 is actually nums one like nums one or mid one if you remembered that if you remember here itself when we have to derive what are all our values of mid one Mid 2 nums one nums two we said the same thing um where is gone yeah as you remembered R1 is nums one of mid one L1 is nums one of mid 1us one so now I'm just saying that okay nums one should not like mid one should not be zero mid one should not be in so it is a like standard check to actually validate that I should not get a runtime error so I just did a standard check okay mid one if it's less than L1 then only I assign my R1 I assign my R2 L1 and L2 right now when this is done again if you might have seen okay like I'm looking at this phone because uh I'm getting some calls um and I just don't want to I forget my time so I'm just said one thing okay now I have seen that my L1 L2 R1 R2 are with me now what where we have to move that will depend upon the condition which I saw firstly is it even required to move that we'll check okay if L1 is less than equal to R2 R L2 is less than equal to R1 which means it's a bad condition now just go and return okay if it's odd length like return maximum of L1 L2 if it's a even length return the maximum of L1 L2 plus minimum of R1 R2 by two okay but if it is not a valid case then okay as we discussed that if L1 is less than R2 which indirectly will mean that L2 is more than your R1 then you have to move your low to mid plus one and vice versa you'll do for high equal to M minus one and that's how ultimately you can return your zero if you don't return from either here or here right and that's how you can simply get this solved in your o of log n time or o of log M time whatsoever is small n or M and space is also over fun and that's how again it's a torture question but yeah it's a very good question for you to be ask it has many follow-ups with amazing mindset of many follow-ups with amazing mindset of many follow-ups with amazing mindset of binary search two pointers and a basic brot Force also cool than Again by
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
739
hey everyone in this video let's take a look at question 739 daily temperatures on Lee code this is part of our blind 75 list of questions so let's begin in this question we are given an array of integers called temperatures which represents the daily temperatures we want to return an array answer such that the answer of I is the number of days you have to wait after the I today to get a warmer temperature if there are no such Future Days in which this is possible we will keep answered I as zero okay so let's take a look at what this question is saying to these examples here we have these examples here nope what is this question saying well first of all I will actually just order the days right so I will say something like this is day one day two three four five six seven and eight right so these are our set of days and so for 73 what is the next day that is warmer right well it would be this one right it would be 74 is the next warmer day and we can see that's day two and we're day one so we will add in one to our answer what about for 74. well again it's like the next day right so it is 3 minus 2 which is one after 75 the next warmer day is actually this one the day 76 right or the day that has temperature of 76 which is day seven so we have seven minus three which basically means that we have to wait four days you can basically go on and then eventually like you see for 76 we actually don't have a warmer day and same thing for uh temperature 73 at the last index here we don't have a warmer day and you can similarly follow the logic over here you can see that our answer should be one and zero and then similarly over here okay so what does this question kind of remind me of well if you think about what this question is saying we want to basically find like the next warmer temperature right and if you think of this in terms of uh like a more generic problem temperature in order for it to be warmer it has to be greater right it has to be like we can say that temperature six is greater than four for example so essentially what I'm being asked to do here is I'm being asked to find the next greater element right that's all this question is I'm essentially just finding the next greater element so for next greater element for 73 it would be 74 at 75 for 75 it is 76 Etc right I'm just being asked to find this but instead of returning this I'm returning like the difference here like how many days right how many days has happened so we've actually already done a problem like this we've already done the problem next greater X greater temperature or whatever it was called uh next what did I call it I forgot what I called it but it was next greater temperature something like that right so we've already done a question next word element that was the question X greater element one so it's exactly the same as that X greater element one it's exactly the same as this question but instead of returning this temperature here we're actually just returning the difference here and if you remember how we did this question we used a monotonic stack specifically a decrease in monotonic stack why because whenever you want to find the next greater then you have to use a decrease in monotonic stack if you want to find the next lower then you have to use an increase in monotonics back so I'm not going to go through the entire monotonic stack logic again but if you want to learn that you can go to the next greater element but I've tried to basically just summarize it as we're doing this problem here but really it's all this it's all the same it's exactly the same so why don't we go ahead and start off with the monotonic stack idea and maybe we can start off by finding the next greater element and then we can maybe modify our algorithm so that instead of our next greater element we will return like the difference here right so maybe let's go ahead and start off with the next greater element and then we can modify to return the difference okay so I would just call this temps right temperatures it's later along so how might we go about doing this well first thing we need to do right is we want to restore a result variable and our result variable we can just start it off as like an empty list right we don't need to do anything right now what do we want well we need to go through our temps array right so for Iron Range zero to length of temps and we also need our stack here but we will have our stack this is our decreasing monotonic stack so now what well now we need to determine if I can pop elements off the stack right so that's the first thing we do either determine and pop and then here add to stack okay so if we can pop how can we determine if we can pop or not well in order for us to pop from a decrease in monotonic stack we must break the structure right we must have something where it's like five and one and then we try to add on something like a three which in this case is like breaking it because it would break the moneticity so in this case we can check biostack and stack at -1 is less than or biostack and stack at -1 is less than or biostack and stack at -1 is less than or sorry it's less than yeah is less than the number we're just about to add which is temp set I if this is the case then I can go ahead and pop from the stack so I can do item is equal to stack.pop so in can do item is equal to stack.pop so in can do item is equal to stack.pop so in this case what we would be doing it will be popping this one here and then what does it tell me it tells me once next greater element is three in this case the day or the temperature that is the next greater one from the current temperature is three it's three degrees so that's what it would tell me we go ahead and do that and then well we would need to like store this information somewhere right so here we can figure out like um store this information so we would store this somewhere and otherwise we would just add to the stack right so here we'll do stack dot append and said I so what we can actually just do here is we can actually just add this to our res so we can do res dot append what do we want to append well we want to append uh like the individual the answer now if you think about this one we will not necessarily be processing like this array like and like return to result in the same order right because here what we're doing is I figured out the answer for one but I don't know the answer for five yet so it wouldn't make sense for me to just add to the result array just yet so maybe instead of actually adding the element why don't we add the index because if we add the index and what we could do is we could maybe set result we started off at all zeros right length of temps started off at all zeros and then instead of adding Temps at I we can just add an i which means this instead of Stack it minus one it would be stack at -1 so minus one it would be stack at -1 so minus one it would be stack at -1 so this will actually give me the index right and then I will figure out Temps at this index and then this item that I'm popping it's actually not an item it's more of an index and then what I could do is I could do result at index is equal to well this item that I just popped which is are the item that I'm just about to add so this will be temp set I so let's take a look at what this does and I will just print temps.i or not and I will just print temps.i or not and I will just print temps.i or not temp side I will print uh yes I'll print temp Set uh result I'm sorry I'll print result in the very end and then I can just return like an empty list like this so let's take a look at what happens here so maybe I shouldn't have run all the test cases I'll just run the first one but let me just return this run this first test case here okay so you can see that we're actually getting the proper answer the next proper the next clear element is 73 is 74 then a 74 75 then here it's 76 which is all the way here Etc now we're almost there we're almost at the solution but notice that we don't want to add in the next greater element right we want to add in the amount of days that it's been since this next greater element right and if you notice because we have access to the index we can actually very easily do this why well if we have access to the index then we know the index like this index that we just popped right so we know the index that we just popped and we know the current index also so all we need to do now is we just need to store the difference so instead of temp set I here what I can do is I have this index here and I know this index it must be somewhere in the future right it must be one of the Future Days what I can do is I can do index minus I that should be my answer and I might actually have to do plus one here depending on how they do their question but let me just see so I've actually just run this example test case okay so we get minus one minus four minus two so we get the correct answer but it looks like the order is different and I made a mistake I said that this is in the future it's not this is actually in the past because this is what was just on the stack so the future is actually this here I it should be I minus Index right and then looks like that's actually will fill up the result array so we can actually just return result we'll go ahead and remove this so now let's go ahead and run the test case and we can see that it passes we'll run all of the test cases you see that they pass and then we can go ahead and submit and perfect we arrive at the answer so this is the O of n time answer and o and n space answer as well so let's go through quickly what we did here that was different than the next greater element well we had a couple of differences right first of all we added the index instead of the item right so we added in the index why did we add in the index well often it's actually easier to just add in the index because from the index you can figure out the element you can also do like interesting things like figure out the difference like in daily temperatures just as we did here that was like one difference we did otherwise like when you add the index he refilled the resume right so when you add the index another Advantage is that you don't have to process items in like the order they came from a next greater element like we had a specific order that we wanted to follow so that's why like we were able to just go ahead and like we did it um using just the item itself but if you don't have to do that if you have access to the index then you can fit out as they come about like if we have something like this if we have like this one here then I can like fill out this in the answer array whenever I get the index of this one right so that's another way in which we can just use the index so in the future it's probably just easier to just to use the index instead of like the actual item itself but that's just something to keep in mind anyways I hope this question um will useful and it helped
Daily Temperatures
daily-temperatures
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead. **Example 1:** **Input:** temperatures = \[73,74,75,71,69,72,76,73\] **Output:** \[1,1,4,2,1,1,0,0\] **Example 2:** **Input:** temperatures = \[30,40,50,60\] **Output:** \[1,1,1,0\] **Example 3:** **Input:** temperatures = \[30,60,90\] **Output:** \[1,1,0\] **Constraints:** * `1 <= temperatures.length <= 105` * `30 <= temperatures[i] <= 100`
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
Array,Stack,Monotonic Stack
Medium
496,937
202
hello welcome back to my channel today we are going to discuss the solution to the second problem of the late code 30 days coding challenge the name of the problem is happy number the problem description says that all right it will go to them to determine if a number is happy a number is defined by the following process starting with any positive integer replace the number by the sum of squares of its digits and repeat the process until the number equals to one so the given example is 19 so what we have to do we have to take the square the squares of the digits so in this case the digits are 1 and 9 in fact to take this square so 1 square plus 9 square which is equals to 82 again if we repeat the process it will be 64 plus 4 which is equals to 68 repeating the process will give us 36 Plus 64 which is equals to 100 now if we repeat the process then we get 1 in this case so 19 is a lucky number because eventually it is ending up in 1 next we take another example let's say the number is 4 initially now if we do the same process on this we may be getting 16 then we will be getting 36 plus 1 which is close to 30 7 then 9 plus 49 58 then applying the same process 25 plus 64 89 then 64 plus 81 5 145 then next we will get 1 plus 25 plus 16 46 16 plus 36 wait a second 25 plus 16 plus 1 6 it is 42 this 42 then we will get 16 plus 4 which is equal to 20 and next you will get 4 here so 4 is again reappearing next step we will be adding 16 then 37 then 58 89 145 42 and 20 and this cycle will keep repeating itself and it will be eventually an infinite loop so this problem basically converges into the problem of finding a cycle whether or not there exists a cycle so either the number is going to end in 1 or there will be a cycle in the process so this is basically a cycle detection algorithm we have to apply the cycle detection in order in this problem so we can either use set here or hashmaps to store the numbers which have which we have already encountered and if a number appears again then we can return false in those cases and another approach could be to use Floyd's cycle detection algorithm in which we keep this flu and the first pointer and we move the slowed pointer by one step each time and move the first pointer by 2 step so there is a mathematical proof that in for each number if it is not a happy number there will be a cycle I will provide the proof in the description it is a theoretical mathematical proof you can go through it once another one the fluid cycle correction algorithm I will also provide the link to that so if you don't know that algorithm you can refer to that video and later on solve this problem now let us look at the code so this there's a helper function which is going to return us the sum of the squares of the digit of a number and this is the froy cycle detection algorithm which i am using here so there's a slow pointer and a fast pointer the fast is moving one step at a time and slow the slow is moving one step at a time and fast is moving two steps at a time so when they are equal we will get out of the loop and if slow is equals to one we will return over answer so let me try to do that we'll try to simulate the process for this particular number 19 then 82 then 68 then 100 then 1 okay now there's a slow pointer in the first pointer one step slow a move here first we'll move here then slow we'll come here and fast fill here slow we'll move to this point and fast will remain on one because square of 1 is 1 then again square of 1 is 1 and slow will come here in the very next step now this is the point when slow is equals to fast and it will hit the exit condition of the do-while loop so slow condition of the do-while loop so slow condition of the do-while loop so slow is equals to 1 hence we are going to return true in this case when we try to simulate for this let's turn the first pointer I think it will end up somewhere over here and slow is not equals to 1 so we are going to run Falls in that case so the link with the floyd-warshall so the link with the floyd-warshall so the link with the floyd-warshall algorithm and the mathematical proof will be given in the description please go through it once if you liked the video please share it share the video with your friends and please like and subscribe thank you
Happy Number
happy-number
Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squares of its digits. * Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. * Those numbers for which this process **ends in 1** are happy. Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. **Example 1:** **Input:** n = 19 **Output:** true **Explanation:** 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 **Example 2:** **Input:** n = 2 **Output:** false **Constraints:** * `1 <= n <= 231 - 1`
null
Hash Table,Math,Two Pointers
Easy
141,258,263,2076
387
hi my name is david and we're going to do elite code problem easy level first unique characters in a string and we're going to do it in javascript given a string find the first non-repeating character non-repeating character non-repeating character in it and return its index if it doesn't exist return negative one so for this example the string of s is equal to the elite code and we return zero because that's the first index of the non-repeating character index of the non-repeating character index of the non-repeating character so let's begin so first what we're going to do is that to keep track of everything we're going to create an object so create object and call our character count and the purpose of it is to keep track of all the characters in the account for characters as the key count asset value and after that we'll have to loop through the string through s and inside of the loop we will have to create a condition so the condition we want to see is that character inside of the object if it's not we will add it to the object and the first character it won't be in it so we'll have to do it and then if it sees it again we'll do something else we'll increment it so we'll have to create a condition to see if the current character in s is in the object character count let me put and if it is inside of it we alright so first we're going to do is we want to have it if it's not inside of it if not we add it to the object we add the key of current character and a value of 1. and then we have a condition if it is in it current character is in s is in this we increment this value by one so we're doing this to keep track of all the characters and the account and now that we have it due we'll create another loop to see which one when the first time it appears as a non-repeating loop through s and then we create a condition to see if the value of that current character in the object is equal to one in the character count and if it is we return the i the index value and then if we loop through it and nothing is happens it doesn't find an a non-repeating character we just return a non-repeating character we just return a non-repeating character we just return negative one okay when kodo it makes more sense so first we could create the object that character count and it's equal to an empty object next we iterate through the s for let s equal zero s is less than i again these letters confused i is less than s dot length i plus and now we check if it's inside of the object if so if it's not in it first if character count s so that will get the value we need if it's not in it we will add it to the object we'll add it and now we do the opposite of it if it is in it we just increment it by one and now we'll get the finish with the object the create an object now we have to loop through again to see the first time it repeats and then we create the condition if this is equal to one we return the index i and nothing else if it's not in it we return negative one let's check nice we got it so the time complexity were doing loops but they're not nested so it's going to be of n and the other one space would be also oven because we'll create an object that depends on the length of n and that's it thank you
First Unique Character in a String
first-unique-character-in-a-string
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. **Example 1:** **Input:** s = "leetcode" **Output:** 0 **Example 2:** **Input:** s = "loveleetcode" **Output:** 2 **Example 3:** **Input:** s = "aabb" **Output:** -1 **Constraints:** * `1 <= s.length <= 105` * `s` consists of only lowercase English letters.
null
Hash Table,String,Queue,Counting
Easy
451
11
hello everyone let's do lead Code 11 container with most water so we're given an array of heights where each height represents a vertical line so as you can see here in example we want to find the maximum container that we can create using these vertical lines basically the maximum area we can fill with water so in this case is this blue area here let's look at this example in this case the biggest container that could have been created is this one highlighted here so the height of this is 7 and the height of this line is eight so basically the length of this is 7 and the maximum height is the minimum line because if we added more water here you would have overflowns or spilled dollar so the height is 7 and to find the area it's basically seven times seven which gives us 49. this is how we got this output 14 9 the first service solution would be to use brute force basically we would calculate the error for each possible combination we would have two pointers let's say a left and a right we would first calculate the area of this container this area is one we would then move right over here calculate the area of this container here in this case the area is 2 which is greater than the previous one so the current Max area Max so far is 2 we would move R again so the container gets bigger but as you can see we are bounded by the smallest height in this case which is one so when we're gonna have R to be at the end no matter how big this height how big this line is the maximum area in this case is going to be nine now we need to move left will be here now and R will start here we can see the maximum area is this one and the value is the minimum height in this case is 6 times the width so it's one the area that is covered is six so it's not greater than the maximum we found earlier so we leave this unchanged we move R again R is going to be here this time so this area is now 4 which is still smaller than our Max and eventually when R is gonna reach this position again we will have found our maximum area in this case 49 The Brute Force solution is probably not going to be enough to pass the lead code automated tests so the time complexity of this solution is N squared and the memory complexity is of one because you are not using extra memory there is a linear time solution let's build up on the Brute Force solution we were looking earlier we can take some ideas from that basically we need to have two pointers a left pointer starting at the beginning and the right pointer starting at the end we are going to use these two pointers to calculate the maximum area by just going through the input array once let's look at an example this is the initial position that is going to be at the beginning and right at the end and this is the maximum area container that is going to be formed we're going to save it in a Max area variable Max so far is going to be 9. we now want to move the pointer in this case left because between the two it's the one with the smaller height and we want to do this because we hope that the next one might be of a bigger height so left is gonna go here now we're going to compute the area again in this case the area he covered here is 49 so our new Max is 49. we know that this is the right answer but we still want to carry on now we want to move again use the same rule move the point enter with the smaller height in this case right is not going to be pointing here and the Ada covered by this rectangle is 18 is not greater than 49 so that's going to stay and change until the end as we know we are going to move R again R will be now here they have the same height but still the maximum area is not greater than 49 what we're gonna do in this case this is one of the edge cases we can either look at the next height or we can just pick randomly and move either pointer let's say we are going to move Left Right will stay there at the end we will be in a situation similar to this one where Ali is going to be at the same position as R and this condition will allow us to break the while loop and actually return whatever the current Max is in this case 49. this is a two pointer solution the time complexity is all fun because we will just go through the array once and the memory complexity is O of one its constant memory we are not gonna we're just using two pointers let's try some code now so we need two pointers left and right left is going to start at zero and right is gonna start at the end of the array we are also going to initialize a variable that is going to contain our result at the end so max 8 equal to zero we need a while loop and the condition is going to be while L is smaller than R we need to calculate the current area so which is going to be we need the width of the base which is going to be right minus left pointer times the height of the minimum line because we don't want to spill water so we can use the mean function of python we now want to update the current result we want the maximum area so the max area could be the new one or it could still be the previous one so we'll just use the built-in one so we'll just use the built-in one so we'll just use the built-in function Max we won't update the pointers we can use the simple if so if height of L is smaller than the height of R we are simply going to move left pointer by one hoping that the next position is going to have a greater height otherwise we'll just decrease R this will also cover the edge case where both are the same and at the end we can just simply return Max area let's see if this works as you can see it does work please like And subscribe if you found this video useful thank you
Container With Most Water
container-with-most-water
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`. Find two lines that together with the x-axis form a container, such that the container contains the most water. Return _the maximum amount of water a container can store_. **Notice** that you may not slant the container. **Example 1:** **Input:** height = \[1,8,6,2,5,4,8,3,7\] **Output:** 49 **Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49. **Example 2:** **Input:** height = \[1,1\] **Output:** 1 **Constraints:** * `n == height.length` * `2 <= n <= 105` * `0 <= height[i] <= 104`
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle. Area = length of shorter vertical line * distance between lines We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
Array,Two Pointers,Greedy
Medium
42
523
Today we will talk about lead code question 523 continuous basis, all the questions are talking about one wait and whether to return true or false, but when to return true, we see that if If there is any morning whose sum is divided and if the reminder comes then zero should come, that is, if there is any morning whose sum is being divided then how to divide then return has to be done. Yours should be of Tu size. Let us look at this question carefully on our white board. From this, you will understand well how to do this, so like man lo, this morning has been given to you, that means you have been given this Now, like man lo, the time from here till here is S1 and if he How to do our modules so the reminder is okay and from here to here is S2 and the reminder of that is also k plus k in tu n plus r because that's your all this is all S1 a so S1 If you had divided by your then only then there is a reminder, it is okay and now if you do S2 - S1 then only okay and now if you do S2 - S1 then only okay and now if you do S2 - S1 then only this sum will come from here till here. Is this total correct? If we remove all the further S1, what will happen? K * M - N Okay, so it means that it is happening like this, we will take all the variables, okay and what will we do, we will start doing sam from the beginning and will take us, if C is plus, then what will we do, as if till now, if our If we look at this, then look in this one, we have named it ' then look in this one, we have named it ' then look in this one, we have named it ' spectre', now it is spectre', now it is spectre', now it is not here, what have we done that it is 23rd, so it is okay on 23rd August and what will be its reminder, the value of our key which is six. So, if we take a reminder from six, then our 5 will be equal to 5. Okay, we will divide 23. Here, if we keep doing this in the same manner, then we will get the idea. Now let's see once through our Ford, then add a little more here, then you will understand better. If it comes properly, then if you look at your code, then you have created it, okay, from the time the reminder starts till the time I come in the morning, the reminder is zero, okay, so that means that reminder should be zero, I take it that your key value is six and that is yours. It becomes 6 and 8. Okay, so you see, the value of A is 6, so 6. Look, what is the size of this morning, but how is it being divided, everything of this morning is being divided by Sam's six and six, three. The size of the sabre is 1, so it cannot be taken, okay, that's why I have made I note equal to zero here so that the size of van length does not come at this place, okay, and if the reminder is zero, then I have done it now, I note that your What is there in the map, I have already got the reminder, right, now the reminder has come, so what did I do that my eye is up to this index and this eye is also there and what is the reminder if he sees it, what is its length, if he Give it greater or should be equal to 2, only then we will proof the return. What is this? Look at your code again, you will understand it well there. Now look here, I had put this five whose index I had given as 0. Okay, now my Here again, put my van here and gave the index team. Okay, reminder till here, whatever you see from there, news from here till here.
Continuous Subarray Sum
continuous-subarray-sum
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_. A **good subarray** is a subarray where: * its length is **at least two**, and * the sum of the elements of the subarray is a multiple of `k`. **Note** that: * A **subarray** is a contiguous part of the array. * An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`. **Example 1:** **Input:** nums = \[23,2,4,6,7\], k = 6 **Output:** true **Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6. **Example 2:** **Input:** nums = \[23,2,6,4,7\], k = 6 **Output:** true **Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer. **Example 3:** **Input:** nums = \[23,2,6,4,7\], k = 13 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= sum(nums[i]) <= 231 - 1` * `1 <= k <= 231 - 1`
null
Array,Hash Table,Math,Prefix Sum
Medium
560,2119,2240
63
okay hello everyone so today we're going to solve this lead code problem 63 and the name is unique paths 2 and it's the second variation and if you want to well there's the first relation as well which has the name as unique paths only unique paths for unique paths one if you want to check that problem solution then you can follow a link in the description so now as of now we're going to discuss this problem and it's a pretty standard problem let's say and it's a medium level question let's see and one thing more uh for interview standpoint the this problem is very standard and is actually observed that this problem has passed in a lot of interviews so let's see you're given an m cross in integer array grid okay there is a robot initially located at the top left corner which means that if this is the grid then the robot is located at this point that is the top and left corner that is did 0 right this is the zero point and the robot tries to move to the bottom right corner okay so this is the goal this is the start and this is the goal state the robot can only move in either down so if this is the robot it can only move in either down direction or right direction at any point of time an obstacle and space are marked as one or zero respectively in a grid okay i think this one is a variation in the second part in the first part as you can remember there were no obstacles but in the second part there are obstacles which are specified by one so a path the robot cannot include any square that is an obstacle okay which means that if we are following let's say we are following this path and this power should not have any obstacle let's say that there was an obstacle in this case so this path cannot be followed and because of that we have to follow another alternate path that is this one let's see uh return the number of possible unique paths that robot can take to reach the bottom right corner okay the test is well let's see uh i think this problem could be better understood by analyzing an example so this is the robot this is the start position of a robot and the robot wants to go yeah and this is the start position and the robot wants to travel to this one that is the goal state and the it has a lot of paths first of all the robot can go in this way this is the first path then robot can also go from this path as well right but sadly the robot cannot go from this path can you answer me why well obviously because there's an obstacle let's say because of better understanding the example has shown that the obstacle is like a rock or a boulder which cannot be passed so because of that the robot cannot go from this direction to this path because there is an obstacle and the robot also cannot go from this direction to this direction because there is an obstacle so there are only uh well this is not just one path there can be multiple but as of now as of what we can observe there are only two parts right and i think it makes sense because any other path none of the other path can be followed because there is an obstacle in between so this is the problem so one naive solution to this problem could be that you are at your zero comma zero state and now you have two decision and why you have two decisions because the question specifies that you can only move where was it yeah you can only move either down or right which means that you can only move in this direction that is the right direction or in down direction so let's say you are at this block so you can move in this direction or in this direction although we cannot move in the right direction because there is an obstacle but what i want to say is that the freedom to move is only two cases that is either you will go in the cell that is below the current cell or the cell that is on the right of the current cell so now you have two options so from zero to zero uh let's say i'm going to mark each and every this is zero comma zero this is 0 comma 1 this is 0 comma 2 this is 0 so 1 comma 0 and 2 comma 0 and this is 1 comma 1 one comma two comma one and two comma two let's see so if you are at one zero comma zero you have two options so the first is either you can go down or you can go right so if you go down then you will end up at one comma zero right so now at one comma zero you have two options either you can go down or you can go right well you will go down so you have two comma zero and add two comma zero either you can go down or you can go right well apparently the down is not possible because that's like an out of the boundary of grid so you will backtrack to it and then you will follow the right path and the right is 2 comma 1 and again at 2 comma 1 either you can go down or you can go right well the right is not valid because then you will out of the boundary of grid so you have to backtrack and choose the right one that is two comma two and now the cell or the value that is the cell that we are currently on is two comma two that is the goal state and because we are on this cell so i will say that the path is now following this direction right so let's see what is the path so you traveled yeah so you traveled from zero comma zero then you went on to 1 comma 0 then you again go to 2 comma 0 and then 2 comma 1 and then finally 2 comma 2 so this is the path let's see so zero comma one okay one comma zero okay two comma one okay two comma two well that's a valid path that's very great because we have uh completed a valid path are there any other parts as well of course there are other paths and we have to return if you remember we have to return the number of possible unique paths that the robot can take to reach the bottom right so this is one of the unique paths that we yet has to that are yet to be calculated so let's see uh yeah after backtracking this right we are done with this then we are done with the 2 comma 1 and now we are done with 2 comma 0 and then we'll backtrack to this one so on this part we will see that we have to reach the right part so at 1 0 the right is not possible because there is an obstacle so we are not going to continue it then we will backtrack to 1 comma 0 sorry 0 because 1 comma 0 is also completely executed or completed the control has been followed to the end of the function so now we are back to zero comma zero and at zero comma zero we have the choice to move down or right and we have used the first trace that is to move down now we will move right so we will move zero comma one right so now i'm moving in this direction just remembering and from this choice we have from this point we have two choices again that is down or right and i will say that i will go down well i cannot go down because uh one comma zero then we have one comma from zero comma one we have in downward direction we have one comma one that is an obstacle so we won't be traveling here right because one comma one is an obstacle so we won't be traveling here we won't be traversing this cell and then i will say okay if i cannot go down then i have the other option that is right let's see then i will go zero comma two well yeah it's not an obstacle so we can go to this one then at this point i have two options that is either down or right so i will say that uh yeah i will say i will go down let's see one comma two okay and then i have another option that is down or right i'll say i'll go down again and two comma two so we have reached again we have reached a goal state and now we have another path that is this one right this is the another path and if you wondering what's the path exactly this is the bulk and then i will backtrack to one comma two and then i have to take the right one well i won't be doing this because it's an out of bound thing we are going out but out of the boundary of the grid and that's not acceptable and then at 0 comma 2 we cannot go right because that's an again an out of boundary option so this won't be done as well and now we are done with our question so i can say that i have encountered 2 comma 2 two times which means that we have two different two unique paths right and that is our answer for this example uh well if you can understand that this whole scenario is going to take exponential time right because we have a whole recursive tree that is forming up and we are traversing each and every possibility and if you will also look closely you can see that there are some overlapping problems let's see okay yeah so let's see do we have any overlapping problems or not actually in this case we don't have overlapping problems because the paths were very different right like this 0 1 0 and then 2 0 2 1 2 is a whole different path and this one is whole different path but believe me uh if you will take another example let's say that we have five cross five grid or six call cross five grid in that scenario if you are multiple or just one obstacle in between then you will have multiple paths that are overlapping with each other and in that scenario you can easily conclude that there are some overlapping paths the paths which are using same cells like um two different paths are using some same set of cells in their path in their you know trajectory which is like an overlapping problem and when a recursive problem is an overlapping problem in that scenario we have an optimization technique for this whole case that is db or dynamic programming right we have dynamic programming for this one let's see how we can solve this question with dynamic problem programming and by the way for this solution the time complexity will be 2 raised to power n where n is the number of cells which is n cross m right so this is the time complexity which is um very slow and it's not acceptable in introducing any case like that so we have to come up with some optimized solution and the optimized way is let me copy this diagram or image yeah so the optimized way to solve this problem is to keep a track of how many ways do we have for each and every cell let's see at this state at the starting state how many ways do i have to reach a cell like how many ways will like um just yeah i'm bad guys sorry for the encryption i had something very important to do so yeah at this starting cell that is zero com that is zero comma zero how many ways do i have to reach this cell well only one way right only one way so i'm going to say that we only have one way and for this cell how many ways do i have to reach this cell only one way because i can only reach from this cylinder and fro for this cell how many ways do i have to reach this cell i can only reach from this side so only one and similarly for this uh column how many ways do i have only one and one it's pretty easy to understand that you can only come to this cell from this cell right you cannot come from this right or well it's an obstacle so you won't be there so you cannot come from this side and the direction is also not acceptable and you can also not come from this side because it's an outer boundary situation so now you understand that there is only one way for these um the first row and the first column of the grid now for this one well let's say that there is not any obstacle as of now for this cell you can actually reach from yeah so for this cell you can actually reach from this side right and also from this side but the ways of reaching this cell is going to be dependent on the ways the previous of the like the cell from which the cell like this is the new cell and you are coming from this cell or you are coming from this cell then this cell is going to ask you that if you are coming from this cell how many ways were to there to reach this cell if there were you know like x amount of ways to reach this cell and there are y amount of ways to reach this cell then in total for this cell it will be x plus y it's fairly simple that if you are using from like there are two ways to reach this cell and there are three ways to reach this cell then to reach from this cell there will be like this the ways to reach this cell will be x plus y or 2 plus 3 that is 5 i think it um i am having some trouble explaining it but for me it was very trivial and intuitive i think if you can like try to wrap your head around it then you will be also able to understand it so for this cell as well the dependency of this cell will be only from this only from the cell that is above to it right so it's only one it's again one and the ways to reach this cell only this cell is resultant of uh providing the robot away to this cell so the waste that is okay one only and now if you want to reach this cell then this cell is going also going to contribute in the ways of reaching this cell as well as this one so the total answer will be 2 and now this problem has been reduced to order of m cross n times time complexity and thus again the space complexity is the absolute space complexity is still constant but the time complexity is optimized to m cross n and the previous time complexity was 2 raised to power n cross m and now it's m cross and this is the power of tp so let's see how we can code this question okay so first we have to keep a check that if there's an obstacle on the starting of the grid where then when where a robot has to start then it's obvious that we cannot go in any other direction because if this is a grid and there's an obstacle at this point then we cannot go through this side or this side either even if there is there are no obstacles in the whole grid except the first cell we still cannot move from that cell because we have an obstacle there so this is the first check that if there is an obstacle on the first cell then we are going to return 0 and then we're going to say that number of ways so this is like a this is not i'm saying that there's an obstacle this is not saying that there are number of ways of reaching zero comma zero cell right and that is one then we are going to fill like the one i have shown you here because if you can observe then i have started filling this side this row and then this column that is the first row and first column we want to do the same so this is like first row and this is the filling of first column okay and the filling is kind of dependent on the fact if you have um yeah so if you have zero if there's an obstacle so if there is not an obstacle like the filling will be done on two things if there's not an obstacle and the previous cell has one way then we are going to assign one to it right otherwise there are zero ways if any if both of these any of these conditions are violated then we are going to say that there are there is no way to reach this cell right and why we are saying why we are checking the previous one because this previous one means does not means that an obstacle it means the number of ways although it's i think kind of confusing to you know actually have number of phase and a numeric value for an obstacle but well this is a question and i think it's more like an intuitive question so because of that the previous one that is i minus one means the number of ways and then we are filling the first column with similarly like the we have done earlier on the first row and then the main part where we are traversing the whole grid obviously not from the starting column that is 0 from 1 comma 1 because we have filled this one we have studied this one now we'll be starting with this cell and going in this direction and traversing the matrix this way so yeah so now you have if it's an it's not an obstacle it's a clear path then i'm going to have the value that is the cell on the like this one so this is like zero comma one zero comma two one comma two and one comma zero two comma one so if this is the for example let's say this is the uh i comma j itself then this one is the i j minus one right it makes sense because two minus 1 and this one is i minus 1 j this is the same thing that we are doing the cell that is on the top or right above the current cell and the cell that is in the on the left of the current cell right these are these well these are these two values interpreted to and uh they are some the number of ways for reaching the cell that is right above of the current cell and the number of ways of reaching the cell that is on the left of the current cell is going to be the resultant their addition is going to be the total number of ways to reach the i comma jth cell and if it's an obstacle then there is no way to reach that cell then we can we cannot even include that cell in our path so we have to say that zero there is no way you know there is zero ways to reach that particular cell where there is an obstacle now at last as i've shown you earlier we are going to have our answer at this point because we're going to traverse this matrix from this side and then from this side and the last cell will be the goal state and then our answer will be on the goal state that is a grid minus 1 that is the row or the last call number and the last row number or it can also be n minus one or if it's um yeah it's an m okay so it's like m minus one and n minus one right i think the question is clear it's not that difficult question pretty standard question in dp and if you can work around with this one and try to build another case for example by yourself which is of more say you know the matrix size is like 6 cross 6 or 5 cross 5 then you can easily understand that there is some overlappings that this state has been explored earlier but somewhere in the left in the right subtree you remember you realize that there is one comma zero again and that's like a problem of overlapping so then you will be like okay dp is used and when you're going to use gp then you're going to work your head around by like number of ways to reach this cell is the number of ways to reach let's say i comma jth cell is very much dependent on the cell that is one above it that is i minus one j and the cell that is on the left to it that is i comma j minus one sub and when you realize and made this map and make this observation then you will be easily then you will easily be able to write this code and this part will be very easy to interpret and write on your test case so i hope the problem is a little bit clear and this was it thank you for watching
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
85
Hello friends, the liquid problem we are discussing today is 830 Maximum Rectangle Problem, it is a very good problem and one of my most favorite problems. You will definitely have this problem in it because you will get a lot of money in State Bank and 1 hour. This place will be useful. Okay, if you stay till video calling, it will be a lot of fun. The problem is Bihar Governor Arun. The problem is that you have a bank account receiver which has a judgment on channel zero. What you have to do is to make a rectangle of 105 from the lage and return it. More than this, you will write against. So see the editing in this, there is only one printer and only one printer, their maximum is this saying, why is the area in Edison Dhablu market only dark, and the rest you will not find people like this, nor will you find education workers, okay then you will get rewarded for this point. First of all, I want to tell you that before this channel, I want to tell you that what you do is to pay attention to the object in an interesting way, if you see, it is necessary, then you can always learn something by writing on your own. You will get the gift solution many times, it looks so complete, it is Bigg Boss Quarterly, so you try its Mittu solution, now let's go, see exactly the confirmation of the solution, what will we do, as many as your pictures, that is, as many as one. Army, you mean, what will we do, you gender, if you send, it is the evening bill, what will you do, you will go every year, according to Urmila etc. It's the training after the lap, we will maintain it. Continuous Vansh's time, when you are here, then Vansh is this or that. Or pee 123 skin tight slap what are you doing bittu lieutenant stop all have to be maintained here see here bring to front what will be the benefit of maintaining that see why you have a meaning for triangle why kind of area of ​​triangle on the land into breast area of ​​triangle on the land into breast area of ​​triangle on the land into breast Okay, this way triangle work is fine, so if you do any point and you know what is your edge, miss told you that you have maintained training in the camp, then you will know this, then you move down and come down as much as the backcountry. How will the fog move? See what I have done. What did you think about your implementation last week? The brightness bell has been measured by the Parliament. It is right to left migration in the row. As we are here, right take right system in our cities. Maintain from your knowledge world that what you do n't do on your group, how every day there is a thread, every problem, which is you, this is my hero, then you get this, whenever you get validation in 121, there are 120, so what did you get here, then means to. If you are present then what is your problem? Is your life point there? The word of Vansh is there, cash, jewelery etc is there, only then the application is there, after that you get yours, what has happened if it has become a hit, then Amit is yours. The area which was there for you is also your answer below, which is the answer, yours is broken, this report will be there, door below it, Bade Taluka Military, I got a letter written for you, I miss you, Capsicum, I have made you also, below which you are, Continue eighth, right toe. Left thumb under this continues Bansal, okay, that's what this yagya is, but what should you do, I have to say minimum of twenty three, look, you will see that you will make rectangles, only you will keep it, what is a rectangle, what is lumber, meaning, I will keep it and take it with me today. The entire allowance should be of Taurus, then whatever is below it should be Bittu, only then it will be made, this is this, then it will be Bittu, only then you will be able to make a right angle from the top point, that if you want to keep it as the first choice, then further down and By commenting below, if you set a free virtual like the triangle will not be filled, then you will understand me as a natural family and write the meaning of your introduction, the address is and the witch has gone down, okay, so what is the medium, I have given you the photo. Meet, but will your height increase or will it increase due to intake, then you have this career in the form of a tweet, then okay, here you are half of its diseases, now what will we do now and you can explain from here and are sitting further down from the office. So you and squeeze what is a knife aa 1 minute I think police write kevda in it you and I think again I got you equal to ok if you get an auto then equal to Megha do penance the desired person is the dress I you Tubelight Then you got my fast, then you get equal to two, take off, what will you get from the whole fast, you will get the minimum menu camera in two minutes, because you know that brother, due to low caste, the height has increased. Hey, this work has to be done to the six members of this gang, now we ginger below. Sitting, your height increase research percentage and exam is done, area sixty [ __ ] Adams, okay, done, area sixty [ __ ] Adams, okay, done, area sixty [ __ ] Adams, okay, what you have to do is to match every obstacle everywhere, you have to sit down, meaning that if you tell me the middle of the continuous time 20132 laptop in your leg every day, one is okay. And the height should sit at the very bottom, we will submit and take it to the minimum. If you have two here, it is okay here and then with the help of going down, on these axes, one time will be like this, one two is one from the bottom, okay seven zero, okay then. What will be your first year? First of all, 2.1 will What will be your first year? First of all, 2.1 will What will be your first year? First of all, 2.1 will have its own breakdown. Will you go or not? It is written below that teachers are right to left and Sanghamitra told you what is one rank here, what is one side, it is April 30 that You will have to meet. If you want to make this dancer below then you will have to complete it. Your statement will be something like ' you will have to complete it. Your statement will be something like ' you will have to complete it. Your statement will be something like ' Kara Cab', practice the last letter, Kara Cab', practice the last letter, Kara Cab', practice the last letter, what should I say in my decision, we have got such a bank, we have a property and calculate it in your area. Remedies, you must have thought of this time, then do not fear this, then look at Mishra Good in the lists, exactly what will we do, the biggest work, what we have to do, right clear and vansh time, internal assessment while withdrawing 10th house review, why is Pooja character like this? You can do the certificate in that table store, at this point the time will be earlier, then you will not be able to do 120 in one character, okay, in this, I had taken the option of a letter from that Pattinson can maintain it, okay, his security is till white, this Ravana is subscribed by Rachna. If I am a tiger, my health is equal under the curve, from whom I must have heard this, then in that, if the one on his right, do my wait, like do meher here, what 151 has been maintained before me and here I have kept you closed, but its instruments are yours. Have you folded and taken two cups of sugar? Do I give you every other motivation of verses and if you are now at the turning point then it is definitely on this, then what is your percentage, if you are sitting from here with 20%, then your sitting is here with 20%, then your sitting is here with 20%, then your sitting is after that. 250 and your Hanumat means your body, then next you whether you need help or not, you mean the one equal to mi, well, keep the rice time inter, keep the mix point from here and from here you will start turning on the mode below, okay, doing good. Brother's wave will go, beef cases where everyone is present, okay till then the chickens are down and you are Amla's Tahir Chowk, it will remain now and what is the meaning of birth certificate in the room while tracking the non-minimum certificate in the room while tracking the non-minimum certificate in the room while tracking the non-minimum admit, career and your balance or That - you Laxman, is it okay - balance or That - you Laxman, is it okay - balance or That - you Laxman, is it okay - youth like all of you, that this is your point, so for this, zero one two, if delhi-110012, how much height is okay, then delhi-110012, how much height is okay, then delhi-110012, how much height is okay, then what will we do, you maintain the size, take the glass, balance your brother's. During this time, keep the button maximum close and let's practice the sycamore and the last chance. This is our introduction to this body. Now write time for Africa N * * * * * * Yoga is fine and what are you N * * * * * * Yoga is fine and what are you N * * * * * * Yoga is fine and what are you doing, do the whole pan for each. Normal top Tilak is trying to don't then this which explains the time complexity of different boys and this tree etc because we had done this you have made this to maintain the tree till that time the organization is in crisis 77 running the internet then this Inertia is also up to half a kilo 2018, so this thing will cross it, there is no problem, okay, there is a passbook, but now you will enjoy it very much, Veemee Avatar, so here we go, its optimal, it is famous, okay, we are also talking about tremendous. That is from yesterday, what is the largest area of ​​rectangle what is the largest area of ​​rectangle what is the largest area of ​​rectangle in a given two grams, if you look at the ginger problem, then the problem is that you can subscribe, you had to do some tuition for this, how to see, then God, who is the first, you cannot pay like Look, whoever you become, he also has his height, so you know that this dam is his height and his daughter Vanshika, as I said something, only then you, this is just a matrix, meaning 11 closed celebs soon, both of them subscribe on every channel subscribe Do n't forget and subscribe here it is above that if you two explained to where here I told you we lining this we today we made this program that you can remind your this year app that if you in this point Those who want to do this have a maximum. Well, now we cover it, that's fine, how much do you need from the family, let's go further. Here I see, you reached Zoom Than Rs.1 first but you reached Zoom Than Rs.1 first but you reached Zoom Than Rs.1 first but will keep its height increasing, you have increased one's chances. In between this zero six became next and 131 in the test that Jyoti was height cutting and what is her rate and shirt and gambling talk they now subscribe here to vent out their anger so here you get how much is its seat hatred and like Do big trees and set the alarm on it. Author is a good pepper to hit the top one, you will get a particular height in every and yes here the camera's like this contact number three layer see one two three laser 1380 came here. We have subscribed, subscribe my channel, you have to subscribe to this channel by subscribing, subscribe if you have the meaning like do Pathribal here Yagya 4655, subscribe because you have to subscribe to this channel and if you subscribe. If you subscribe i.e. do not forget to subscribe the entire staff of the school because what you did on this channel is that earthquake check top hits a specific has been added, then what will you have to do now i.e. you should subscribe to this channel so what will you have to do now i.e. you should subscribe to this channel so what will you have to do now i.e. you should subscribe to this channel so that you can subscribe Subscribe That's why you if you are wearing any proper texture after that leave is approved neither had to be canceled immediately Calculate the polytechnic area because after that as if it is small after this you have come with no matter how big of a celebration it is If you will not be able to work, if you are a teacher, then for that, the number of elements will be there, the number of butts will be the biggest in the last part of a human being, what are you doing, if this is Ashok Ram, we are the exam of this program, text the message, subscribe, these are small because Subscribe till now, subscribe the channel, like and subscribe our channel, then you have Abhishek and your time is now, there are tips, there is traffic on the forest, but this temple is a prospect, so if you art means porn, if you start watching, subscribe. Subscribe and if you have subscribed to my channel, like and subscribe to our channel and you can contact us, what happened was that the whole team together got looted so much that what do we do now, if there is any diet then subscribe to it, then it means school. It is possible, but if you like this video, then you have to subscribe like this, if you subscribe and subscribe, what to do now, please, how will you take it out, meaning what is there in it, where is this phone. Aya but okay so that would be minister and stop I meant and - so that you subscribe this subscribe our Channel subscribe and you mean score until I where you are given. That I have to cook you till it rains this model top posts tagged so far present in which means the result was hard decorated as long as it has Chetak problem on 9th then please subscribe minute tawa par appointment subscribe button Hoga - Dr - - - - - - Dr - - - - - 121 Pylin Got more subscriptions You have this recipe flight I haven't subscribed to you till then so do n't forget to subscribe now because subscribe on this channel subscribe my channel health tonic quick What will this be from your career - quick What will this be from your career - quick What will this be from your career - where is it, if it is on one side, if you have to find out that the actual tenth topper means A grade two, but ka or beech hoga aayi ho jaaye mitwa aayi, so what has happened, then you can easily look at the relationship. This is the digestive element of the matters, soon you will go to the end, follow this happiness and what is there in the P tag about going to the end, as long as you have this reference, then you have to repeat this, what to do if your present director has started from the stop. So you press it back and present that small post office, so long as you perform the extension toe till the temple site twitter happy printhead at this time and you add meaning rich and leave loosely in his health and height, then only this reason happiness now we We have our problems, let's go, but the problem is, how to do it in his office, it is okay, 11 first two matches, you have the subscribe button, how 520 admit, okay, but when you go to the same thing in seconds, when you go in seconds, when you reach here, then this is that Aamir Subject Starting Matrimonial Find a place for Tomato in it Okay and going forward this note will go in tow and whatever it is will remain but I have one that if you are here if you have taken out the ATM then it is here for you that I have put my darling head here This of the camera is absolutely fine, you are the Revenue Officer and the order of appointment is Mirwaiz. You put the facial hair in front of him. Okay, we have reached the third. Now as we reached, what is yours, how is it defined, this plate here and this one. What will happen is that end, what will this become, 2nd will happen, okay, so here if you from here, it will ask, oh man, what has happened is that it has gone to zero and what is the height in inches in front, it will ask towards Soon ok so this is what subscribe and fold it definitely subscribe the subscribe button if you Puri if Meghnad's grammar any above 10 album has no meaning so send the device found here to G exam leadership. Cover it or inject it from whose 10 that you must subscribe here Subscribe to 123 above Subscribe to some here Subscribe to the channel Like and subscribe On one hand, this prince is the cadre Have to back something up that this is just one Talk to others to do something, if you subscribe, which is top which is subscribed here, then you subscribe and subscribe - subscribe - subscribe - 159 Okay, if you this Iyer's soil, oil minister, to pour in and when you get this temperature back to you This is to keep you happy, such a festival is given by making quick settlement on the setup and investment is fine, comfortably Nobita Current Mr. and you have subscribed your soon subscribe button here, this is what we have subscribed to this, Tiger is this, I am Amit, so it will be much better that You tighten it so much, it's okay, so overall today is completely secure and there is no one to have any problem, the height has increased and is medium low, you have taken the same time for each year, plus what time should you bring for each year. From this it is just our ender so the time has been set that encounter is real inside-inside install that encounter is real inside-inside install that encounter is real inside-inside install that is not the people of vansh behind him garlic then after that it is written for me meeting after that it is the third worker woman only tempered ok so that white How is the cap, runtime is Ashraf-ul-Haq, white How is the cap, runtime is Ashraf-ul-Haq, white How is the cap, runtime is Ashraf-ul-Haq, who is the president of your height and size of the chapter, then the pattern will be found towards its attacks, it is as appropriate and we are accused of this, what will we do so that our skirt is pressure Salman himself does the analysis, then if you have any problem then definitely come in the comment section, it can be removed in time, it can be done very powerfully, if you are invisible, okay, then let me update the video of torch light area histogram, we will make it and cut it, okay. What's the point in this - We have reduced it a bit, okay. What's the point in this - We have reduced it a bit, okay. What's the point in this - We have reduced it a bit, then we used to be a scientist, training is needed, like the video and subscribe to the channel and such arghya.
Maximal Rectangle
maximal-rectangle
Given a `rows x cols` binary `matrix` filled with `0`'s and `1`'s, find the largest rectangle containing only `1`'s and return _its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 6 **Explanation:** The maximal rectangle is shown in the above picture. **Example 2:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Example 3:** **Input:** matrix = \[\[ "1 "\]\] **Output:** 1 **Constraints:** * `rows == matrix.length` * `cols == matrix[i].length` * `1 <= row, cols <= 200` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Stack,Matrix,Monotonic Stack
Hard
84,221
211
hello everyone in this video we will be solving problem 211 design add and search words data structure the problem statement is we need to design a data structure that supports adding new words and finding if the string matches any previously added words we will be having a constructor a method for adding the words called adword and a method called search which accepts a string parameter and returns true or false if we see a dot in the input sort string it can be matched to any character in the string that we have previously saved to the database in this example we are given these three words that is passed to the add word method which needs to be saved to the database and the remaining four are the actual search instructions or search methods executed with this as an input so if you look at the first three input we are adding bad dad and mad and now in for the search when we are getting pad as an input because we do not have any text that matches that search word so we will be returning false now if you look at the next one which is bad as an input we do have a word callback so we will be returning true after that we have a dot and a d if we have a dot we need to ignore that character so because it is started with a dot we will ignore the first character of all the words and look at the next one we have a so all of these words qualify and then we have d again all of these three qualify so hence we are returning true even in the last one we have b dot so between bad dad and mad we have one word starting with b and because the remaining two are dots which we have to ignore so we will ignore those and because we found a word we will return true one important constraint over here is we need to return true only if we are able to find the complete word for example let's say my input is and if my search criteria is p dot even though this word sort of qualifies in this search parameter but still it is not enough because we are looking for a word with three characters only we have a word with five characters so we need to return false in that scenario now that we have talked about the problem and a couple of scenarios let's switch to whiteboard and talk about what is the best data structure that we can use to solve this problem normally the simplest solution to such problems is brute force where we are recording all the inputs in an array when the search method is invoked we will iterate through all the values in the array compare the search word with each of the word and find out if there is any match if we find a match at that moment we will stop the iteration and return true and if not then we will return false even though the solution is the simplest solution it is not a scalable one because if we have let's say 5000 words and the character length is at least 10 then we are running the loop at least 50 000 times because we have to go through each and every character for each word to make sure that we are checking for each valid case hence the time complexity will be exponentially large so this is definitely not going to give us an efficient solution now let's talk about a different data structure or an approach to solve this given the problem statement and the cases that we have to cover for testing i feel like a search tree is going to be the best suited one specifically i am talking about the prefix search tree if you haven't heard about this algorithm or this data structure i'll briefly talk about it in this video the way this search tree works is for each word let's say we have a word abc so for each word we will have a node let's say we have a node for a for the next letter in the word after a we will have a separate child node so i will have b here naturally this a is going to have a root which is going to be common for all the letters and after b we have c and i will add c here now similarly we will do the same iteration for the next word which is that because we haven't covered d over here i will create a new node and then after d we don't have any other nodes inside it so i'll add a new all together if i look at math we will have the same scenario let's say i want to add another word d a y so now if i want to add it to the same data structure from root i will check if the first character exists yes d exists so i will use that so i will go to d now i need to check the next character so after d i have a so i will again check if i have a node with the value a yes i do so i will go there now inside a the next character that i'm looking for is y do i have a y no i do not so i will create a new one important part over here is the way to identify if we are done with the word or not so at each point when i was iterating for day d is not the last character of the word a is not but y is so whenever i am at y we will highlight it with a different color and when we are coding it will probably add a new property so whenever we are at the end i'll just highlight it with green just to make sure it's distinguishable i'm hoping that you are able to understand how this prefix search tree is going to be designed and how it fits into the first part of our problem where we have to add all the inputs that we are getting whenever add method is called now the next part is to search i just randomly chose four words we will be using for testing let's start with that we will start iteration with one character at a time so i will check underneath root if i have a character d i do have a character d so i will go there and inside it i will check for the next character which is a do i have a inside it yes i do uh the next one i'm looking for is d inside a do i have d yes i do so with my search pattern i am at the end of the word so my requirement is to make sure that this character d is also the last character of the word in other words i need to have a word that ends with d i could have two words in my input i can have one as dad and one as daddy which are both acceptable i need to make sure that i have a word called that and because when we were entering the data we made sure that we highlighted this node with the green color saying that this is the end of the word this tells me that i have a word that matches my search criteria or search pattern so i will return true now let's look at the next example it's me so starting from the root i'm looking for m do i have m yes i do i will go to the m node after that i'm looking for a do i have a node yes i do so i will go to a after that i am looking for why do i have a y node here i don't i will return false the next part is interesting we have d dot and dot so when we check for d i will check from the root i do have a d so i'm at this d node the next is a dot so when we say it is a dot we don't care about what is the character we will take everything so underneath d we only have one character a so we will take a as the next iteration if i had b over here i would have taken d a and d b both after a the third character in my search bar search pattern is a dot again so from a i will look at all the children or all the nodes underneath it and add that to my condition or that qualifies to be my search pattern so i will take y i will take d so now i have d a y d a d now i have to check if the words end at y or d because i'm looking for a word with only three characters and over here both of the words matches that pattern so my return is going to be true the next scenario which is a dot b so when i check with a underneath my root i have an a so i will come to this node after that i have a dot so i will take everything so i'll go with the b first and after b i'm looking for another node with a b in it because underneath this b node i don't have any other b nodes i will return false i hope you were able to understand this explanation let me show you how we can build this data structure using csha the c sharp implementation we have the box dictionary and i have created this custom class as my data structure to hold the information this custom tree class contains two properties one is the children which is a dictionary of character and custom tree and i have this property called is end which will help me determine if the character that we are looking at is at the end of the word or not and the constructor is going to initialize this children variable and create a new instance of it i have this property called root which is going to hold all the nodes that we talked about so starting from the root if we have like dad so it will have the first layer as d and then a and then d in the constructor i am initializing this root variable next we have this method add word where we get the word so whenever this method is called i have starting this while loop which will run through all the characters in the word and i have created this temporary variable which will hold the instance of the custom tree at each layer so inside the while loop i am getting the character and then i am checking if the character already exists in this temp custom tree if it exist it means there is already a word that was created before with that character so i do not need to create a new node altogether i can use that so in that case i am not going to be going inside this condition and if that node does not exist so i'm creating a new node inside this children so i'm passing the character and then a new instance of custom tree as we are incrementing the pointer we need to now look at the next layer of nodes hence we are replacing the value of temp by the children after this while loop is done we will have all of the characters inserted into the custom tree and the stem variable will still be pointing to the last value or last character that we inserted which we can safely say is the end of the word hence i am marking the is end property to true the next important method is this search where we get this word as an input so here i have created this list of custom tree called trees which will hold all of the custom trees that we need to search for i'll talk about why i'm using a list instead of a single instance in a moment so just like before i have this while loop which will run until the end of the word i am extracting the character from the word based on the index and then i have this temporary variable that will hold the values of all the next custom trees that are qualified or that matches to the search pattern and we need to continue searching forward then i start this for each loop to iterate through all of the trees that are qualified so far so when this is running for the first time the route is the only tree that is qualified hence we will have only one but in case we have a search parameter as a dot we can have multiple children that are qualified hence i am using this list of trees instead of just one so inside this for each loop i'm running it for all the nodes and checking if any of the children contains the key of this character if it does then i'm adding that children to the temporary variable so that we can continue this searching for the next hierarchy or the next character once we increment the pointer if the character is a dot then i am doing a temp dot add range and adding all of the children to this temporary variable because we have to search through all of the words and not just one particular node once the for each loop is complete i am replacing the value of trees with this temp variable that we built just now based on this for each loop and the search criteria and after that i'm incrementing my pointer so this while loop will run until we are at the end of the word and we have gone through all of the characters after the forage loop is done i am checking if this trees variable have any entries with is n property set to true because we are looking for word that actually ends at the right alphabet and not keep on continuing forward if we find any such value this any method will return true or else it will return false i hope you were able to understand my explanation and the source code that i just walked you through if you have any questions or concerns feel free to reach out to me via comments this source code is available on my github repository i'll be adding the link in the description below feel free to check that out and i will see you in the next one happy coding
Design Add and Search Words Data Structure
design-add-and-search-words-data-structure
Design a data structure that supports adding new words and finding if a string matches any previously added string. Implement the `WordDictionary` class: * `WordDictionary()` Initializes the object. * `void addWord(word)` Adds `word` to the data structure, it can be matched later. * `bool search(word)` Returns `true` if there is any string in the data structure that matches `word` or `false` otherwise. `word` may contain dots `'.'` where dots can be matched with any letter. **Example:** **Input** \[ "WordDictionary ", "addWord ", "addWord ", "addWord ", "search ", "search ", "search ", "search "\] \[\[\],\[ "bad "\],\[ "dad "\],\[ "mad "\],\[ "pad "\],\[ "bad "\],\[ ".ad "\],\[ "b.. "\]\] **Output** \[null,null,null,null,false,true,true,true\] **Explanation** WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord( "bad "); wordDictionary.addWord( "dad "); wordDictionary.addWord( "mad "); wordDictionary.search( "pad "); // return False wordDictionary.search( "bad "); // return True wordDictionary.search( ".ad "); // return True wordDictionary.search( "b.. "); // return True **Constraints:** * `1 <= word.length <= 25` * `word` in `addWord` consists of lowercase English letters. * `word` in `search` consist of `'.'` or lowercase English letters. * There will be at most `2` dots in `word` for `search` queries. * At most `104` calls will be made to `addWord` and `search`.
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
String,Depth-First Search,Design,Trie
Medium
208,746
283
Friends, today we are going to see the second problem of array, one move zeros which says that we have been given an integer array of numbers, we have to bring all the zeros to the end and we do not have to change the relative order of the non-zero elements, meaning. That we have to we do not have to change the relative order of the non-zero elements, meaning. That we have to we do not have to change the relative order of the non-zero elements, meaning. That we have to do it in this place, sort it in a way that the non-zero elements have to be that the non-zero elements have to be that the non-zero elements have to be brought forward but in an order, like one is here first, then one should come here first, if it is on three, then th is here after that. Zero should come last, okay, so what will we call it in this place and we do not even have to make a copy of the array. Firstly, let's see its intuition. Let's take an example array. To solve this problem in order A, we will write 01031. What can we do, we can make a q, what is in kya, our in place remains our element which is first aga first in first out because q takes our kya first and first out so aa let's make a kya now its Let's save the non-zero element inside. its Let's save the non-zero element inside. its Let's save the non-zero element inside. First of all, we will save the one here, we will not take the zero, now we will do the three here, then we will do the 12. Now at the end, what will we do, whatever is our q, we will take it from q. We will dec from here and put one here, now dec this element, put 1 here, now dec this element, put 12 here, now rest, if there are elements left in our array, then we We will put zero here and this will solve our problem. Now let's see its code. So let's write Guy's code. As I said, first of all we will create a queue of integer. Let's name it equal or gender list. First also we can do one thing let's create our base case if numbers dot length equal one then return two single element then we will return same to same otherwise we will create Q then run a loop e a e 0 aa lesson numbers dot length aa plus Now what we will do is if our element is not zero then we will put it in q dot d numbers i Now what we will do is let's put a variable called index, put zero in it now we run We will do a loop until our q dot is mt till our ku is not mt then what we will do is we will do q dot dk of index in names, we will take our element, poll function is used for this and we will add plus to the index. We will give and check if our array is still there, if the array is not complete then we will put zero in it, then how much time did we take, our time here, time is complex n, order and time is applied here also, order and time is applied here too. Our loop also has order A. This loop also has order A, so the total time complex is A because we have used K. Let's run this once and see the code. So we can see that both our test cases have been accepted. We order the same question as one space complicated. Once you see it, our problem has been accepted. Thank you guys.
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
1,011
hey everybody this is Larry this is February 9th of delete co uh or Larry just doing an extra question um yeah because you know the other one was done before so let's just pick a random question let's keep it with medium and I think I could choose someone told me that I could choose a premium one right how do I choose a premium one okay there you go because I keep on picking prompts that it was done before or something like this or like that I end up doing later so uh so I'll do a premium medium and let's see should be a Liberties and still get an SQL question okay let's try again okay 10 11 capacity to ship packages within D Days let's do this the conveyor Bell has packaged them as we ship from one point to each other okay the I package has a rate of way to buy each day we load the ship the package on the conveyor belt in order given by rates we may not load more weight than the maximum weight capacity of the ship okay what is the weight capacity of the ship oh that's what we're trying to figure out return the least weight capacity of the ship that will resolve all the packages on the conveyor belt being shipped within day days okay so basically if you have 15 and you have to do it in order right okay in order so this is a um I think the first thing to think about is that you have this Min um this minimization problem where um where okay so you know you have a let's say let's you know let's try a big capacity right like mentally um let's say we have a capacity of 200 then you can ship everything in one day and then now okay can you go lower well this is where you kind of get this intuition about um also this isn't a premium question isn't huh so I think I messed up there again anyway somehow oh well I mean I always I'm solving it so I'm going to finish solving it but I just realized that even though I said I wanted a premium question uh solilitko but in any case um yeah so let's say we have a smaller number and you know that if something works for 200 then 201 will be fewer days right and but it may also mean that 199 may not be enough days or it'll be more days but you know maybe not be five days so this is basically what um this intuition of like getting a number and then trying the answer is the basis for binary search and of course in this case um or in you know in order for it to be binary searchable you have to have you know some function that you test every time and that test has to be fast enough which is usually roughly linear time but you can also have constant time tests and again tests and maybe even N squared depending on if n is you know depending on how big n is right so based on that we know that we have a linear thing because we just have to go from left to right because we just have to go you know we cannot choose change the order um so there you go yeah so let's that started so levels ago zero oops uh rate is equal to um uh 500 is the most times this so it's going to be like 500 times 5 times 10 to the fourth or something right um it's the most maybe plus a little bit more so let's just make it six I don't know right and then this is the uh you know this is just regular binary search stuff and then okay if mid is good that means that when what is good here right good means that we ship within the number of days if this is good then that means that we want to try a smaller ship capacity but mid is good otherwise this is not good and we need to try a bigger capacity that's basically the idea behind binary search and of course now we have to implement a good function I call it Target but yeah and this is going to be the target weight so basically we just we could just count um yeah so um I should make want to make capacity at least one just because I don't think zero would ever make sense I mean it doesn't make sense even if the constraints kind of you know but it will give you a weird thing if you are not careful and I probably have done them in the past but yeah so basically now capacity as you go to the Target and then maybe um days as you go to uh well use uh days used or something like this days used is equal to zero so then now for X in weight we go okay so capacity uh if x is greater than capacity then capacity is you go to Target and there is used right increment by one else uh capacity minus X um and there's a caveat here which is that if X is greater than um if x is greater than Target then this is still going to be true right so or you could maybe write another way which is that if x is greater than capacity then we return Force right because that means that you know this is just not enough otherwise we return um days used is less than or equal to days I think this should be good unless I messed up a sign or something but uh okay hmm don't mess something up all right so one thing that you can use to debug is just print out um Target and the days used I think that should be good oh yeah okay no that's real okay so 15 would take two days so this should return true so then that we would try to get a smaller number I guess that the logic is right but why is that foreign if x is greater than Target then data is used to Z Plus One if it's still bigger than capacity oh I'm dumb this should be this um and then uh capacity I guess minus X again okay yeah okay still wrong though what do I return I returned 11. because basically oh this starts with one day used okay so okay as you can see it is very sensitive to you know you have to be really correct on this function um because if you're just off by one somewhere like I just forgot that I obviously you need at least for the first day to fill it up um if you don't you know I mean it was just wrong right the code is one you get a wrong answer so yeah uh all right let's give it a submit this is why you test and debug yeah so what is complexity here well this is linear time constant space as we talked about this is going to take log of O uh o of log r where R is the range times n right where R is the range and all of log r space now all of just all one space I suppose right um yeah that's what I have for this one let me know what you think um yeah just kind of concept about you know binary searching on the answers just about you know having a feel for things and I think I've gotten a question in the past about on a Discord about how to figure out if this is binary searchable the answer is I don't really quite know per se or rather like I don't look at problem and go oh this is binary search necessarily but I sometimes I will be like okay is this binary searchable so maybe I have a checklist mentally maybe of like oh it's a binary searchable and if it and then I go okay assuming that this function is binary searchable then is it fast enough right drive an O of n function like I have here or depending on what the N is maybe n square or something like this right and if I do then I ask myself well is it a binary searchable function and with those criterias are met then you know then I give it a go you know I'm not always right but you know um that's one of the things that we explore but yeah that's right help with this one let me know what you think um yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
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
61
Al so this question is rotate list so giving the list not the head for the single link list and then you also given a K represent number of time you need to rotate to the right and if you're on the last one you're going to replace to the you know the first one right and then let's look at this so um when k equal to two right so this is original um single LL so we rotate right by two and then definitely that this will jump and this will come back to the beginning and jump one again so four become what the head and three become a tail right so in this question we are supposed to find out what is the new Target New Tail so when we Traverse the new tail which is going to be this guy we can assign new head right we can assign new head if we target a new head we are not allowed to assign the new tail so you just have to know we need to find a new tail for the rot um list right and basically we need to Traverse the length so we know that what is you know what is the rotated is based on the K because if K is actually greater than the length right you want to so if k equal to five and your length is five equal to five you when you Traverse five times you will get the original single linkless order right the way you want to do is why you want to find out the K is actually less than the length so how do you than less than the length so how do you do that it's going to be you know k m by length right so this will be represent the remaining rotation if K is actually greater than L right so now we want to know okay this is the remaining me let's just go remaining K and then we want to derse Traverse you know uh three or Travers three times actually two times right so the length is five right the lens is five k equal to two so is actually you know 5us 2al three right so if you travel three times so this is one time two time three time uh three time this is your head so again we need to Target the new tail not the new head so just make sure you get the what new tail so it's going to be three minus one right so it's going to be two and once you get a new tail then you can assign the head equal to this guy based on the tail. next and then you can assign the you know the tail you know this tail next equal to no and then you return ahead and make sure you connect this one with this one all right so this will be it right so let's talk about how you do it so what happened okay let's look at this so um so link should be zero so the range including zero right so including zero which mean that head equal to no so returnal all right and then I need to make sure I have a length uh I have length at this and also we starting from one which is because we always starting from head right head is one unit right and then we Traverse right so I'm going to say this last not uh new starting from the head and I'm going to Traverse so new tail down next is not know um sorry this is should be last tail so I'm traversing my last tail to get the length so length equal to so I will Traverse the T you know Travers the no until the tail to get a length right and then I will say list no it's going to be Target tail right target tail is actually equal to starting from head and then we need to you know starting uh you know so we just say 5 - starting uh you know so we just say 5 - starting uh you know so we just say 5 - 2 minus one right so it's going to be the Len minus k m by length and then we need to assign a value equal to J right and then just has to be greater than one I mean that would be um that would you know just get R of the minus one at the end so it's going to be k Sorry length minus K so it's going to be 5 - uh 2 = to 3 but you at the end you say - uh 2 = to 3 but you at the end you say - uh 2 = to 3 but you at the end you say J greater than one which mean you say well which means 5 - 3 right so you jump well which means 5 - 3 right so you jump well which means 5 - 3 right so you jump two times only so Target equal to target. next so now this is your target tail right so my last tail has to connect to the beginning right so my last tail next is equal to the head all right so now it's connect right my head is remain one right here but I need to reassign my head equal to what my target tail Target tail down next right target tail so head become this guy right but I still have a connection over here I need to make my connection disconnect so Target nextal to no then I will return ahead so this will be it let me run it submit and yeah so time is space or straightforward you definitely have all of info time Travers every single one of the know in the link list space is constant right and let's just consider all of them because we have no idea the length right I mean this is going to be the worst case for the time so this will be it so if you have question leave a comment and I'll see you later bye
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
452
Hello Hi Everyone Welcome To My Channel Let's All The Problem Minimum Number Of Cost Wave Women Sudhir Video Start End Coordinator After Start End Subscribe Bhairav ​​Can Give Start End Subscribe Bhairav ​​Can Give Start End Subscribe Bhairav ​​Can Give Water From Different Long-awaited Water From Different Long-awaited Water From Different Long-awaited Extension More Syphilis Award-2012 Extension More Syphilis Award-2012 Extension More Syphilis Award-2012 Start Giving A Limit To The Number of what is this problem basically a give values ​​and the access like this values ​​and the access like this values ​​and the access like this and giving coordinate software system was started like this can be possible half skin ₹3000 hair possible half skin ₹3000 hair possible half skin ₹3000 hair start this point from Z2 and subscribe extension and subscribe mid day meal per values ​​of meeting Have 2012 date in this so let's take an example per values ​​of meeting Have 2012 date in this so let's take an example sure this problem is similar to this set of problems which have solved in the previous challenges and this problem Jasbir and challenges of life and your solve this problem and solution to this problem but you will get idea And solving for solving this world will give some different point subscribe and will stop this point reddy and rebuild subscribe shyam subscribe my channel welcome two three 500 to 1000 e ki and elastin from tattoo last year from shyamveer value sir giver Like This Point In This Year First One Need Not Anywhere Between 20 And Avoid Being Tried To Share And Subscribe Show Total To Subscribe Vyavasai Fati Code So Let's See Another Example In Dishaon Example 123 400 12123 4000 Doob School Values ​​Of 12123 4000 Doob School Values ​​Of 12123 4000 Doob School Values ​​Of Independence Day In History Has Been Distorted Subscribe To Hai So Let's How Many Improvements For Implementation Values ​​Are Short Method You Can Used Implementation Values ​​Are Short Method You Can Used Implementation Values ​​Are Short Method You Can Used Resorting To The Indian Regional Languages ​​In Java Using Pass Deposit Is Languages ​​In Java Using Pass Deposit Is Languages ​​In Java Using Pass Deposit Is Zara Doctor Amazon Off But Why Do You Like To Cervi And Very Positive Subscribe Yes Ji Bittu Our Settings Band Stock Index For This Problem Can Also Be Used In This Time Elections Will Also In The Cases Can Go Into So Let's Subscribe And Cool At Nine Adhir With Intent And The First Man Points Of 051 Dab School Novels In PowerPoint Se Z F Hai So after defining dissolve erase all the balance from physical to descent sexual points not length plus no for checking this condition when points paid deposit clearly subscribe thank you will take another arrow and update please do this point subscribe and subscribe the Channel and subscribe It happened that I am this walking Let's meet record is a little accepted So what is the time complexity This is the meaning of birth states and slogans against time complexity Solution in law and space complexity Jasbir Singh Subscribe to the start End And Points Will Be Id 2nd Id Subscribe To The Method Admin Of And Deposit This End Of The Current Points Balloon So Let's List That Bhagyashree Network But You Can Try It Out And Should Feel Like My Video then subscribe To My Channel thanks for watching this video is
Minimum Number of Arrows to Burst Balloons
minimum-number-of-arrows-to-burst-balloons
There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons. Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_. **Example 1:** **Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\]. - Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\]. **Example 2:** **Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\] **Output:** 4 **Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows. **Example 3:** **Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\] **Output:** 2 **Explanation:** The balloons can be burst by 2 arrows: - Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\]. - Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\]. **Constraints:** * `1 <= points.length <= 105` * `points[i].length == 2` * `-231 <= xstart < xend <= 231 - 1`
null
Array,Greedy,Sorting
Medium
253,435
110
all right this LICO question is called balanced binary tree it says given a binary tree determine if it is height balanced for this problem a height balanced binary tree is defined as a binary tree in which the left and right subtrees of every node differ in height by no more than 1 so with this binary tree just by looking at it we can see that it's balanced because the left side has a height of 2 and the right side has a height of 3 and were allowed to have a difference of 1 so that one's balanced this one is not balanced because the left side has a height of 4 and the right side has a height of 2 so this one is not balanced alright in this video we're going to go over some definitions slash assumptions and then we'll put them all together to help us solve the problem all right so what is a binary tree is a data structure where each node has at most 2 children so let's say this node how many children does it have it has no children and by the way these things I'm just using them as placeholders for the word null I don't want to pollute this with the word null and this is just shorthand for that all right so that node had no children how many children does this node have it has two children this node and this node alright next we'll go into the height of the binary tree well first we have to realize the fact that each node is in and of itself a binary tree this can be viewed as its own binary tree so can this and so can this all right so what's the height of this binary tree it's actually pretty debatable it can either be viewed as 0 or 1 so some people would say this has a height of 0 because it has no children some would say that it has a height of 1 because the node itself can be considered 1 it doesn't really matter each way for this problem so we'll just say that each one of these has a height of 1 so what's the height of this well this has a child so we consider this to be 1 and this to be 1 so that would have a height of 2 all right and finally what height would this have notice that on its left side we have 1 2 3 but on its right side we have 1 2 so what would the high P this is very important the height would be the side with the most children so in this case this is the side with the most children so we'll consider this the height of the binary tree so this will have a height of 3 the next concept I should point out is very close to what we just did but just note that if a note is null we'll consider that to have a zero so remember we said this has 1 and this has 1 giving it a height of 3 that would mean that every time you see a null node that is a 0 so this is 0 and 0 all right so let's get more to the meat of the problem what exactly is an unbalanced binary tree is just a tree that has at least one node whose left and right sides have a height difference of more than one and I'll show you what I mean remember earlier we said this has a height of 3 so it's left side is 3 1 two three but in order for us to determine if it's an unbalanced binary tree we also have to take into consideration its right side it's right side like we said has a height of two so the difference between three on its left side and two is one will still consider that balanced it would be unbalanced if the difference is more than one so let's extend this binary tree to show you one that's unbalanced say this is seven and that has no children now what's the height of the left side versus the right side the height of the left side is now one two three four and the height of the right side like we said before is 2 4 minus 2 is 2 that would be an unbalanced binary tree and remember earlier I said that if any one of its nodes is unbalanced the whole thing is unbalanced so let's do another quick example and we can start with the bottom since that's more in line with how we're going to solve this problem so we'll start here is this an unbalanced binary tree the left is 0 and the right is 0 so no that's not unbalanced what if we go one level up it's right child a zero and it's left child is zero down here and one so it's left child is 1 minus zero is fine that's still considered balanced let's go up one more node how many children does 3 have it has zero children on the right and how many does it have on the left you're here this is considered one so is this sir how many children does this have it has zero on the right and two on the left 2 minus 0 is 2 remember you could have a maximum difference of 1 so this would be an unbalanced binary tree don't get confused with how sometimes I'm talking about children versus a tight it doesn't really matter the concept is the same we could have also found the same thing saying this has a height of 1 on the right side and a height of 1 2 3 on the left side what's 3 minus 1 that's 2 so it's unbalanced all right so the final tiny concept we have to understand is that we're taking the absolute value of the difference between the left and the right children what do I mean so the left side of this has 1 2 3 4 5 a height of 5 and the right side has a height of just 1 so that's 5 minus 1 that gives us 4 but what if the tree were set up a little differently what if instead this was the binary tree in this case the right side would have a height of 5 1 2 3 4 5 and the left side would have a height of 1 so we'd take 1 minus 5 that gives us a negative number but we can just ignore the negative so remember what we have to do is find the absolute value what's the absolute value of 1 minus 5 it's the same as the answer we just got which is 4 all right so the way we're gonna solve this is we're going to check the height of all the binary trees if the height difference between its left and right side is greater than 1 we'll return negative 1 instead so what we're actually doing is we're first checking to see if it's children have a value of negative 1 so because we're using depth-first recursion the first using depth-first recursion the first using depth-first recursion the first thing that's going to be checked is the left side of the number 5 so that's going to give us a value of 0 and what's the right side it's a value of 0 also so when you add 1 for the note itself its left side is 1 and it's right side is also 1 is that unbalanced well 1 minus 1 is 0 and we're allowed to have a difference of 1 so know that 1 is still balanced so now let's go up one level what's the height of the left side of the node with the value of 4 well it's left side has one more here so that would give us a total of 2 for its height and it's right side has a value of 0 here ignore this should really be moved over to like here because it corresponds to the number 5 all right so what's the height of the right side of the node with the value of 4 we have one here so is this unbalanced well its left side has a value of two and its right side has a value of one two minus one is one that difference is still acceptable because we can have a maximum difference of one so let's go up one more level what's the height of its left side well this is one so that'll be one two three and what's its right side it's right child gives us a zero so it's total right side gives us one what's the difference between three and one well that's a difference of two if the difference is 2 or greater we actually know that we have an unbalanced tree so what this one will return is negative one all right then it's going to check the right side is going to give us zero here and zero here so that entire level is going to be one so finally it says is my left or right side negative one and it is so overall that will return negative one all right so let's get to the code what lead code has given us is a function called is balanced which accepts a root is just the entire binary tree in this question we're going to assume that if the root is null then the binary tree is balanced so we'll say if root is null it will just return true okay and the way I'm gonna solve this is I'm gonna have a helper method which gets me the height of the entire binary tree and remember I said that if the height on either side is unbalanced I'm just gonna return negative one so overall I'm just gonna check whether the method that I'm gonna use is going to return to me a negative one so I'll say return get height a root and see if that doesn't equal negative one because if it does equal negative one that means it's unbalanced and if not then we know it's balanced all right so let's write the helper method we know it's called get height so let get high equal to function which will accept a node remember each node is itself a binary tree and we know that if the node is null it'll return a 0 so if notice null will just return 0 and we know we're going to use recursion so we'll recursively find the height of the left and right notes so we'll say let left equal get height of node dot left and we'll say let write equal it get height of node dot right so because of the way we've set this up so far the first thing it'll check is here this is going to be 0 and this is going to be 0 now we'll check whether or not that's unbalanced so we know that if either the left or the right is unbalanced we have an unbalanced tree and I mentioned earlier I just haven't put this in the code yet that if it is unbalanced that it'll have a value of negative 1 so we'll check if left equals negative 1 or right equals negative 1 then we'll return negative 1 all right as I'm editing this video I realize I might not have been clear what this line means what I'm talking about left and right it's talking about the heights of the children I've already calculated so if either one of them is negative 1 meaning if any one of my children is unbalanced then I'm gonna be unbalanced and I'm gonna pass that negative 1 all the way up to the top so now every node above me is also going to have a value of negative 1 why else would we return negative 1 we'd return negative 1 if the absolute value of the difference between the child nodes is greater than 1 so we'll say or math.abs left - the right we'll say or math.abs left - the right we'll say or math.abs left - the right is greater than 1 I know I've said it a bunch of times before but I'll say it again that's because to be balanced we can have a maximum difference of 1 so that's just checking to see if the absolute value of the difference is greater than 1 and if it is we know it's unbalanced so we'll return negative 1 to signify that but if we've gotten past that step we know that it's not unbalanced so now we'll just return the maximum of the left and right children so left and right and we have to add 1 to the height so this is the entirety of the code right now but I'll just walk you through all of the code using the binary tree on the left just to show you exactly how it works all right so as we said it starts all the way at the bottom left that has a value of 0 and the right side has a value of 0 so it will return the maximum of those two what's the maximum of 0 and 0 it's 0+1 that's what's happening on line it's 0+1 that's what's happening on line it's 0+1 that's what's happening on line 32 so here would be a value of 1 then we get bumped up a level on line 21 it asks if the note is no it's not so we go to line 25 925 gets the height of the left node we know the left node is 1 line 26 gets the value of the right node it asks if the node is null yes it is so that half will return 0 then it'll check on line 28 if either the left or right children is a negative 1 meaning we already know it's unbalanced and no it's not or the difference between the two is greater than 1 the difference between the two is 1 minus 0 that's not greater than 1 so it goes to line 32 and it adds 1 to our height so our height right now is so then we get bumped up one level it asks if the node is null on line 21 no it's not on line 25 it says give me the height of the left child we know that's 2 on line 26 it says give me the height of the right child so it goes back to line 21 and checks if that note is null yes it is so then it returns zero on line 22 so now we know the left side is 2 and the right side is 0 so it checks is the left side negative 1 no it's 2 is the right side negative 1 no it's 0 is the absolute value of the difference between those two greater than 1 2 minus 0 is greater than 1 so in this case we'll return negative 1 so now we're bumped up one level to the node with the value of 1 the very first node is that null no line 25 retrieves the value of the left node which is negative 1 then it's going to check the right side so because of recursion that would put us here the left side of this is 0 the right side of it is 0 so it's going to see if that's unbalanced no it's not so line 32 is going to add 1 to this so the value of this is 1 so now we know the value of the children of the left and right halves of the top node the left is negative 1 and the right is 1 so when we get to line 28 it says if left is negative 1 is it yes so it immediately returns that this is also negative 1 so now there are no more nodes to check so we get kicked out back to line 17 and that says return whether or not this doesn't equal negative 1 it does equal negative 1 which means that this is unbalanced all right so let's run the code see how we did all right accepted let's submit all right so it's saying so then about 27% of other JavaScript so then about 27% of other JavaScript so then about 27% of other JavaScript submissions as usual the code and written explanation are linked down below if you liked the video give it a like and subscribe to the channel it helps out a lot see you next time
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
285
welcome back to the cracking paying youtube channel today we're going to be solving lead code problem 285 in-order solving lead code problem 285 in-order solving lead code problem 285 in-order successor in a binary search tree given the root of a binary search tree and a node p in it return the in order successor of that node in the binary search tree if the given node has no in order successor in the tree return null the successor of a node p is the node with the smallest key greater than p dot val so for example if we were given that p equals 4 then we should be returning 5 because that's the next greatest element you know greater than 4. so how might we solve this problem well an immediate naive solution is simply to perform an in-order traversal of this perform an in-order traversal of this perform an in-order traversal of this binary tree so we're going to do the inorder uh traversal and the reason that we do an in-order traversal is because an in-order traversal is because an in-order traversal is because remember that for a binary search tree if we perform an inorder traversal it's going to return the nodes in sorted order so for example it would return one two three four five and six and you know we'd return an array like this then what we could do is traverse this array and find our node um you know p equals four here so we'd find the node and then the next greatest element is simply the element whose index is one greater than the one that we found for if it happens to be that we found the you know element we're looking for and it's at the end then there is no inorder successor and we would simply return none but in this case it's the five so this is the naive solution so you know we'll achieve a run time of big o of n which doesn't seem that bad but because we need this array to store the values we're also going to have a big o of n space complexity which we can actually bring down to big o of one if we are a little bit more clever and figure out how to do this in place without needing to parse out the entirety of the binary search tree first so let's think about how we might solve that more optimally we went over the naive solution to this problem but i mentioned that there's a better solution in which we can actually use no space well the way that we're going to do this is we're going to make use of the properties of our binary search tree and remember that in a binary search tree for any given node so let's say we're at this node 5 every node in its left subtree must have a value less than 5 and every node in its right subtree must have a value greater than 5 and that is the definition of a binary search tree we can know that this is true because we're given a valid binary search tree so what we want to do is for this algorithm we're going to start at the root and what we're going to do is we're going to check because root is our current element that we're at we're going to check if the current element so this 5 is actually greater than or is it less than our value 4 here and why is this significant if the value is actually less than what we're looking for then that tells us that we don't have to explore anything in the right sorry in the left subtree because we know that all values are going to be less than the current element and if the current element is already too small then going left there's no point in that case we just want to go right and then retry our logic so what is our core logic here in this case 5 is actually greater than 4. so what we're going to do is since 5 is greater than 4 5 is a potential in-order greater than 4 5 is a potential in-order greater than 4 5 is a potential in-order successor of the node 4. in this case it is the actual inorder successor but we wouldn't know that without exploring the rest of the tree so we're going to say that 5 is a potential successor so we're going to set up a variable and we're going to say successor and we're going to set it originally equal to none but now that we have found a value that's greater than four we're going to overwrite it and now say it equals to five and what we're gonna do now is we're gonna go into the left subtree of five and then look for another value that is greater than four in hopes of finding you know a successor that's now a little bit closer to four than five was and we're going to continue this so we go to this three and we see that okay well you know this three is actually you know two too small so that means that we can ignore this left sub tree entirely because we know that it's we're not gonna find a solution here so we're gonna have to go into its right sub tree and at this point what we're going to do is we're going to see that we're at 4 which is our value so you know obviously we don't want to say that something is an it or a successor of itself so we're going to try to do now is since this value is you know equal to 4 we would want to go into its right sub tree to hopefully find a larger value but when we go to its right subtree we're going to see that it's actually none and at this point our you know traversal will terminate and we you know can simply return whatever successor we found so it's going to be this five now let's look at a different example where instead of saying that our six that p is going to be um four let's say it equals to five so what do we do so we're at this node five which means that um you know we are equal to the node that we're looking for so obviously this can't be our successor because you know it's the node that we're looking for so what we need to do now is realize well if we're going to look for an element that's larger than 5 we can't do it in this right subtree it's in the left subtree sorry because every node here is going to be less than 5. so that means that we have to go into our write subtree and we're going to end up at this node 6. so is this node 6 greater than our node 5 yes which means that it's a potential in-order successor so we're potential in-order successor so we're potential in-order successor so we're going to say successor is now going to equal node sixth and what we're going to do now is okay what we want to do is we want to go into its left subtree because this node is actually greater than six or sorry greater than five and what we're going to want to do is hopefully find a value that's closer to five so we try to go into its left subtree and we see that it's none and now our iteration will finish because there's nowhere else for us to go right we can't go up the tree we can only go into its left or right children so at this point we would finish and we can return that the successor is actually 6. so that's the general algorithm we want to use it's a little bit confusing but essentially what we want to do is we're going to have a node which is going to be you know our current node representing like where we are in the iteration and if the current node its value is actually greater than or equal to the value that we're looking for then what we want to do is we want to go into the right subtree of that value and hopefully search for something that is um you know a little bit smaller and then what we want to do otherwise so you know we'd end up at this six and if our value is actually you know less than or equal to the um value sorry if p is actually less than or equal to the value that we're currently at then this node becomes you know a successor candidate and we can keep track of this and hopefully find you know better successors as we go down the tree so it is a little bit confusing to explain it but i think once you see the code it's just a few lines and it's really simple i think it's more of just wrapping your head around why it works and how we can use the properties of a binary search tree so let's go into the actual editor and we can write this out and it should be a whole lot clearer than the actual diagram ever will be so i'll see you there now it's time to write the code remember that we need a variable to track our successor and originally it's going to be none in the case that we actually can't find a successor we want to just return none and what we're going to do after we do all of our processing is to return whatever successor we found so we're going to say successor is going to equal to none and what we want to do now is iterate through our tree while we still can so basically we're going to try going to left or right subtrees while you know we still have nodes to process and when we hit a null node that's when our iteration is going to end so we're going to say while root we're going to say if p dot val so the node that we're looking for while its value is actually greater than or equal to the current node that we're at then that means that um we want to go into its right subtree to potentially find that next larger value right because we're looking for the in order successor of p so if p's value is already too big then that means that we have to go into the right sub tree and to potentially find a larger value we could ignore the left subtree because we know that if you know this root.val is already too small then this root.val is already too small then this root.val is already too small then going into its left subtree there would be no point because we're just going to find smaller values we need to go into the right subtree and use that property of a binary search tree to hopefully find a bigger value so in this case we're going to say root is now going to be root.right so we're now going to be root.right so we're now going to be root.right so we're going to go into the right subtree of our current node otherwise what we need to do is the node that we're at is actually a potential successor so we're going to set it to be you know the current node that we're at this root and then we're going to go into the left subtree to hopefully find one that's actually closer to you know our target p because we want to get the next largest node we don't want just any larger node we want the one that's closest as possible to the node itself and then what we do is we're going to go into the left sub tree to look for it so we're going to do that until obviously our iteration finishes when root becomes null at some point doing this root.right null at some point doing this root.right null at some point doing this root.right or root.left will give us a null node or root.left will give us a null node or root.left will give us a null node and then we can stop processing because we know that we've done it at this point all we have to do is simply return the successor oops successor and we're done so let's submit that double check that it works and it does cool so what is the runtime complexity of this algorithm well the runtime complexity is going to be big o of n in the case that we don't have a balanced binary search tree it's going to take big o of n time if we had a balance tree it would take on average you know log n time because it's a binary search tree but because we can't be guaranteed to have a balanced binary search tree it's going to be big o of n you know think of it as like being a tree that's like all one you know all right nodes or like all left nodes right we would potentially have to go to that very bottom node to find our solution what is the space complexity well because we're doing everything in place here and you know we don't define any extra space except for this like successor variable which is just holding um you know basically like a pointer to a node this is going to be our constant space solution and you know this while loop can be thought of like the as the iterative solution we're not actually doing anything recursively here so this is going to be a constant space solution and you know this is going to be the best solution that you can do so we were able to bring down that big o of n run time by doing it the naive way where we just parsed out all the elements and then tried to find the next one in the list of the sorted elements that we got back from the inorder traversal so that is obviously one way you could do it but your interviewer will probably ask you as a follow-up to solve it in ask you as a follow-up to solve it in ask you as a follow-up to solve it in constant space so you definitely want to know the solution anyway that's going to be how you solve this problem if you enjoyed this video please leave a like comment subscribe if there's any videos you'd like to see in the future please let me know in the comment section below and i'll be happy to make those videos for you guys just tell me what you want to see and i'll do my best so in the meantime happy coding bye
Inorder Successor in BST
inorder-successor-in-bst
Given the `root` of a binary search tree and a node `p` in it, return _the in-order successor of that node in the BST_. If the given node has no in-order successor in the tree, return `null`. The successor of a node `p` is the node with the smallest key greater than `p.val`. **Example 1:** **Input:** root = \[2,1,3\], p = 1 **Output:** 2 **Explanation:** 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], p = 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.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,173,509
237
alright this li code question is called delete node and a linked list it says write a function to delete a node except the tail in a singly linked list given only access to that node so given the linked list which has a head of four and the rest of the linked list is 5 1 9 let's say we're only given access to the node 5 and we want to remove it the output should be 4 1 9 example 2 we're only given access to this node and we want to remove it we want our final answer to be 4 5 9 then it says the linked list will have at least 2 elements all of the nodes values will be unique the given node will not be the tail and it will always be a valid node of the linked list and do not return anything from your function all right so let's say we want to remove the node 5 usually when we want to remove a node from a linked list we have access to the node in front of it so usually what we do is we just set the property of the node in front of it to the node after the node we want to remove so in this case we would have at the end 4 1 9 no but what this question is saying is we don't have access to the node in front of us so we'll get rid of all this sort of look more like this we want to remove five without knowing what's in front of us so just to represent a linked list another way let me bring this up so if we look at this the first value is four and it has a next property that's pointing to a node with a value of five that has a next property that's pointing to a node with a value of one etc and as we can see each node is very simple it just has a valve property and the next property the key to solving this is all we really have to do is make the node we're on look like the node that's after us and then point our next property to the node after the note that we're pointing to right now I know it sounds confusing so I'll show you what I mean so just remember that we're talking about the node five as the one that we want to remove so we'll just make five instead of five we'll make it one which is the same as the node after us down here just to show you what it look like more in the code this value would be one all right so far we have four one nine null remember what we need is four one nine no and we still just have access to this node but all we have to do now is point this arrow instead of to the node after us will point to the node after that which would look like this one now points to nine so if we look at it our linked list is now four one nine no we've successfully removed the number five so the final step down here is the next property for the number one instead of pointing to what we had it before which was next which was the node with the value one will pointed to next dot next which is the value 9 all right so leap code has given us a function named delete node and it accepts a node remember this is not necessarily the head of the linked list it's just the node we want to remove all right so if we look to the left each of these arrows it's just this nodes dot next property so five dot next points to one four dot next points to five one dot next points to nine and nine dot next points to no all right so let's just pretend it's the number five that we're removing remember what we have to do is we have to change the value of the node to the value of the next node so that would be node dot Val which right now is the number five we're gonna change it to node dot next Val so for on five dot next points to one and we'll change it to that value which is 1 all right so now our five becomes the number one and the only thing we have to do next is change the next reference of the node we're on which is pointing to the number one to the reference of the next node after that which is pointing to the number nine so our code is just node dot next which again is pointing to the node after it that has the number one - node after it that has the number one - node after it that has the number one - node dot next which is the number nine so we're here no dot next right now is pointing here but instead we're gonna have a point two no dot next which is the number nine so that would look like this now this points here so just note that since nothing in this linked list is pointing to this node anymore our linked list is now really just four one nine no all right let's run the code looks good let's submit it all right so our solution was faster than about 29% of solution was faster than about 29% of solution was faster than about 29% of JavaScript submissions as usual the code and written explanation or link down below if you liked the video give it a like and subscribe to the channel see you next time
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
260
hello and welcome to my channel so today let's look at the lead coder 260 single number three so uh given integer array norms in which exactly two elements appear only once and all the other elements appear exactly twice find the two elements that appear only once you can return the answer in any order you must write an algorithm that runs in linear runtime complexity and the use is only constant extra space for example one two one three two five the output is three five or five three because the three and the five only appeared once and uh example two uh the other model will be minus one zero because uh the other they are they both appear only once and similarly for example three so the norm's length is between 2 and 3 times 10 to the power 4 and the norm's eye is a integer range so each integer in norms will appear okay yeah so the question is this question we can use a bit operation to do that um so mainly we are going to use xor uh here because each two elements appear only once and all the other elements appear exactly twice so one and xor there is a few properties y is a like the same number xor itself is zero um and if xo a x or zero will equal to a itself and so and also the order doesn't matter so you can do a x or b and then x or a so it will be still it will be equal to b so uh if like a element so in this case example in this question it's like you have a many like elements appear twice so those elements will be cancelling each other after xo so in the end for example you have a bbc c d in the array then you xo all of them then in the end you will get a and the x or c um so the first step is xo or the elements then you will get a we can call in a diff so it's a like so x are all the elements in the array and then we needed to um we need to use a trick called uh um so if we do an end if my and minus if whatever this do so assume diff is uh in binary uh format is like this so that then just give and the manuscript will only keep the last center uh one last set bit in the in this integer and then so the d4 minus the different minus df we will getting this number um so then we can at the last center bit in the diff so um so uh so the last uh center bid is uh after we got the last set bid we actually know that either in this example either a have data being said and the b does not have that b set or there's a two possibility or like a have that b i have that a does not have that b set and the b oh actually c i mean the two single number it does not have that difference and i see have that has that she has that big set because the a and the c must have one number as a one in that location and uh the other number in the um see now the other number will have zero in that location it must be different otherwise the xor will be zero so either a will be this number serial or c will be like so it doesn't matter like which one is which one whether we know that uh one of them one of the number have the piece set in this uh did like have this be said the other one has just been not set so um so what we can do actually is we can do a like for all the for num in the norms we just um check if num and the diff is a larger than zero or equal to zero so if it's uh if it's larger than zero that means that number has one center in the uh has that big cell so we actually excel with uh we can actually uh in that group so we can define our answer array then we just here we just need to excel the that norm so what we did is uh what we did is we actually separated the uh all the norms to two groups one group will containing in a in this case the other group will contain c but like uh in this group we can make containing other like elements but they are actually just appear in the pair like uh all the others all the other uh numbers are in pair but only like a appear the ones in this group and then similarly for the other group so what we need to do is just x or all the elements in this group then we will get a and all x and all the elements in this group we will get c so in uh we will then we will get the answer array so uh the time complexity is a is o of n and the space is a space we didn't use an extra space so it would be 001 so let's uh start coding uh so firstly we want to maybe define x or sum it's zero it started with zero so we uh for order and num we just xor all the numbers um then after down this we do our x or uh with the negative xo sum so um well actually maybe we can do making the clear a little easier to read so yeah we can assign another called this so this one will um have the last um only have only leave the last third bit of actual sum everything else that will be set uh will be set at zero so only the last sub bit will be in the diff so um yeah then we actually can define answer array which is the two elements then we get a we use all the norms to so if the norm is a and the diff is larger than zero so which means uh that it has that bit set then we put in the uh we can put in the one so we just xor that number else means that bit is not what not said we will like excel with the answers array zero then we just return in and we just return the answer array so okay yeah so this works and uh so the this question the testing point is the xor and also you need to remember this uh this trick um so hot lager using an end and a negative value so it will get a set of the last uh leave the last set bit but everything else will be set at zero so let's conclude today's essentials thank you for watching see you next time
Single Number III
single-number-iii
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. **Example 1:** **Input:** nums = \[1,2,1,3,2,5\] **Output:** \[3,5\] **Explanation: ** \[5, 3\] is also a valid answer. **Example 2:** **Input:** nums = \[-1,0\] **Output:** \[-1,0\] **Example 3:** **Input:** nums = \[0,1\] **Output:** \[1,0\] **Constraints:** * `2 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each integer in `nums` will appear twice, only two integers will appear once.
null
Array,Bit Manipulation
Medium
136,137
899
hey everybody this is larry this is the 5th of september hit the like button hit the subscribe button hit join me on discord uh let's talk about these daily problems every day for the rest of the month come hang out okay so today's problem is orderly queue um before we start i just want to say that i usually start these lives so watch it on your own speed uh and i don't know i usually say we should celebrate stuff um but i in the last two contests i finished a little bit out of the top hundred so is that good enough i don't know let me know uh but basically i was top 110 twice so that's uh that's my reason for now anyway okay um let's look at today's problem which is orderly q so you're given a string s and a k you could choose one of the first k string s and return the lex okay and so one thing i would say is that when you think about any number of moves um you can you know think about it but in this case one of the first k okay hmm so if k is equal to 1 then we just do a tie breaking from every smallest thing right so we just sort and then that's n square ish what happens if n is uh basically like some rotation of s is the answer is k is equal to one right what if k is equal to a um i feel like this is a trick question uh let's start so k is equal to one that's let's write this down like as you go to one the answer is a rotation of x s right what's k equals to two what does that mean um like my question is can you just literally sort the string right uh on two so let's just say you have something like that say uh you can even add more letters so i don't know if adding more letters change the answers that much but if k is equal to 2 then what does that mean first k let us know if k is equal to 2 then we can de facto can what is the strategy for k is equal to two that's what i'm trying to think right now um so what happens after one iteration you keep one character in the front as kind of the temporary variable you want to call it that and then just loop and then you could think about um if you have two rare two numbers right or sorry two counters in the front you can think about one of them as the variable and then the other one is just rotating through the entire way right um and can we do anything from that observation um so you could either get the min or the max does that decide them help let's say we get the men right hmm this is an annoying problem let's say we get the min and then we push it to the back does that change anything i guess what i'm trying to think is i try to think if there's any strategy that we can do to kind of sort the string right let's give it enough k we can definitely sort the string what does that look like okay this is too long so let's try something even dumber so let's just do abcd right or maybe let's just say it's backwards right um then what happens then here we can what are some strategies that we can do right we can go to so let's just say we move to c and we put d in the back so then we have b a d and then here we let's say we keep b for some reason i'm just playing around with this so don't hold me to it and then now we put it so that now we have a dcb and we have a in the beginning and we already did is rotated to be honest kind of and then now we can rotate again so now it's a b um dc but then now this is sorted right so then now we can let's just say uh put a and the b in the back so now we have d c a b can we and then now let's say we move the d to the back right so then now we have c a b d and then eventually you're going to get the c d a b again and then now you could put a c in the back i think i've messed up actually i think here already you can already put the c in the back so it's a b c d and then that's already sorted right now can i generalize this yeah because i think basically what you're saying is that you want to get one character at a time in a way right so basically for example and you can you could so you can keep on looping on a thing so then this becomes a min and it becomes an insertion sort so if k is equal to two you can sort the string and if is that true let me play around with a little bit more so basically let's just say we have okay i banged on the keyboard um so then here we let's just say we keep a in the beginning and then here in the rest we just have uh this in some order i mean i guess this is the same order right um and then now so now we have a in the beginning so then now we go we sort the second character say um by my space key's a little stuck so now how do we get the second smallest character right so well we put the a in the back so now we have this for example and then now we just keep on rotating until we get the second smallest character so then now we have um let's just say um well let's just say dr e uh d a w r um keeping the second one um and then now let's just say we know that d is the second smallest character so then we rotate it until a goes to the back and then now we put d behind it right and then now we could do the same thing so i think after k equals 2 because and because k equals 2 if k is equal to 3 you don't even have to use the third character if that's the case um so that means that in that case if k is greater than two i might be wrong on this one though to be honest i didn't it's an intuition uh you through test cases but um but yeah so okay so actually if k is equal to one we do this thing with the um with the rotation um can we do it in better spread i don't know otherwise we return a sorted version of um join it again i think maybe uh so okay let's see if this works first in code so um uh two it return okay so this does return what i want and in a cheating kind of way we see the expected answer so i think i'm more confident about it though that part is cheating but uh but yeah we have to figure out this part which is just um no uh the answer's a rotation of s so we can yeah i mean maybe there's a fun way of doing it but i think that's still um this log no this could be at least all of em so that i think that's still o and square if we do some kind of sorting things so yeah so let's just do the thing which is that for start is in range of n where n is length of s then current is equal to s of um to start let's just say best is equal to s if as if current is less than s then best is equal oops if current is less than best is less equal current return best okay so let's give it a submit okay cool um yeah i don't know how to explain this one that well to be honest you saw what i did i think what i did was i just thought is it i think for me i just thought like for k e goes two um is there a special case for k equals two if not is the case for k us three i had an intuition that for k equals three um that's enough things to kind of uh be sorting but i wasn't sure about k e goes to so that's why i was kind of going through the cases and trying to think and once you are able to do it becomes kind of like insertion sort is the way to think about it um i don't know how to kind of i mean i know how to explain the reasoning but i don't know how to explain how to get there so that's what i like about this video maybe is that you kind of saw how i did it which is just took a lot of examples and play around with it and see if i could get there uh yeah so this is gonna be n squared time because yeah this sort so this is an n loop and this comparison is over n so it's going to be n squared you know it's pretty fast n squared um otherwise it's just n log n but in the worst case it's going to be n squared so yeah in terms of space i guess this is linear but you can actually do better but this is also linear so maybe you can't i don't know uh yeah that's all i have for this one what a silly problem i think but yeah i'll talk to you later stay good stay healthy to good mental health have a great rest of the week have a great sunday i'll see you later and good mental health bye
Orderly Queue
binary-gap
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "acb " **Explanation:** In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ". In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ". **Example 2:** **Input:** s = "baaca ", k = 3 **Output:** "aaabc " **Explanation:** In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ". In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ". **Constraints:** * `1 <= k <= s.length <= 1000` * `s` consist of lowercase English letters.
null
Math,Bit Manipulation
Easy
null
1,275
hello everyone and welcome back to another video so today we're going to be selling the lead code question find winner of a tic-tac-toe game alright so winner of a tic-tac-toe game alright so winner of a tic-tac-toe game alright so in this question we're going to be playing a tic-tac-toe game and the two playing a tic-tac-toe game and the two playing a tic-tac-toe game and the two players are going to be a and b on a three by three grip so first they gave us the rules of tic-tac-toe so real us the rules of tic-tac-toe so real us the rules of tic-tac-toe so real quickly in the beginning we're going to have an empty board okay so let's actually just draw it out so this is what our three by three board is essentially going to look like so we have a three by three just like this okay so there's nine possibilities and the way this is going to kind of index is we're going to have zero uh column first column and second column zero throw first row and second row so let's say if someone is putting a marker at a certain spot then let's say they want to put it over here so we would go to the first row and the second column and we would put either a x or o depending on the position okay cool so now what do we have so now the first player is always going to be a and a always places the x character well the second player is going to be b who always places the o character okay so x and no characters are always placed in empty squares never on filled ones so if something already exists at a certain spot you cannot put an o over here or an x again okay you can only put it at empty spots cool so the game ends when there are three of on the same character filling in a row column or diagonal okay the game also ends if all squares are not empty or there are no more moves that can be played if the game is over okay so the way you can win is there's actually eight ways and these eight ways are actually pretty important so let's just keep track of it so the first possibility is if you have something like this xxx they're all in the same row okay so in this case this is one possible way so you could have that for the zeroth row you could have that for the first row and you can have that for the second row so essentially by row you have three possibilities okay so let's say rows and there's three possible ways to win by just the rows okay now another possibility is the column so you could have something like this so in this case there's again three possible ways by column so you could have either the zeros column the first or the second column okay so let's write that as well so we have column and this is going to be three possibilities now the final thing is diagonals so we could have something like this or we could have something like this okay so if i'm not wrong this is the primary diagonal and this is going to be the secondary die right so in this case uh we have two possible ways to win through diagonals okay so let's keep track of that as well so this over here how many so how many possible ways do we actually have to win so the possible ways we have to win are three plus three six plus two which is eight okay so we have eight possible ways to win given this game okay so now let's move on to the second part and it says we're going to be given an area called moves where each element is another area of size two corresponding to the row and column of the grid where they mark their respective character in the order in which a and b play now remember a plays first and then b then a b and so on and so forth so the goal here is to return the winner of the game so if there is a winner it's either going to be a or b and that's what we return but there could be a condition where all of the squares or places are filled but there is no winner so in that case we have a draw and another possibility is there are remaining spaces but we did not finish the game yet okay so that means we return pending in that case so you can assume that moves is valid and the grid is initially empty and a will always play first so let's just see an example where these are the moves that we have all right so let's say we're given these moves over here and let's just see what the first naive kind of solution would be so that would basically be to first populate this three by three grid and then perform three row checks three column checks and two diagonal charts right so let's just actually first do that real quickly so first would have zero so remember x starts first always then we would go to two zero so two zero that would be o one for x and then two one for o and then finally two for x so now in this case first we perform three row checks so row check no one has one in this case so we leave it as it is then we do three column checks no one has one either and finally we do let's say we do this diagonal check first and then we do this so finally at the last diagonal check we found out that someone has one we return eight now if at this point no one has one it's either a tie or pending and that's how and we need to figure that out so another thing to do instead of doing this several times is we could do all eight of these at the exact same time and instead of populating this we just look at the moves itself okay so let's see how we could actually do this now the way we're gonna do this is we're gonna have two areas one for a and one for b okay now both of them are going to be initialized with zeros and there are going to be eight zeros okay so y eight okay let me just do this real quick so one two three four five six seven eight and we're gonna have eight zeros for b as well so three four five six seven eight cool now what do these eight zeroes represent and in simple words there are eight ways to win and what we're essentially going to do with this area is to check if we have one with any one of those eight of those ways okay so if we have one in a one in any of these eight ways that uh player is a winner now the way we're gonna do this is like i said we could do all three so three plus two of them all them separately right but instead we wanna kind of do them simultaneously so this is where this area comes into play so what we're going to do is we're going to kind of consider these first three elements to check if we are if you want a row okay so this is going to be the first three elements okay so this is going to check if we've won in a row okay and the second three elements checks if we won in a column okay so this is the second three and finally the last two check for diagonal okay now what exactly does this mean so the idea here is very simple so what we do is what is the first move i did so the first move i did over here actually let me just do it from scratch i think that will be easier so the first move i did was zero and that is going to be a's turn so i put x over here and i'm just drawing this for visualization purposes so over here what that means is i've placed a marker in the zeroth row and in the zeroth column and in this diagonal okay so when i place an x over here it is important so that could mean that i could possibly win in the zeroth row i could possibly win in the zeroth column and the primary uh in the end the primary diagonal over here okay so that is exactly what we're gonna do so zero so i'm gonna account for this at all the places so this refers to the zeroth uh row this refers to the first row and this for the second row same way zeroth column first column second column and then we could do primary diagonal and then secondary diagonal okay so now when x is here that means i have an element at the zeroth row which is x okay now the same way i that also means i have an element at the zeroth column so this increases by one and that also means i have one element at a primary diagonal okay so now it is b's turn so b goes to 2 0 right over here so now it's the same thing so this is important for the second column okay so sorry second row so u is o could win in the second row o could win so this also corresponds to the zeroth row and the secondary diagonal so we do the exact same steps so we go to the so in this case we go to the second row and increase b's value by one okay saying that we have one marker in the uh in this row over here okay so now the same way uh this is also at the zeroth column so this would become one now and finally it is in the secondary diagonal so this becomes one okay so now we move on to two zeros so let's go through this a little bit faster so at two zero uh sorry add one sorry mother uh we would have x over here so now we have one at the primary diagonal at this row and at this column so we gotta account for all three so we now go to so this is at the first column this is at the first row as well and we have another for the primary diagonal so now it's saying we have two x elements in the primary diagonal now if this becomes three that means that we have one at the primary diagonal in fact if any of these values ends up becoming three that marker or player has already one okay so now let's just go on for the last two so we have two comma one so two comma one would be an o over here so this corresponds to this and yeah that's it there's no diagonal in this case so this would be the second row so now we have two o's in the second row now again what does this mean this means we're just one away from possibly winning for o add that row so specifically at the second row now we're also going to account for the first column so this becomes 1 and that's it now finally x ends up winning in this case and what does x do x plays 2 so which is exactly over here so 2 comes at the second row so we have one x over here at the second column so there would be one over here as well but now the most important thing is now it's part of the diagonal as well so this now we increase its value and it ends up becoming three so at this point when it ends up becoming three that means we have one so when like i said when any of these becomes three then we have one in one of the possible eight ways so the only difference by using this method is instead of doing three row checks and three column checks and two diagonal checks we're doing all each of them at the exact same time by just using an extra area now there's one small thing to do uh which we might so in this case would end up returning a okay and if b1 we would return b now the last thing is if we go through all the moves and there is no winner and the way we know there's no winner is if we iterate through a and b and we don't actually end up returning anything that means that we don't have a winner so it could either be a tie or the game could be pending the only way we actually know that is if the moves over here are equal to 9 so if the number of moves are equal to 9 that means that all of these are completely filled up and that means it's a tie so if moves is equal to nine we're going to end up returning tie but if that is not the case that means that the game is still pending and that's what we end up returning okay so this is the solution and now let's just see what this looks like in code all right so the first thing we're gonna do is we're gonna define our two areas a and b and these are gonna be the zero areas with a length of eight representing all the eight possible ways we could win so now we have a and b now we gotta iterate through our moves so we're gonna go by index and the reason we're gonna go by index is because every time we're at an even index so zero two four that means that the player a is winning in other words it is x's move okay and when that's not the case when we're at an odd index well that means that it is uh oh so player b's turn or in other words o is playing okay cool so now we need to get the two moves so this is going to be in the format of row comma column and the way we get this is we go to moves we go to the index and a row is going to be at the zeroth index and columns at the first index but we could just get it okay so real column zero uh row comma column is equal to moves index okay so now we need to define what we're actually on so who is actually playing right now is it a or b and like i said the way we do that is if index is uh even so if index mod 2 is equal to 0 and in that case the player is going to be a but if that's not the case then player is going to be b cool so now we know who the actual player is so now we just got to populate this array over here so we go to the players area that could be a or b and the first thing we can do is we account for the row so the way we do that is we go to the row itself right so that would either be the index zero one or two and we add that by one now the question is how do we do this for our column okay so it's not this so in simple words let's just go back to drawing so at the zeroth index so this is a the zeroth row first row and second row cool but now the columns are three away so this is at the third index is at the fourth index and fifth index so in other words the zeroth column is zero plus three okay the first column is one plus three the second column is two plus three okay and that's exactly what we're going to do so the column number plus three okay so over there we're going to populate uh increase it by one okay so now we took care of the row and we got took care of the column now we got to take care of the diagonals so the primary diagonal is very simple and the reason it's primary is because well this is at the index zero one and two okay now the way we actually do this for the secondary diag okay so let's just implement this first okay so the way we get that is if the row value is equal to the column value then that means we are at a primary diagonal so in that case we go to the last but one index okay so we assigned that let's say so that's the sixth index right so at the sixth index we're going to increase its value by one and another condition is if it is at a secondary diagonal and to actually get that is if the row value so let's take an example so it's a d3 right so if the row whatever the value is equal to two minus the column then we're at the secondary diaphragm okay so zero two and two minus uh so the column here is two and two minus two is zero so it is part of the second diagonal so over here we have one and one so one is equal to two minus one and the same way uh so in this case we have two and zero two is equal to two minus zero okay so this is how we get the secondary diagonal so if rho is equal to a two minus column and in that case that means that the secondary diagonal has a value so that is the last element or in other words the seventh index so plus equals one cool so this considers all of them so this does the row this does the column this is primary diagonal this does secondary diagonal now we're done with this okay so all we have left to do is we have these two areas and we gotta iterate through these two areas to check if anyone has one okay so we could just do for i in range and the range is going to be eight but this would be specific length of a for example and in this case we go to let's say first we go to a we go to the index i and check if it has a value of three now if it does that means a has one and we return a okay but the other condition is if you go to area b at the index i and if that is also equal to three and in that case well we're going to end up returning b that means b has one now if none of these happen we have two conditions which is it could be a draw and or a tie sorry it could be a tie or a pendant so if the length of moves is equal to nine that means that it is a type so a draw sorry so we're going to end up returning draw okay now if this is not the case well that means that the game is still pending so we just do return pending so let's submit our resolution and as you can see our submission was accepted so thanks a lot for watching guys and do let me know if you have any questions bye
Find Winner on a Tic Tac Toe Game
validate-binary-tree-nodes
**Tic-tac-toe** is played by two players `A` and `B` on a `3 x 3` grid. The rules of Tic-Tac-Toe are: * Players take turns placing characters into empty squares `' '`. * The first player `A` always places `'X'` characters, while the second player `B` always places `'O'` characters. * `'X'` and `'O'` characters are always placed into empty squares, never on filled ones. * The game ends when there are **three** of the same (non-empty) character filling any row, column, or diagonal. * The game also ends if all squares are non-empty. * No more moves can be played if the game is over. Given a 2D integer array `moves` where `moves[i] = [rowi, coli]` indicates that the `ith` move will be played on `grid[rowi][coli]`. return _the winner of the game if it exists_ (`A` or `B`). In case the game ends in a draw return `"Draw "`. If there are still movements to play return `"Pending "`. You can assume that `moves` is valid (i.e., it follows the rules of **Tic-Tac-Toe**), the grid is initially empty, and `A` will play first. **Example 1:** **Input:** moves = \[\[0,0\],\[2,0\],\[1,1\],\[2,1\],\[2,2\]\] **Output:** "A " **Explanation:** A wins, they always play first. **Example 2:** **Input:** moves = \[\[0,0\],\[1,1\],\[0,1\],\[0,2\],\[1,0\],\[2,0\]\] **Output:** "B " **Explanation:** B wins. **Example 3:** **Input:** moves = \[\[0,0\],\[1,1\],\[2,0\],\[1,0\],\[1,2\],\[2,1\],\[0,1\],\[0,2\],\[2,2\]\] **Output:** "Draw " **Explanation:** The game ends in a draw since there are no moves to make. **Constraints:** * `1 <= moves.length <= 9` * `moves[i].length == 2` * `0 <= rowi, coli <= 2` * There are no repeated elements on `moves`. * `moves` follow the rules of tic tac toe.
Find the parent of each node. A valid tree must have nodes with only one parent and exactly one node with no parent.
Tree,Depth-First Search,Breadth-First Search,Union Find,Graph,Binary Tree
Medium
null