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,679
everyone and welcome to another tutorial today we will solve lead code 1 1679 problem max number of K on pairs let's read the description you are given an integer array nums and an integer key in one operation you can pick two numbers from the array whose sum is equals to K and remove them from the array return maximum number of operations you can perform on the array so you should only return the maximum number let me explain example number two we have array we have a k and we have output one how does it work firstly we have three we have one we have three again we have four then we have three okay firstly we will sort this in a ending order we have one we have three then for okay have just sorted and then we will initialize the left and right pointers our left point is here our right point is here and we will every time check if they are equals to six or less than six or more than six if left pointer plus right pointer 1 + pointer 1 + pointer 1 + 4 is 5 it's less than six so in this case we will increment the right left pointer so now our left pointer will Point here and right point will be here again we will check 3 + + + 4 it's 7 and it's more than six in this case we will decrement the right point our right pointer will be here again we will check 3+ six it equals to six so in this case we will increment our number of operations by one say plus one and we will decrement the right pointer and increment the left pointer but here it will be stopped because we will iterate until left pointer less than right pointer so our final answer is one I hope you understand let's C it up so firstly we will initialize left and right pointers left zero right it's last ele element noun minus one and we will initialize number of operations s n and lastly we should sort this in a scaning order nams sort what so we are good to go now we will Loop until left pointer is less than right Pointer while L less than right we will check if nums left plus nums right equals to K if it is we will increment our left pointer decrement right pointer and increment number of operations else if it's more than K we will decrement the K it's more than K we will decrement the right pointer else we just increment our left pointer and lastly return and number of operations yeah it's pretty efficient I hope you understand if you have any questions let me know in the comments below
Max Number of K-Sum Pairs
shortest-subarray-to-be-removed-to-make-array-sorted
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explanation:** Starting with nums = \[1,2,3,4\]: - Remove numbers 1 and 4, then nums = \[2,3\] - Remove numbers 2 and 3, then nums = \[\] There are no more pairs that sum up to 5, hence a total of 2 operations. **Example 2:** **Input:** nums = \[3,1,3,4,3\], k = 6 **Output:** 1 **Explanation:** Starting with nums = \[3,1,3,4,3\]: - Remove the first two 3's, then nums = \[1,4,3\] There are no more pairs that sum up to 6, hence a total of 1 operation. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `1 <= k <= 109`
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Medium
null
86
Hello guys welcome to the video only coding and today vrishabha problem school partition list play list the value addition notes in the loop must subscribe gold channel subscribe red color subscribe and elements from the love you to To Two And Second Elementary Upgrade From This Point Rollins And Placid Before And After All The Best Place To Place In Three And Behave With None Of The Elements In The First Of All Elements The Tarzan Element Which Is The Oldest That In Themselves Come Mine Or Edit Wed So Indian Final List Suvvar Approach And Its Avadhesh Example To The World Which Will Initially Creator List Play List Sunao Into Fuel Filter Element List Play List Ko Play List Toys And Creating A Widely Worshiped Into -Do List Play List Start Into -Do List Play List Start Into -Do List Play List Start A Pointed And Fast Done Aisa Diet Worly See The Element Wave Entry Creatinine Least 122 Is Give The Statement At Least One Element With This Particular Node 1432 To States Subscribe In The Mid-1960s Elements For Greater Noida The Mid-1960s Elements For Greater Noida The Mid-1960s Elements For Greater Noida Attach Road Distance Flying All Elements without video and unlimited statement and next to hand and to hand of hand and to two to so to label Sudhijan Logic Wisch Author is Govardhan X Ghrit Is Note Setting On The YouTube Channel Its Elements In The West Male 1252 Attach This Is This Particular Attachment Is Particular Link Like V Giridih Statement And Tools Next Is Equal To Hand When He Gives His Statement He Guys Next Will Welcome Equal To Head Current is Difficult Word File End Altos National to will shift and I will have to is equal to make hair pack abs for last element basically again in this attachment will be coming 272 Channel End User ID Album Play List End This Element Particular List Two Kids Located May Least Two And Every Two Is Not Miss This Point Was No What To Do I To File Return Only One Two Three And Four Three 500 Grams Sugar Side Reaction Half Moon To-Do Grams Sugar Side Reaction Half Moon To-Do Grams Sugar Side Reaction Half Moon To-Do List Two To-Do For Next List Two To-Do For Next List Two To-Do For Next List Menton Back To Make It Right But I Don't Like This Is The Attachment To Make At Least To All So Much Clearer 142 Spiritual And Thou Link This That Which List Note Star Least One First Year Initially Simple Give The Various Zero Right Initial Adams Green Valley Boys They Can Leave In The Morning Research Give Ilaj Tags Divya Purush Manu List Mode End Less Fuel More Copy-Paste List Mode End Less Fuel More Copy-Paste List Mode End Less Fuel More Copy-Paste Statement End Will You Make A List Of Elements Redmi Note 4 Ko Play List To-Do From List To-Do List All Play List To-Do From List To-Do List All Play List To-Do From List To-Do List All The Best All Elements Wave Torch Light With The Same Color Super 22-01-2014 Dahj Checking Elements Us 22-01-2014 Dahj Checking Elements Us 22-01-2014 Dahj Checking Elements Us Zor Wild West Ruhe Difficult To Get Started Overall Element Williams Ne Little Comment To Know What Is The Current Elements Value So Different List Play List 125 What Is The Return Of The Day That Now LY Shrank 211 Next Tight And Will Give Set Up Statement Points 258 Also Sleep This Condition Is Ruby Statement Related Reddy Statement Will Get Executive OK And Head To Head Tank Schedule Govardhan Excited Moments So After All This Happened After His Aide Decided What Will Happen To Give The Attachment To-Do List Subscribe Now To Make Final Not Behind All Will Give U Are Next Is Equal To Null Felt So Tell what they want to switch on to return this 2012 Eternal Hai taste one thing 9 and one more thing to- 2012 Eternal Hai taste one thing 9 and one more thing to- 2012 Eternal Hai taste one thing 9 and one more thing to- do list 1000 but I want to return the element world will return list play list vansh subscribe and subscribe the same list play list A Sweet Spineless Meter Sensitive Person Grow Latest Cases Which Were Accepted
Partition List
partition-list
Given the `head` of a linked list and a value `x`, partition it such that all nodes **less than** `x` come before nodes **greater than or equal** to `x`. You should **preserve** the original relative order of the nodes in each of the two partitions. **Example 1:** **Input:** head = \[1,4,3,2,5,2\], x = 3 **Output:** \[1,2,2,4,3,5\] **Example 2:** **Input:** head = \[2,1\], x = 2 **Output:** \[1,2\] **Constraints:** * The number of nodes in the list is in the range `[0, 200]`. * `-100 <= Node.val <= 100` * `-200 <= x <= 200`
null
Linked List,Two Pointers
Medium
2265
977
hi everyone welcome to coding with Jaz so today the coding problem that we'll be looking at is squares off a sorted array so for this question you are given a sorted array in a non decreasing order and your task is to square all of the elements and then return it in a non decreasing order as well so the hard part of this question is you don't know if you're given an array with negative numbers because if you're given negative numbers we can't just simply square everything and then return it we need to basically Reese or tit after squaring it the most intuitive way of doing this problem is basically screwing everything and then sort it and for that solution the runtime is gonna be Big O of n log and because we're squaring it's gonna be I mean for sorting it's gonna be big off and login so can we do better than that the answer is yes since the given array is sorted even with negative numbers we are certain that the leftmost number after squaring is going to be the largest number of all the negative numbers and the rightmost number after squaring is also going to be the largest number among all the non-negative numbers so that being said non-negative numbers so that being said non-negative numbers so that being said we could definitely use two pointers to solve this problem so basically what we need to do is to have one pointer color left pointing at the leftmost element in the array and then another pointer call it right pointing at the rightmost element and we're going to go inwards so every time when we look at these two numbers what we're gonna do is compare the square of these two numbers see if you're looking at negative four and ten we're going to compare negative four squared with ten squared which is 16 and 100 and we're going to pick the larger one and the end turn it into the answers array which is a separate rate that we store the answers and for the answers array we're going to insert each element from the rightmost so from the largest point and then we're going to move our right pointer inward by one because we've already stored that number 102 the answer is array so we don't need to look at it anymore so we move our right pointer inwards and then compare those two numbers the numbers at left pointer and the number right pointer Square loops and then compare them again and then we repeat until left pointer and right pointer meet and that's when we have compared all the numbers and have inserted into the ancestry and now let's move on to actually coding the solution out so the first thing we need to do is to make sure that the list to be given the array is valid so we need to check if not a or length a is equal to zero and we simply just return an empty list and then we need to compute our answers array and we could initialize that with a bunch of zeros i given give it the same length as the given array and then we're going to compute our left pointer and our right pointer so left is going to start from index 0 and the right is going to start from length a minus 1 and then what we need to do is to loop through or like use the two pointers to move inwards on the given the race so while left is less than or equal to right remember we don't stop until the two pointers are crossed because when they're equal to each other that's when we are looking at our last melt element and that's when we insert the last element into the array so while left is less than or equal to right we need to compute the left square so we get the element at the left pointer and multiply it by itself and we compute the right square get the element at the right pointer and then square that by itself so now we have the two numbers squared we just need to compare them and decide which one to put into the answers array so that means that we also need another pointer what sort of thing which is call it the answer location and it's going to start from the end of the answers array so it's going to be the same as right so if left squared is less than or equal to right square then we pick the larger one and then insert it into our ancestry in this case the larger one is to right squared so we put answer equals answer it and insert lock block equals I squared and then we need to move our right pointer inwards by one so the write is equal to minus equal one and then we also need to move our answer log in other words by one and then else which is when the left square is greater than goodbye square we just put it cut the right at the left square at the interlocked locations and then you move our left pointer and words by one so plus equal one and then we also move our insert a lot by one so then you just simply need to return our answers array let's run the code and voila hit submit and we're done so let's now think about the runtime and the space complexity of this coding solution like we talked about if you're just simply scoring everything and this sort it is going to be Big O of n log and run time because sorting it takes n log n but now we're not sorting it any longer so basically the whole runtime is just running through every element and then comparing them so the runtime is going to be bigger off end and for the space complexity since we're storing our answer in a separate array which has the same size of the given array the space capacity is also going to be equal of M all right that completes our video for squares of a sorted array and I hope you enjoyed it and please let me know if you found the better solution if you just want to chat just leave a comment below and I hope to see you in the next video I
Squares of a Sorted Array
distinct-subsequences-ii
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
String,Dynamic Programming
Hard
2115
1,704
Hello everyone welcome to my channel Tweet Sunny Today I am going to discuss problem determined in history and half simple like OK of solid code index numbers 1704 and problems of similar type so let's jump to the problem statement that has been given string gas Of evento 16 inches to 10 places to intervene in the split string into house tech software like subscribe from 2nd day of starting from to-do list subscribe button subscribe number 9483 to latest sake vacancy notice test content uppercase and lowercase latest very we activate untrue Ise in bell icon service return for it's ok do the question is confusing and confusing point is like you have to split string into equal half to length ok it means activities subscribe to and the last one month subscribe The Channel and tap on the internet subscribe ladybug positive idea string into equal house and the second step characters operation and the name of this letter to example to release this problem in detail ok so you can see if you can adjust 159 taste like text the book now you can C P Thakur Divided String Into Equal Portions That Is The Number Of Software Divided Into Itself All Like This Point To Characters And Subscribe To The Channel Subscribe That Bill And Indicate Over And Over 200 Suryavansh Coming To Give Winners Coming To Subscribe My Channel co subscribe like subscribe and subscribe this Video abe tu ignore tak is din find out the amount of but you can see in this problem if statement like plant take you and capital's tube school 12512 subscribe that and up to small Set OK Shift Mode Start from 976 this Video then subscribe to the Video then subscribe to subscribe Video Subscribe A Plus 6 Pro A Plus One OK Security Presentation of Snow 761 Necklace Wave Attend 512 Difficult Se Zinc Starting from the Mission More Video then subscribe to the Page if you liked The Video then subscribe to the that your voice witch contains because number on their greater than 6432 so a special greater noida 62 number 3 hours duty who is in this position with oo hello how to get basically significance battery lower convert subscribe to subscribe And subscribe The Amazing 21 Subscribe आर करे और इस घंती मैन मॉबिल नेट एप्सिडियो ok so let's do the co to find the करे और इस घंती मैन मॉबिल नेट एप्सिडियो ok so let's do the co to find the करे और इस घंती मैन मॉबिल नेट एप्सिडियो ok so let's do the co to find the best solution of this problem on ok you can see the wars when function is latest going to basically Kunwar and character is going to give And the 32nd and scheduled suppressed numbers of notes subscribe The Channel Please subscribe and subscribe the Video then subscribe to the Ajay is well of middle increment left and a similar to the that is chip withdrawal family to right subscribe my channel subscribe like subscribe And Subscribe Not working on this status at runtime is clear in Pune at 173 cents of online submission of CO2 in this hole Don't let me in the comment section Avatar Video And Subscribe Share This Video And Subscribe Our YouTube Channel Latest Updates Thank You For Watching My video mesh
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
382
hello everyone welcome or welcome back to my channel so today we are going to solve another problem but before going forward if you've not liked the video please like it subscribe to my channel so that you get notified whenever i post a new video so before any further do let's get started so the problem is linked is random node it's a very easy problem uh we'll be given a singly linked list and we need to return a random node from the linkage any random node value so each node have the same probability of being chosen so see whenever you think of this word you see random you can easily think of that okay every in every language we have a random function so we can use that yes we'll be using that so in the problem we'll be given a solution class and it has a constructor and in the constructor we have the linked list head and a function is given which is get random and this function will return uh the linked list random node value whenever it's called whenever the this function is called it will return a random linked list node value so if we see this test case uh this is the solution obj this is a solution like object will be created and this linked list head is this linked list is passed in that so basically linked list head will be passed and get random and every time get random is called a random linked list node value will be returned so like 1 is return 3 is returned then 2 is return any random value so let's see how we'll approach this problem so this is a linked list which is given to us now we discussed that we can use a random function because we have to return the random so we can we'll be returning the random function uh we'll be using the random function so we like when we use a random function either we give a range in which we need to get the random value so for example i need to get a value from 1 200 any random value i want but it should be between 1 200 so then i'll get 55 or any value i can get right so over here also if we if this is a linked list and we need to return a random value we need to get any random index if we do the indexing this is 0 1 2. obviously it's a linked list it's not an area we cannot do indexing but just for the explanation purpose we are doing indexing and if the random value we get is let's say one we get one so we will traverse the linked list and we will return the one in one index node value like that but how we will get this random value random function will give any value it could be anything like it could be a big integer also right nine eight seven six something like that so but this random value should be between the length of the linked list right it could not be any other value because it then it if it's like 55 yeah we do not have 55 nodes in the linked list so we will not be able to return the node which is at index 55 right so what we need to do is we need to have a random value which is between the length of this linked list that is 0 to the length minus 1 so this should be the random values uh range so what we will do we will use the random function and whatever random value we get we will do modulus with the length of the linked list so then we will get the we'll get the index which is between this length linked list length right so this is we will be doing this and we know how to calculate length of the linkage we will traverse the linked list till the end and we'll just simply do length plus we'll take a variable length and initialize it with zero and we will be traversing the linked list and we'll be incrementing the length every time we go to a node so this is the way we will be getting the random index and we'll be returning the node which is at that random index we'll be returning the node value not the node itself just take care of that we'll be returning the node value so this is the approach i hope you understood it this is like a basic uh overview of approach let's see the code now you better understand so this is the code um this is a solution class see over here in the question they have given us the solution class and it has the solution constructor which takes the head of the linked list this is linked list node which is uh like over here and then we have taken a variable length which will store the length of the linked list and this is a head we have taken a pointer variable which will be storing the head of the link list so this is the constructor in the constructor only since linked list is being passed this link list is being passed will be we will calculate its length so we have calculated the length and we have stored it in this variable so then whenever the get random function is called see get random is being called whenever get random is called we'll be calculating the rand index which is the random function modulus length right and then what we will do we will traverse the linked list until we get to that index and when we get to that index we will return that index value so i hope you understood the code the time complexity for the code uh since we are doing we are calculating the length so let's take it as o of n and for the time space complexity we it will be of one because we're not taking any extra space so i hope you understood the problem and the approach if you have any doubts or any if you have any doubts let me know in the comments and if you like the video please like it share with your friends subscribe to my channel and i'll see in the next video thank you
Linked List Random Node
linked-list-random-node
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen. Implement the `Solution` class: * `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`. * `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen. **Example 1:** **Input** \[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 3, 2, 2, 3\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.getRandom(); // return 1 solution.getRandom(); // return 3 solution.getRandom(); // return 2 solution.getRandom(); // return 2 solution.getRandom(); // return 3 // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning. **Constraints:** * The number of nodes in the linked list will be in the range `[1, 104]`. * `-104 <= Node.val <= 104` * At most `104` calls will be made to `getRandom`. **Follow up:** * What if the linked list is extremely large and its length is unknown to you? * Could you solve this efficiently without using extra space?
null
Linked List,Math,Reservoir Sampling,Randomized
Medium
398
1,669
hey what's going on guys it's ilya bailey here i recording stuff on youtube chat description for all my information i do all liquid problems make sure you subscribe to this channel give me a big thumbs up to support it and this is called merge in between length lists you are given two length lists uh list one and list two of sizes n and m respectively remove list uh list one's notes from the eighth note to the blitz node and put list 2 in their place the blue edges and nodes in the following figure indicates the result okay let's look at this example this figure here we got list one and list two as you can see a and b are the notes we are going to remove right uh build the result list and return its head okay so as you can see we break the connection between those two nodes a minus one and a and b plus one and we make the connection between these two nodes okay a minus one and zero which is the head of list two and uh m minus one which is the tail okay which is the end uh of place two and b plus one which is uh the note located uh right after the note at the position of b yeah well let's look at this example real quick here we got list one list two uh s here right three and four uh five three and four are the notes we're going to remove uh we remove the notes three and four and put the entire list two in their place uh the blue edges and notes in the above figure indicates the result okay so what we are going to do is uh we are going to have two nodes uh for the list one okay uh the start node and the end node we will be moving uh the end node to the node which is at the position of b here for example 4 right in this example um yeah and we will move start the start node to the position of the node which is located right before the node at the position of a okay 3 which is here next we will need to break the connection between uh the node which is located right before a here too uh with this node right this connection we break this connection uh we built the new one okay the connection between two and you know this value which is the hat of list two and um we will be moving list two which is the head of list two to the end of the list and create the new connection with the node uh which is located right after uh the node and the position of b which is five okay here with this node make the connection and we also have to break uh the connection with you know the connection we break the connection we say and dot next is equal to no uh in order to make sure that all those connections are you know are broken yeah and finally return the head of the list one that's the whole idea we need to follow to solve this problem yeah go for it so as i said before we say we create two nodes we have uh the start node which is equal to no right of the bar we have um and which is equal to at least one the head of list one uh in here we traverse uh list one we say int i is equal to zero i is less than uh b because we go to b no more uh there is no need for us to do such a thing okay and at each iteration we increment i by one and we move the end node to the next position which is ends door next um at each iteration we check whether i is equal to a minus 1 which is the node right before the node which is located at the position of a okay which is here a minus one if it's so then we uh say that start is equal to this position okay to this node uh which is so at this point of time and is here so we say start is equal to end we just move start to this point um at this point of time right after the for loop uh we need to make a connection with this node uh you know between those two nodes a minus one and 0 which is 0 represents the head of list 2. so we say start door next is equal to list two next we will be moving list two which is the heart of the list right at the bottom to the end of the list uh to do such a thing we uh will create a while loop okay and uh the condition is while um list to the next is not equal to no we move this list to node to the next position list2 next um yeah so at this point of time right after uh the while loop uh we know that list two is here at the position of detail at the end of this list too uh so here we need to make a connection with the node which is located at the position uh which is located right and at the position of uh the node right after uh right after the node which is located at the position of b okay which is b plus one we make the connection between those two nodes a minus one and b plus one um so we say list to the next is equal to as you remember and is still at the position of the node which is located uh at b okay so in order for us to get to this node we say list we say end door next we move this node to the next point to the next position and here we make sure that uh we have broken all the connections when it comes to end and dot next is equal to no as it is supposed to be right and uh points to know and the next points to know here we got no and return the head of the list one which is uh list one yeah that's it let's run this code um well i think that's pretty obvious what we are doing here i'm not sure if you guys need uh an explanation uh you know anyways let's look at this example so here we got list1 ab and list2 so here as you know indices in java start from zero we got zero one two three four and five uh here we got zero one and two this is list two um so here we start is equal to no um okay so ant is equal to uh zero okay is equal to zero um and we are going to traverse list one um so i is equal to zero we are here okay we are here let's say you know those are notes so let's remove that the brackets um yeah so we are here right um i is not equal to um 2 so we skip this condition uh we increment i by 1 which is 1 here and we move end to the next position okay and is located here by the way initially and is here right so we move into the next position which is here um here we check again whether i is equal to 2 is not equal to i therefore we skip this condition we increment i by 1 i is 2 and is you know is here um again we check whether i is equal to 2 yes uh it is equal to 2 so we say start is equal to end we put you know before that start is located somewhere here for example start is located here so now here we uh say that start is equal to end which is here right start is equal to two this point um yeah so we increment i by one and move and to the next position which is here which is three uh you know we go on skipping this condition okay and incrementing i by one so at the position of four right we got you know this we got this condition right we got uh i which is less than b that means that uh at this point of time we cannot enter this for loop uh we already incremented i mean moved we already moved and to this point so end is at the position of four start at the position of two right and uh we out of that loop at this point of time we know that we know the positions and uh all we need is we make the connection between those two notes we are break the connection between two and three uh so we say start dot next is equal to list two which is here which is this connection this arrow and we are going to move these two to the end of the list here so list2 is here rate list two by the way list one is here initially right at the position of zero at least okay list one at the position of zero here list two at the position of zero two um so at this point we say we check whether uh the next node which is you know which is this one uh is null or not it is not so we move list two to the next node which is here and uh we go and check it again the next node is not no we move list two so at this point of time we can see that the note which is right after this one is equal to no okay here we got no um yeah and here we got null as well okay um so here we say listsu.next is equal here we say listsu.next is equal here we say listsu.next is equal to and end.next which means that we to and end.next which means that we to and end.next which means that we create uh this connection between those two nodes five and this value um and we break other connections you know when it comes to uh and dot next okay so here is our and n dot next okay is here and dot next points to no so finally we return the head of um of list one yeah which is list one that's the whole problem thank you guys for watching uh the time complexity for this problem is um linear big of n where n is uh the total of the sizes okay of the list one and of the list two uh and the space complexity is constant yeah we use least node start the first node and the second one which is the endnote yeah thank you guys for watching leave your comments below i want to know what you think uh follow me on social medias uh follow me on instagram i'm on snapchat and i wish you all the best bye
Merge In Between Linked Lists
minimum-cost-to-cut-a-stick
You are given two linked lists: `list1` and `list2` of sizes `n` and `m` respectively. Remove `list1`'s nodes from the `ath` node to the `bth` node, and put `list2` in their place. The blue edges and nodes in the following figure indicate the result: _Build the result list and return its head._ **Example 1:** **Input:** list1 = \[0,1,2,3,4,5\], a = 3, b = 4, list2 = \[1000000,1000001,1000002\] **Output:** \[0,1,2,1000000,1000001,1000002,5\] **Explanation:** We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result. **Example 2:** **Input:** list1 = \[0,1,2,3,4,5,6\], a = 2, b = 5, list2 = \[1000000,1000001,1000002,1000003,1000004\] **Output:** \[0,1,1000000,1000001,1000002,1000003,1000004,6\] **Explanation:** The blue edges and nodes in the above figure indicate the result. **Constraints:** * `3 <= list1.length <= 104` * `1 <= a <= b < list1.length - 1` * `1 <= list2.length <= 104`
Build a dp array where dp[i][j] is the minimum cost to achieve all the cuts between i and j. When you try to get the minimum cost between i and j, try all possible cuts k between them, dp[i][j] = min(dp[i][k] + dp[k][j]) + (j - i) for all possible cuts k between them.
Array,Dynamic Programming
Hard
2251
82
welcome to january's leeco challenge today's problem is remove duplicates from sorted list 2. given the head of a sorted linked list delete all nodes that have duplicate numbers leaving only distinct numbers from the original list so we can have a linked list here and we're going to remove all the duplicates we're not just going to make them unique we're just going to remove them completely now this is going to be a sorted um a link to list so it's going to be a little bit tricky to do this but let's think about how we might do it well the very first approach we might think is to just regenerate this list completely what we can do is traverse through our linked list and count up the number of numbers each node the ones with duplicates which means a count greater than one we're going to skip those and just create a new linked list with only the unique numbers and make that in order so that it's sorted so we can do that let's start with that approach um it doesn't look like we have to do it in place in any way so let's start with creating a temporary list and what we'll do is um we are going to append to this list all of the node values so while there's a curve we will append to our temporary array the cur.value and then just move ahead our cur.value and then just move ahead our cur.value and then just move ahead our curve to equal curve to equal curve to equal so now we have all of our uh values in the list and what we're going to do is create a counter object called a c say counter and put in temp so now we're going to regenerate our temporary array to say uh for all the key values in c dot items if the value is equal to one then we'll add it to our temporary list again so now we have only the unique values now we just need to create our um our linked list right so what we can do is say create a dummy make this occur and make this equal to just an empty node here and this is so that we could uh pass in the dummy dot next as the head and we will for all the values in temp um say curve dot next is equal to list node i and then say cur equals cur.next like that and finally we just cur.next like that and finally we just cur.next like that and finally we just turn the dummy uh or specifically what the next one our dummies point to so that's gonna be the new head so let's see if this works this is the most naive approach and looks like that works let's see if it gets accepted and it does so this is totally acceptable but the issue with this is we're going to be using extra memory right a lot of extra memory here to create our temporary list so how can we do this in place and we should know this because um with linked list this is sorted and there's definitely some sort of two-pointer two-pointer two-pointer solution here so let's think about how we might go about doing this in place say that we had a sort of list that looked something like that how about and also something that looks like let's say two three four so what we will need to do um in order to restructure our linked list is to have some sort of dummy node right so we'll call this d and this d here is going to be pointing ahead on both of these nodes so what we'll do is we'll have two pointers one pointing to the previous node and one that's going to be checking to see if there's duplicates so here we'll start with the dummy and we'll have one uh pointer at one and we'll check to see the next one hey does that equal uh the value itself and if it does then we know that we need to skip this right we'll still have a pointer pointing at d we'll move our pointer head to two and then we'll have this previous pointer point now to the new one too now that works fine but one thing to keep note is like what if we had this example here and we had a pointer at d we move ahead and now we see 3 so we skip that ahead now 2 is going to point to 4 but unfortunately 4 is also duplicates right so we need to keep our slow pointer here at 2 to make sure that the next one's also not a duplicate and we'll just continue our algorithm that way to make sure that um this two is pointing to one that is not duplicate and that could actually be here it's going to be going to the middle here right so at the end it's going to be 1 2 and that's it one two first point to four and then we'll check four to point to nil and then it'll be just one two nil okay so let's see how we might do this first thing is to create the dummy node uh we'll have it called this node and what we'll do is just say make it zero and the next is going to be equal to head yeah okay so now we have our dummy node and what we'll do is have some sort of slow pointer right so the slow pointer is going to be equal to first the dummy and the head's going to be equal to head so now this head is going to be that faster pointer that moves ahead and we'll say while head let's check to see if head dot value is equal to head dot next dot value then we want to do a while loop to move this pointer because it could be more than just one it could be multiple um numbers we want to move this you know head pointer all the way up to the one that's not um not the same right so what we'll do is have some sort of while loop and also need to make sure that there is a head dot next before we can do that so while like that and while um same thing head down next and head dot value equals head dot next value we will move our head to equal head.next otherwise we will just move ahead our slow one people slow down next and also make sure that we move ahead our fast or not fast point on our head trickle um that's all right hit the next one yeah i think so uh move our head to equal head.next as well equal head.next as well equal head.next as well okay so that might be it just return the dummy.next now see if this works oh okay so that didn't work why is that um oh that's right i need to make this slow dot next equal to the head dot next right see if that works yeah i have to restructure it there yeah that's it so just gotta make sure that the slow pointer next pointer is now gonna be pointing to the heads next because right now when's uh wherever it's at it's gonna be at the one where um it's right before the non-unique one um it's right before the non-unique one um it's right before the non-unique one so submit this and there we go accepted so this is all in place it would be of n time complexity and it's probably optimal so that's it all right thanks for watching my channel and remember do not trust me i know nothing
Remove Duplicates from Sorted List II
remove-duplicates-from-sorted-list-ii
Given the `head` of a sorted linked list, _delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,2,3,3,4,4,5\] **Output:** \[1,2,5\] **Example 2:** **Input:** head = \[1,1,1,2,3\] **Output:** \[2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List,Two Pointers
Medium
83,1982
98
so i'm going to teach you the easiest way to solve the validate a binary substring problem so that method is called the limits methods okay so what does the limit method say the limit method states that for each node check if the value of the node falls within certain limits and if not written false so it means for instance for the root node we have we should have a limit and the base limit is going to minus infinity to plus infinity and we're going to check if the root node is falling between these two and if so no problem but if it falls outside this um uh limit then we're gonna return false so let's say we have this on the root if we move this way now the values on the right or on the left here have to be less than the value of nine it means that the upper limit going now to the left the upper limit would adjust to the value of the current node so in this case let's say we have this to be low and we have this to be high so once we move here the low becomes remains the same so it's going to be minus infinity but now the high is going to change to the value of this place which is nine okay so when we are here now we're going to check if seven falls between these two you can see that seven falls uh between minus infinity and mine right so seven is less than nine and is greater than minus infinity so this is fine but when we now move this way we are going to now adjust our low uh yeah we are going to adjust our height to seven and the low remains minus infinity and the high now is going to adjust to seven because whatever i see say should be not greater than seven okay how about moving from here to here in this case our law will now have to adjust because whatever is in this place should be like to be should be greater than what is here so this should be the lower limit at this point so our low should be seven and our high should be nine which is here right sorry which is nine so i have to check if six is between seven and nine and it's not it means now that this tree is not valid so this is the limit of how it works let's see how it plays out in code and we are going to appreciate exactly uh what is happening here so first i'm going to kind of increase my phones a little bit so the first thing we want to do here is to write a helper function that takes in nodes and takes two limits and simply checks if that node value falls between the two limits so i'm going to call this function valid i'm going to say d a valid and specify a node and specify low and high and then we are going to check first if the node is known so if not node we are going to simply return true the reason we are going to return to true wings an empty node is because an mt3 on empty node is a valid node as well so i'm going to check if the node value falls below the lower limit so if note the value is less than or equal to because the binary search tree or quality is not allowed this has to be strictly less or high less or greater so if that value falls below the lower limit or is even equal to the lower limit you're going to return false okay so actually this is true and this will be false okay again we are going to check if the node value falls above the offal image so i'm going to save nodes dot file is greater than equal to high at this time we also return false okay now we have the we have checked these two now we're going to call this same valid for the left and right uh children of this node so i'm going to say valid recursively now because we are going to call it recursively so i'm going to specify node.left specify node.left specify node.left i remember when we are going to the left now the lower limit remains the same and the upper limit is now going to change to node.val we are going to do the same thing for the right subtree i'm going to say node.right and the lower limit is now node.right and the lower limit is now node.right and the lower limit is now going to change the node.file and the going to change the node.file and the going to change the node.file and the upper limit is going to remain the same and this is going to be and because we are going to make sure that both of them are true for also return to so i'm going to return yeah so let's show how this okay so let me take all this why do we have this error okay so we are going to recursively return valid return for the uh not that left okay we're gonna call it for the left and call it for the right as well okay um so why do we have this error here okay so i'm gonna say if one second let me just correct this okay so i have to put it uh here okay so i'm calling this function recursively and i'm going to uh actually return here so when both of them are valid we are going to return true and we are now going to call this function a valid function on the root so i'm going to say return valid now i'm calling it on the root so i'm going to call it on the root and i'm going to give it the base case which is minus infinity and plus infinity so minus infinity is going to be floats uh floats minus inf um plus infinity is going to be floats uh inf okay so this is fine great um so yeah so this is a same line okay so this is this should be fine so let's run it and let's see what we have so i'm going to run this code now and let's see um it says node is not defined let's see okay so this actually should be in here okay so sometimes i don't know so yeah so let's run it and see float is not defined sorry about this is gonna be floats okay yeah so i think it should work now uh let's see so it's accepted and let's go ahead to submit this code and let's see what we have so i'm submitting now and speeding up okay so let's just check here and it says soft size it works so you can see that my code runs faster than mine is 7.87 on final python 3 online mine is 7.87 on final python 3 online mine is 7.87 on final python 3 online submissions so i'd like to thank you for viewing please remember to subscribe to my channel i remain kinds on the tech pro and i'm always there for you
Validate Binary Search Tree
validate-binary-search-tree
Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: * The left subtree of a node contains only nodes with keys **less than** the node's key. * The right subtree of a node contains only nodes with keys **greater than** the node's key. * Both the left and right subtrees must also be binary search trees. **Example 1:** **Input:** root = \[2,1,3\] **Output:** true **Example 2:** **Input:** root = \[5,1,4,null,null,3,6\] **Output:** false **Explanation:** The root node's value is 5 but its right child's value is 4. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,501
105
hello friends we are still not employed by a fan company so let's not stop lead coding till we get there today we are going to construct a binary tree from pre-order and in order traversal lead pre-order and in order traversal lead pre-order and in order traversal lead code problem and if we see some of the companies where i want to get a job who have already asked this question there are companies like microsoft amazon bloomberg apple uber by dance google facebook and linkedin so that's why i'm paying my utmost attention i hope you also enjoy the video now this is a very hated lead code problem and let me show you why this is from the solution tab of the lead code problem where people have expressed their views very abruptly some people are saying why god why some people are saying that it's time to leave for himalayas some people are saying that if you get this question they do not want to hire you and things like that there are many other comments the thing is we do not want to focus on the negativity let's try to see that what is the approach to solve this problem and then we are going to see that how can we be able to solve this problem if we encounter this in any interview because our aim is to get into fang not just dream about it now this is a lead code medium problem but in my opinion this should have been a lead code heart problem now let's try to understand the problem basically we are given two integer arrays called pre-order and in order and basically pre-order and in order and basically pre-order and in order and basically they are the pre-order traversal of they are the pre-order traversal of they are the pre-order traversal of binary tree and in order traversal of the binary tree now based on these two arrays that we are given we need to construct and return the original binary tree so let's try to understand this with an example so over here we are given as an input we are given two different arrays pre order error and in order array now somehow if we iterate over this preorder in order array there is only one combination of binary tree we can make and which is this one so that is the example that is given over here now let's see that what is going to be the different approach to solve this problem but before we do that the important thing in this problem is to understand that what is a pre-order understand that what is a pre-order understand that what is a pre-order traversal what is the in-order traversal what is the in-order traversal what is the in-order traversal and how can we use that property store advantage so first of all i'm going to show you preorder and in order traversal how it works so first of all we are going to learn about pre-order traversal and basically about pre-order traversal and basically about pre-order traversal and basically pre-order is a dfs kind of traversal pre-order is a dfs kind of traversal pre-order is a dfs kind of traversal which is depth for search if you want to know more about different kinds of traversal you can check out my video over here now let's focus on the pre-order traversal for now so basically pre-order traversal for now so basically pre-order traversal for now so basically pre-order traversal first of all we pre-order traversal first of all we pre-order traversal first of all we visit the root note then we visit its left subtree and then we visit its right subtree and we keep on doing that until the nodes exist so let's see that for this given example what is going to be the path that we are going to follow so first of all we are going to visit the root node so in this case the first node we are visiting is going to be node number 5 then we are going to visit its left child so left child in this case is three so again we are going to visit node number three and then again we are going to visit its left child because remember its root left subtree and right subtree so left subtree still exists over here so we are going to visit node number one now left subtree does not nothing more exist in the left subtree so now we will start visiting the right subtree so we now will visit the node number seven now after visiting the node number seven now there is nothing exist over here so again we are going to go back to the root because we still have to visit its right subtree so we when we start visiting the right subtree again we are going to follow the formula for root left and right so root node in this case is going to be eight so now we are going to visit node number eight after that we are going to visit node number six and then we are going to visit node number nine which is the right subtree and this is going to be the traversal path that we are going to take now let's see that what would be the inorder traversal in the same manner so again as mentioned the inorder is also a dfs kind of traversal but in this case the methodology we follow is that first of all we visit the left node then we visit the root node and then we visit the right node so for this given example what we are going to do is first of all we are going to go to the left node all the way possible so left node in this case is one so first node we are going to visit is going to be node number one now for uh now we can't go left anywhere so now we are going to visit its root node so root node is in this case is going to be three and then we are going to visit its right node so right node in this case is going to be 7 after doing that after visiting all three nodes now we don't have any more nodes to travel on the left subtree so now we are going to visit the root node as mentioned over here because we have already taken care of this left part so now we are going to visit node number five now again we still have values that we need to visit on the right subtree so again we are going to take on the same initiative so now the first thing we are going to visit is going to be the left most element for this right subtree so left most element in this case is 6 so we are going to visit the node number 6 over here after that we are going to visit the root node which is 8 and then in the end we are going to visit the node 9 over here which is this one so this is how in order traversal works so after understanding both the values and both the different traversal mechanism let's see that what would be the optimal solution and how we are going to approach that okay suppose this is the binary tree that we are given that we need to iterate over and uh we are given the pre-order and in order traversal for pre-order and in order traversal for pre-order and in order traversal for both of them so in that this case the pre-order traversal for this tree is pre-order traversal for this tree is pre-order traversal for this tree is going to be and the inorder traversal in this case is going to be now once we have both the values let's see that what is the approach we are going to take so if you closely observe both of these values for pre-order and inorder values for pre-order and inorder values for pre-order and inorder traversal they both have something to offer the thing they have to offer is that this pre-order allows us to that this pre-order allows us to that this pre-order allows us to determine that what the root of any section of the tree is and this in order allows us to determine that what is the left subtree and what is the right subtree of any given tree how let me quickly show it to you so if we see this pre-order traversal the first value in pre-order traversal the first value in pre-order traversal the first value in this case is actually the root of the binary tree which is 5 over here which you can clearly see that the 5 is the root of the binary tree so well that is interesting information the thing is this alone is not helpful if we see with this inorder traversal for this five if we see the left side of this five there is only one entry over here which is three and if we see in this tree actually this three is the left subtree of this entire tree where the root is 5 now if we see on the right side the values are 6 8 and 9 which is these three items and this is actually the right subtree of this original given tree where the root value is 5 so now we actually have something meaningful that we can use if we keep on repeating the same process now for this pre-order same process now for this pre-order same process now for this pre-order traversal again we see okay so the next value is three so three is already the left subtree now if we again break it from this in order traversal for this in order traversal we only have three value over here we have nothing on the side we have nothing on the right side because the right side value is actually 5 which we have already identified that is the root of this original value 3 which means we can determine over here that for this 3 it does not have any values on the left subscribe and right subset because the very next value of this three is actually five which was already the root of this value uh three so now again we have some meaningful information so far let's backtrack the information we have found so far that let me create an answer value over here where we have already found that okay the first value is 5 ah the left most value or the first left value or left sub child of this value number 5 is actually 3 and for this 3 it does not have any more children so now we can add the values null over here okay now we are done iterating up until this point but we still have some more nodes that we need to iterate over so based on this pre-order traversal now based on this pre-order traversal now based on this pre-order traversal now the next node we have is 8 so now we know that the current root we are iterating over is actually 8 okay so we have this value 8 now from this in order traversal we actually have these three values where this 8 is actually in the middle because remember this in traversal allows us to determine that what is the left subtree and right subtree of any given root so in this case if the root is 8 then the left subtree is going to be the value 6 and the right subtree is going to be the value number 9 so we are going to use it to our advantage now for this value number 6 again we are going to try to see that what is on the left of 6 and right of 6 but in this case since we don't have any more information for this value number 6 the left value is 5 which was the original root which we have already iterated over and this next value is 8 which was the origin the root of immediate root of this value number 6 whichever we have already traded over so now we can determine that for the 6 we don't have any other value so which means that we have two null values so again now let's and same thing we can determine for this nine as well that for this nine the left most value is actually eight in the right there is nothing over here which means this nine also does not have any more children so now let's again backtrack based on the information we have found so far so now on the right side the value we got was eight that was the route we iterated over and we found that information based on the pre-order information based on the pre-order information based on the pre-order traversal after finding this eight now we started iterating over the left and right children of this eight so left children was six so we iterated the value six now the six did not had any more children so we had the values null over here and now then we had the value number nine and nine also did not have any more children so now again we had the two more null values over here and this is the actual binary tree that we were able to create based on this original given pre-order traversal and inorder pre-order traversal and inorder pre-order traversal and inorder traversal and that is the solution that your interviewer is expecting and that is what is needed for this problem as well now there are actually two ways to do this problem the there is an iterative way and there is a recursive way if you know me i love the recursive solution so i am going to opt for the recursive solution basically what we are going to do is initially we are going to find the root value and then we are going to find the left subtree and right subtree now again we are going to pick one value so we are going to pick the left sub tree so now even for the left subtree we will have a root value in its left child and right child and again we are going to keep on repeating the same process and we will be continuing to building our answer and same thing we are going to repeat for our right subtree as well so basically we are taking a bigger problem and then dividing it into a bunch of different smaller problems i know this looks really messy but you get the idea of what i'm trying to convey over here and let's see the time and space complexity in this problem so time complexity is actually going to be big o of n where n is the number of nodes that are present inside any given tree because we will have to iterate over both in order and pre-order traversal and originally it's pre-order traversal and originally it's pre-order traversal and originally it's going to be two n traversal the thing is generically we can write it to big o of n if we see space complexity well space complexity is also going to be big o of n uh because uh recursively we might have to iterate over all the nodes and it worst case scenario it could take big of n space this is a wonderful time in space complexity given that how complex this problem was and based on the pre-order and in order traversal we were pre-order and in order traversal we were pre-order and in order traversal we were actually able to build the solution for the binary tree now let's see the coding so before we start coding we will actually have to define that how we are going to use this pre-order in order going to use this pre-order in order going to use this pre-order in order array well we are going to use this pre-order array to determine that what pre-order array to determine that what pre-order array to determine that what is the root value for any subsequent positions and once we have the root value we are actually going to use this in order array to determine that what is the left subtree and right subtree for any given root and once we have both the information we are actually able to build our tree now the thing is if you clearly understand that for this inorder array we will have to look up at information much in much broader fashion than compared to this pre-order array than compared to this pre-order array than compared to this pre-order array so what we can do is in order to iterate over this in order array or rather than iterating it just by considering this to be an array we are actually going to create a hash map where we are going which is going to allow us to iterate over this in order array pretty fast and uh so let me define two global variables over here first of all once you have these two information now from our main method first of all we will have to iterate over this inorder array and then we will have to populate this in order index map that we just created so let me quickly run a for loop now we have our hash map ready to go now we will have to create a separate method where we are going to call the recursion so first of all let me create a new public method so now i have created a new method called array2tree that returns a tree node and as an input i am taking the pre-order array on the left ocean and pre-order array on the left ocean and pre-order array on the left ocean and right portion uh and now we are going to create this recursive method now before i do that i will also have to initialize the values for this pre-order index and the values for this pre-order index and the values for this pre-order index and also for this in order index map so that i'm going to do it now back to our uh recursive method so for recursion first of all we will have to create a terminating case and the terminating case in this case is going to be that if the value of left is greater than the value of right if that is the case we break out immediately and we will return null if that is not the case first of all we will have to define our root value and root value we are going to define from our pre-order array going to define from our pre-order array going to define from our pre-order array so our root value is actually going to be the whatever this pre-order index value the whatever this pre-order index value the whatever this pre-order index value that we have uh and then we are also going to uh increment the value of this pre-order index as well so pre-order index as well so pre-order index as well so this is the root value and after that we are going to increment the value of preorder index now since we have our root value we are actually going to create a new tree node called root and for this root node we are going to assign the value that we received over here originally the value of this pre-order index is 0 which means that pre-order index is 0 which means that pre-order index is 0 which means that the first value we are getting from this pre-order is the main root of the tree pre-order is the main root of the tree pre-order is the main root of the tree once we get that value we will have to create the left sub tree and right subtree so we will have to call this array to tree method again and we are going to populate the value for left and right child so for the left child we are again going to call this array to tree method uh inside the input first of all we will we are going to provide this pre-order array as we found as it is now pre-order array as we found as it is now pre-order array as we found as it is now for the left subtree we are going to keep the value or same for the left value but for the right portion the value is actually going to be different and that is going to be different based on whatever this root value we had so in this case for the first value for this pre-order array the root value is pre-order array the root value is pre-order array the root value is actually three so now for the left uh part we already have the value but for the right part we are going to have to provide all the values that are present after this root node so we are going to do that so for that now our in order index map is very helpful now we have both the information ready to us now we are going to call the right subtree in the same manner but in this portion we are going to treat whatever the right variable we had already uh but now we are going to change the left variable so left for the left variable we are actually going to use whatever the value we had for the root value and we are going to do it plus 1 and as the right limit we are going to keep whatever the right limit we originally had and after this recursion ends and after this function ends we simply need to return the root variable okay so now our recursive method is ready to go now all we will have to do is from our main method we will have to call this uh recursive method that we just created that should be it so we are calling this pre-order method but we are calling this pre-order method but we are calling this pre-order method but we are providing the pre-order array and as the providing the pre-order array and as the providing the pre-order array and as the left uh position we are providing the value zero as the right most position we are providing the value of whatever the pre-order length is -1 and pre-order length is -1 and pre-order length is -1 and that should do the trick now let's try to run this code it seems like our solution is working as expected let's submit this code and our code is pretty efficient compared to lot of other solutions i will be posting this in the comments so you can check it out from there thank you
Construct Binary Tree from Preorder and Inorder Traversal
construct-binary-tree-from-preorder-and-inorder-traversal
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_. **Example 1:** **Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\] **Output:** \[3,9,20,null,null,15,7\] **Example 2:** **Input:** preorder = \[-1\], inorder = \[-1\] **Output:** \[-1\] **Constraints:** * `1 <= preorder.length <= 3000` * `inorder.length == preorder.length` * `-3000 <= preorder[i], inorder[i] <= 3000` * `preorder` and `inorder` consist of **unique** values. * Each value of `inorder` also appears in `preorder`. * `preorder` is **guaranteed** to be the preorder traversal of the tree. * `inorder` is **guaranteed** to be the inorder traversal of the tree.
null
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
Medium
106
1,845
hey everybody this is Larry this is day six of the Leo da challenge of November and actually day six this time hopefully I'm getting it right uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's farm and today we are still in uh at least of this recording uh still in kagoshima here in uh Japan and yeah let me know what you think I'm just walking at uh having probably a couple more drinks than I should have but by the time you watch the video I probably should have been okay so yeah uh yeah anyway to the F hey oh yeah right I always forget that I have an intro now but hope you enjoyed the intro uh I'm still in kagoshima I'm actually about to get on a bullet point maybe a bullet point but also a bullet train in about an hour so I really hope that this video is fast uh this is day six of the Leo da challenge hopefully I got the right date this time and today's problem is 1845 seat reservation manager all that seems reasonable maybe uh and actually that's funny CU I had to pay for a seat restoration on the bullet train anyway okay so you have a restoration state of n seeds one to end initialize reserve the smallest numbered unreserved seed reserves it and void unreserve unreserved okay so basically you have to get a um repeated Min kind of thing right and then you know and then putting it back uh this is a very standard binary search tree type thing uh yeah I mean that's pretty much it really and you can do it in any number of reasonable binary search tree things where you can add and remove right uh and yeah and in Python the way that I would do it is with Su course sorted list it's not actually what I just said but um but it does have the API of something like that uh so yeah so um and then maybe I say something like for I in range of n is it 1 to n so let's say 1 to n + let's say 1 to n + let's say 1 to n + 1 we also should save s isal to n so that I guess we don't run out seats or maybe we R have SE oh yeah okay well we at least have one un resered seeds then we should be okay but maybe we should I mean in theory we probably should check it anyway but it's also fine we don't for now and then yeah uh this we just um X is z.l. Z this assumes that we always X is z.l. Z this assumes that we always X is z.l. Z this assumes that we always have a seat but we can check for it if they want us to but and then unreserve is. seat number so I didn't really go over this form that much but SL is basically just um there seats that are available so then here we get the Min seat that is available here I guess and then here and then remove them obviously from avilable seats and then this is yeah and so is terrible name so maybe available it's only slightly better but you know I think I was just terrible all right let's give a spin uh oh yeah okay let's give it a spin uh looks good for this one let's give it a submit and there we go apparently I've done it before I mean I probably should have I didn't even look it up to see where I done it before but seems pretty reasonable I probably did the same way yeah I even uh I even got that time I didn't get wow this is exactly the same code I wot it only took an effort to write this extem more and I just converted available to this that was three years ago H time fries and yet some things don't change anyway uh that's all I have for this one I got a train to catch um it's going to be uh initialization is going to be n log in uh this is going to be all L again and this is going to be all L again which is you know uh going to be good for most reasonable cases so yeah um that's all I have for this one let me know what you think and you can watch me outro now thanks for watching hit the like button hit the Subscribe button join me on Discord and today's uh ice cream is whatever this is uh yeah uh I'm not going to get it in front of you this time but I mean cuz it looks like a very standard ice cream Kong uh yeah so but I am still excited to have ice cream so stay good stay healthy take a mental health I'll see yall later and take care bye-bye
Seat Reservation Manager
largest-submatrix-with-rearrangements
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`. Implement the `SeatManager` class: * `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available. * `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number. * `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`. **Example 1:** **Input** \[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\] \[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\] **Output** \[null, 1, 2, null, 2, 3, 4, 5, null\] **Explanation** SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats. seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\]. seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2. seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3. seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4. seatManager.reserve(); // The only available seat is seat 5, so return 5. seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\]. **Constraints:** * `1 <= n <= 105` * `1 <= seatNumber <= n` * For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat. * For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved. * At most `105` calls **in total** will be made to `reserve` and `unreserve`.
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
Array,Greedy,Sorting,Matrix
Medium
695
35
hello and welcome to my channel so let's look at the lead code 35 search insert position give a sorted array of distinct integers and a target value return the index if the target is found if not return the index where it would be if it were inserted in order you must write an algorithm with o log n runtime complexity so the example one is a one three five six then target is five so uh so you need to return to the index of five um so also um second example is a example that the target is not in the array but you need to insert it at the index one before three so you the returning the output there is a one oh okay so also norms contains distinct values sorted in ascending order um so the so this is a question to ask the binary ask using the binary search and the time complexity will be over log n and log range um log n time and space is one so the question actually is a there is a two possibility why is that if the target value is there then you need to return uh the index of the target if the target value is not there you return the uh index uh where the target is inserted for this question actually what you are trying to do is insert the to calculate the lower bound of the array the norms so the law about the definition is uh the first uh index that has a value larger than or equal to the given value so what if the value is uh existing in the array then this will return the first index that has that is equal to that value if the value is not uh in the array then it will return the first index that has a value larger than the given value but also that index is where you need to insert that value too so we can start writing the code so the firstly low is zero and the high we are going to use the norm star length and um so while low smaller than high then we get a uh the middle value then so if norm's smeared is larger than or equal to target then we assign mid to high else low is uh i mean the plus one so playing then we just return low this is uh how do you calculate the lower bound so let's submit okay so this concludes today's daily challenging question so if you have any comment or suggestion please comment on the video thank you for watching see you next time
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
819
hello everyone welcome to my youtube channel today we're going to look at the 890 question most common words in python um so given a paragraph and list of bandwidths return the most frequent word that is not in the list of bad words so uh let's see the example here the most frequently appeared word is actually um hit one two three times but because the hit is banned so we should output the next frequently appeared words which is ball so we can see that in the example there are some uppercase letters lower case letters there are some punctuations so if in the string everything is lowercased and there are no punctuations all words are separated by space it will become really easy because we can just convert the string to a list and then we can calculate the most frequently appeared word that is not in the banned list so um in our code our goal is to first try to convert the paragraph to a lowercase string and without all the punctuations and then we are trying in to convert the string to a list and then we will import the collections counter module and method and to calculate the most frequently appeared word that is not in the band list so let's try to do it so paragraph the lower paragraph so now we did convert the paragraph into lowercase letters and then for i am paragraph if i am a punctuation list if i is punctuation we will replace uh replace i to a space right so paragraph equals paragraph dot replace i to a space so for this for loop we are trying to convert all the punch
Most Common Word
minimum-swaps-to-make-sequences-increasing
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**. The words in `paragraph` are **case-insensitive** and the answer should be returned in **lowercase**. **Example 1:** **Input:** paragraph = "Bob hit a ball, the hit BALL flew far after it was hit. ", banned = \[ "hit "\] **Output:** "ball " **Explanation:** "hit " occurs 3 times, but it is a banned word. "ball " occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as "ball, "), and that "hit " isn't the answer even though it occurs more because it is banned. **Example 2:** **Input:** paragraph = "a. ", banned = \[\] **Output:** "a " **Constraints:** * `1 <= paragraph.length <= 1000` * paragraph consists of English letters, space `' '`, or one of the symbols: `"!?',;. "`. * `0 <= banned.length <= 100` * `1 <= banned[i].length <= 10` * `banned[i]` consists of only lowercase English letters.
null
Array,Dynamic Programming
Hard
2234
1,624
hey there what's up this is steve today let's go through one little problem it's labeled as easy it's actually pretty straightforward but i thought it's meaningful to go through this problem quickly and it's legal problem 1624 largest substring between two equal characters let's take a look at the problem given the string s return the length of the longest substring between two equal characters excluding these two equal characters if there is no such a substring written -1 -1 -1 then it gives the definition of a substring which is a continuous sequence of characters within a string for example given input is a there is no such a substring that is not empty between the two a's that's why it's returning zero so the optimal substring here is an empty string because there are indeed two equal characters which is a but there is no other string other than the empty string in between these two same characters so that's why it's returning zero not a minus one in which case do we written -1 in the in which case do we written -1 in the in which case do we written -1 in the case that there is no character that appears twice for example here c b z x y in this case we return -1 because there is no such a we return -1 because there is no such a we return -1 because there is no such a case that there are two same characters now let's take a look at a normal happy case which is there is two same characters and in between these two same characters there's a non-empty string which is a b there's a non-empty string which is a b there's a non-empty string which is a b c a for example here right so there's a and in between these two a characteristic there's bc this is one substring and it's length is two so that's why we return two here if we take a look here so there is multiple different two same characters bb a and cc right the longest one is cnc between c and c that is because it has four it uh it has a substring of length of four right all right so this is very straightforward problem so let's take a look at the problem api max length between two equal characters it just passes in the input s what we can do is that we can traverse through this string one character at a time for each character that we're iterating on we try to find if this character has another mapped character in towards the end of the array if it doesn't then we don't need to check the substring in between these two because there is just none of such a thing that exists if that does exist as such a character towards the end of this string we can take the length between these two same characters and then we can maintain another variable outside of this iteration loop we keep updating this iteration loop whenever we find a bigger one we'll just update that in the end after the iteration finishes we'll just return the max length that's the idea very straightforward now let's put the idea into the actual code so i'll initialize a variable called maxlearn initialized to be in actually i can initialize to be minus one because it's possible in this case there is no two same captures in this given stream so in that case we'll just initialize to be minus one and then we'll go through this i then i plus so first let me get this character as char at i so we get this character next step we want to see last index as last index so in java for any string object has such an api called last string last index f we call this so we get this last index then we want to compare if last index not equals to this i because it's not equal to i because it's very possible that there this character exists only once in this given string in that case last index is going to be equal to i so in that case we don't need to do anything but if that's not the case what we want to do is we want to update the max length just in case that the max length between these two same characters is longer right so lane and the length here is so last index minus i minus 1 because we want to strip off the two same characteristics in both ends so we want to take one off of this distance so in this distance itself last index minus i already strips off one character in one end and then we need to strip off the other one on the other end that's why we minus one here and then in the end you can just return max lens max lane all right now let me hit run code all right this is accepted now let me hit submit all right accept it to you memory usage not super good and let's see of course they are super there's a variety of different oh it's still 20 one more time now stop spamming it oh still 20 yeah there is a variety of different ways that you can solve this problem this is just one way that i thought very straightforward hopefully it helps you guys understand this if you guys find this video helpful please do me a favor and hit that like button that's going to help me a lot tremendously and help out with the youtube algorithm and i really appreciate it also don't forget to subscribe to my channel as i have accumulated quite a lot of different nico tutorials or videos to talk about different data structures or sorting algorithms or anything that is see as fundamental so with that said hopefully i'll just see you guys in just a few short seconds in my other videos thanks very much for watching
Largest Substring Between Two Equal Characters
clone-binary-tree-with-random-pointer
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "aa " **Output:** 0 **Explanation:** The optimal substring here is an empty substring between the two `'a's`. **Example 2:** **Input:** s = "abca " **Output:** 2 **Explanation:** The optimal substring here is "bc ". **Example 3:** **Input:** s = "cbzxy " **Output:** -1 **Explanation:** There are no characters that appear twice in s. **Constraints:** * `1 <= s.length <= 300` * `s` contains only lowercase English letters.
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
133,138,1634
368
hello guys welcome back to my YouTube channel today we are going to solve Day N problem on lead code if you guys haven't subscribed my YouTube channel yet then please go ahead and subscribe it now without any delay let's get started with today's problem okay so guys uh this is a problem of largest divisible subset so in this problem we are going to use uh our DP okay this is of medium level but uh I will make sure that by the end of this video you guys will find this problem very easy okay so now uh let's read the problem statement first okay so in this problem we have given a set of distinct positive integers nums and we have to return the largest subset answer such that every pair of elements in this subset satisfied this condition okay so answer of I mode answer of J is equal to Z or other way around if answer of J mode answer of I is equal toal Z then it is also good okay so if there are multiple Solutions then we have to return any of them okay so this is the example one in this uh input nums is given to us has 1 2 3 so here you see uh two mode of 1 is zero right and three mode of 1 is also zero but three and two okay so three mode of two is not equal to zero so we can't return 1 2 3 okay we can return either 1 two or we can return 13 okay so in order to solve this problem let's understand the logic first that we are going to implement in our solution okay so this logic is going to be very important so watch it carefully okay I'm going to explain it very slow and in very detailed manner okay so first of all in this we have to find the largest divisible subset okay so here before uh understanding this logic okay so I have one question to you guys let's say this is a subset okay in this subset first element let's say three okay after that I am adding the element whose mode with the three is going to be zero okay so let's say I have added six so what is six mode of three okay 6 is completely divisible by three right so the remainder is zero right so 6 mode of three is zero and after that so here one more thing in this subset I am adding the elements in increasing order okay so after that I am adding one more element X whose mode with 6 is equal to zero so let's say I add 6 24 here okay let's say 24 again so 24 mode 6 what is 24 mode of 6 so 24 mode of 6 is also equal to zero okay because 24 is completely divisible by 6 okay so 24 mode with 6 is also zero after that here I am adding one more element let's say I have added 48 okay in this subset so what is the 48 mode of 24 so this is also equal to Z only right because 48 is also completely divisible by 24 right so here in this list you can see that uh 48 is completely divisible by 24 is completely divisible by 3 and 6 is also completely divisible by 3 but now here one more thing so here can this 48 is completely divisible by three by six yes it is true 48 is also completely divisible by 6 because 48 small 6 is also zero 48 when we are going to divide 48 with 6 the remainder is zero now again check this 48 with three okay so this is also true 48 is also completely divisible by three okay and can this 24 is complet isible three yes in this case 24 mode 3 is also equal to zero okay so what did we get from here from this step we get that we have to just check the mode of these two numbers then these two numbers okay we have to check the mode of the I + 1 element to check the mode of the I + 1 element to check the mode of the I + 1 element with the this I element if their mode is equal to zero then uh it is clear that its mode with previous element is also going to be zero only okay so this is how we are going to create one longest divisible subset okay so I hope this is clear okay so now let me erase this part okay so now let's suppose this is array given to us this is one array given to us in which the elements are 1 8 7 4 and 16 okay so now to solve this problem we are going to first sort our array okay because here we have to just return the largest divisor subset and in subset elements order can be anything it can be 2 1 2 okay it can be 8 4 2 1 it can be 4 28 1 so order can with anything uh it will return uh option uh return our output as correct only okay so order is not necessary here because this is a subset not sequence okay so this is just a subset okay so in order to solve this problem we are just going to our sort our array first okay because I have already explained one example in which we have to just uh check for the mode of the I and I + 1 check for the mode of the I and I + 1 check for the mode of the I and I + 1 and if this is satisfied then it is definitely satisfied with other elements okay so that's why I am going to sort our array first so here after sorting my array it is going to look like this so uh this these are the index this is the index okay and this is our array okay so at zero index element is one at one index element is four at index 2 element is 7 at index 3 element is eight and add index for and is 16 okay so now we have sorted our array after that in order to solve this problem we are going to create one DP array okay and in this DP array I'm going to fill all the elements initially one okay so here I'm going to create one DP of same size of this array and I'm going to fill all the elements with one okay so all I have filled all the elements as one and after that I'm also going to create one previous index named array okay in this array initially I'm going to fill it with the index only so here see this is zero index so here I have fill zero here this index is one so here I have filled one initially here this is two I have f it as two here it is three I have f it as three here it is four index so I have filled it this PR array as 4 so what this PR array is going to store later on so this PR index is going to keep track of the last element in the DP that we are going to add at our particular index so let's say uh this is DP of I right this is index so this DP of I in this DP of I if I'm going to add this element this particular element then I am going to store the index of this element here in this previous index okay because here I'm going to keep track how my d p is going to look like after I'm adding this okay so what did I add in my DP so that it is looking like this what is the last element that I have added at this particular index so it is going to just store the previous index that we have that our DP has used at this point of time okay so this is the use of this previous index and also we are going to create two variables one is max length and we are going to set it to 1 initially and we are also going to create one variable as Max of index and we are going to set it to zero initially okay now this these are the our first basic steps that we are going to perform in our code okay this that's done now after that what we are going to do we are going to run one Loop for Loop which is going for I so initially I'm going to set my I at this zero index okay I is this at this index and J is also at this index okay I'm going to use one four uh four Loops okay now for initially I'm going to check for this condition J is going to till run till J is less than equal to I so if both I and z are zero for the first case then uh there is nothing going to happen inside my Loop okay because my J is going to run till I less than I okay so now let's uh skip this step First Step okay so let me skip this step okay so now my I is at this index and J is this J is at this index okay so now first I'm going to check if my nums of I if I'm am going to check if nums of I mod of nums of J this is what I'm going to check if my nums of I that is this okay and mode of nums of J so it is true okay it is true and after that I am also going to check if the DP value okay if the DP value of at J is nothing but zero so DP of 0 is 1 if DP of J okay this day and when I'm going to add one more element in the DP so this was the initial one and after that I'm going to add one more element in our DP so it is going to be two and two is greater than the DP value which is available at this index okay so this is the initial DP okay when I am going to add an element uh this element in the DP okay so I am checking what is the total count total sum is two okay but here I store only one okay so this is greater now so here I'm going to modify it with two okay here I modify the size of my DP of i s 2 because now the two elements are there in my subset what two elements 1 and four two elements are there in my subset okay so I have modified my DP I as that is DP of i as DP of J that is 1 + 1 so is DP of i as DP of J that is 1 + 1 so is DP of i as DP of J that is 1 + 1 so total it becomes two and here I told you that in previous index of I this position we are going to store the J's index so J's index is zero okay since this is using this value okay this value J value so it is at index zero okay so here I have stored zero okay so I hope this is clear now after that my J this step is completed my J reach is here and now I J is less than I so this is not true so I have to skip this so let me erase it okay so this is not required now okay so this is we are going to use later on also so now my I reaches at this position and now again my J is going to start from zero to less than I okay J is going to run from zero to less than I so first my J is at this index okay so now I'm again going to check if the this s is divisible by 1 is this 7 mode 1 is equal to 0 yes this is zero and here I am going to check the frequency it is one DP of 2 is one right now but when I'm going to add s 11 and 1 together then in that case this is going to become two okay and this PR index is using this J value so it is going to become zero right this is going to become zero so this is for I when my I is at this position and J is at this position now after that what happens this J moves to this index okay so now when J is at this index then again I'm going to check if my nums of I modus of J is uh zero so 7 mode of 4 is zero no it is not true so if this is not true then we have to do nothing okay we don't we need to skip this now this is completed now after that let me raisee it now after that my I reach is at this index and J is at this index previous first time okay so now I am going to check if eight this eight mode of this one is uh zero yes it is true so now I am going to add two elements one and8 both are added so when one and eight are added so here I'm going to update the previous index that eight8 is eight has used so it has used this one now so this one is at zero index so here I updated to zero okay so this is completed Z is completed now my J reach is here now I'm going to check if 8 mode of 4 is zero yes it is zero if this is zero then I am going to check what I am going to check if the value at this Index dpo2 this is true now when I'm going to add one more element that is eight here this was two previously so when I'm going to add eight here so it becomes total three and this is two given only this is two here only so when I am going to add this three here okay this is going to be updated to three because here I find one more element 1 14 and one more element 8 1 148 okay so when I'm going to add 148 so here I have added three total three elements at this TP ofi and here this 8 uses this Index right now this index four okay to join the elements so four is available at which J is one so here I have wred it to one pre Vis to one okay re is updated to one now after that this step is completed and my J reaches here so when my J reaches here I'm going to compare if 8 mode of 7 is zero no this is not true then we are not doing anything okay so this step is completed as well okay so now let me erase it so now after that my I reaches here okay so first time my J is zero J is at this index so I'm going to check if 16 mode of one is zero yes it is true so this is 16 only now when I'm going to add 11 16 so it becomes two and here J is going to updated as zero because J is using this one okay J is updated to this zero now my J reaches this index then I going to check if 16 uh mode of 4 is uh zero yes it is true and what is the size here available this is two available but now when I'm going to add 16 also in 1 4 and 16 when I add this then it becomes three okay so now it becomes three and here this is going to be updated to this index one index because I'm using this four okay so I updated this one three and one now my J reach is at this position so now I'm checking whether uh this 16 modulus of 7 is zero no it is not true so I'm going to skip this step then my J reaches here now at this index I'm going to check whether 16 mode of 8 is zero yes it is true if this is true then it is going to check for this DP of I value this value so in this value it was three elements before now I'm going to add 16 one more so it is going to update as four because now 16 is added here at this index 1486 so when four is added here and at which Index this eight as element present is three so here I operate to it to three okay so now from here one thing is clear that uh my DP is looking like this okay so my DP is looking like this first add this it is not one then two then three then four this is how my DP is looking like right and my PR how it is looking like that how it is looking like uh zero then one then three it is looking like this right okay so my DP is looking like this and my PRI is looking like this okay so now what I'm going to do after that so after that see this is a array given to us 1 4 7 8 6 so first time I'm going to add in the list of subset whatever available so let's say I'm going to say it as subset so in the subset first I am going to add what Max index so here uh we are also going to keep note of what is our max length and Max index after each step okay so my max length finally it is going to update to this four and Max index at which index it is available at three Okay so we are going to keep track of this one else as well okay so this is the maximum length that I get four and this is the max index three this is Max Index this is the max length to first in my subset I'm going to add the element which is available at the max index so what is the element that is uh at Max index okay so at Ma Max index that is this three what is the element okay what is the element available at the max index okay so here one more thing uh first we are going to add the nums at Max of index okay so max of index is going to be four Max of index is updated to four only and Max of length is also going to be updated to four okay yes so it is also going to be update to four only okay Max of Index this is a prear this is prear ignore it okay so max length is four and Max index where it is available that is also going to update to four okay not three four okay so max index is four and what element is present at our Max uh index 16 so I have added this 16 in my subset okay now after that I am going to check if the element at this I'm going to check this element because after that I'm going to use three index okay in this prev you see uh in the last step I get the three because this is the element that I'm using so I'm keeping tracking of the elements now so here I find the last element 16 that I've added right and here I give the link that I am using this third this three these three elements okay I am using these three elements I'm using these three elements for this one okay so I'm keeping the track okay previous index so I reached the previous index here eight so I am going to add that 8 now when once I reached here then I'm going to check this one okay what is the previous reference here so it is previously referring to index one okay it is previously referring to index one so I am going to reach to the my index one so what is the index one what is the element available at my index one so at index one element 4 is available I'm going to add it okay after that uh this I reached here okay at this four and after that I'm going to check the previous but is previous showing it is showing me to go to zero because previous element that we have used till here is zero so when I reach zero so I have added one now here when once I reach this one then again it is refering to zero so once uh element uh is going to reference to itself in that case I'm going to return I'm going to don't print anything I'm going to just break okay so here what is happening see this is how our DP looking like okay and uh we are also go keeping track of the max length and Max index so max length we are keep tracking of the max length in our DP so what is the max length that we get four and there is one more element Max index okay so this Max index and this pre values are different okay this is not the same so max index is going to show us at which index that we get the max length so we get the max length at four Index right at Fourth index only we get the max length Okay so here this Max index is four and max length is also four then after that I'm going to in my subset I'm going to add the element which is at Max index so max index element is 16 then I ask the 16 Index this 16 is avilable at four index so I ask that pre index that this is the array this is the pre array so I asked this pre that what is the value available for this index for you so he said uh this pre said that for me at this particular index 4 this three is available so I said okay so now let me access this element which is at third index available for you available in the array so I access this eight so now eight asks uh it ask this Bri what is the element available at this particular index uh okay so said the one index is available so said that okay let me go to one so it added four here the now this four is going to ask uh this four is going to ask that this PR aray what is the reference or the of reference stor here so it said that I took the element from zero okay so my array going to pick this one and it going to add one then one is going to check with this pre VAR okay what is the reference so it said zero okay so you are just pointing to me only so that is not the possible case because in our problem it is mentioned that distinct positive integers are available so we are going to just return it okay so we have to just print this output 16 18 41 okay so this is for backtracking purpose okay so this bra are we are creating just for backtracking purpose now this is the complete theory that I'm going to write now in our code step by step okay so if you guys are clear with the logic now let's write the code so first uh as I told you we are going to create one DP array okay int DP and the length of this DP is also going to be the same of our nums do length Okay nums do length now after that I have told you that we are going to fill the elements in our DP AR that uh AR do fill where in our DP and with which element one element okay so I'm going to fill every index in another DP as one okay initially and after that I told you that we are going to use sort so array do sort and we are sorting what this nums okay array do sort nums now after that I'm going to create one PB index okay previous index and in this same length new int same nums dot length Okay now I've created previous index array in which we are going to store the reference of the previous element that we have used that particular index of DP okay now I'm going to create max length and Max IND index max length and I'm going to start it with one and int Max of index I am going to start it with zero okay that's it now after that I'm going to run two Loops simple one is I and one is J for INT I is going to run from zero and I is less than nums do length l e n GT h length and i++ after that inside this I am saying i++ after that inside this I am saying i++ after that inside this I am saying that uh here I have told you initially that I'm going to give the initial value as index only for the priv okay here initially pre is zero because this index is zero previous one because this index is one previous two because this index is two previous three because this index is three so initially I'm storing values like this so can I write it like this previous index at this particular ie is equal to I only okay so here I have initialized uh the values in our previous index now after that I'm going to run one J Loop for INT J is equal to Z I have told you J is going to run from zero and J is less than I okay that's it so this is already clear right okay so now this J Loop and after that inside J loop I am going to check but if the number which is at I mode of nums which is at J is equal to zero okay this is one condition I'm checking and in the end and I'm also checking one more thing that uh the element which is present at the previous index that is DP of J and when I'm going to add one more element in this DP of J okay once I find this num I mode of num J is equal to zero so when once I am going to after that I'm going to add that element into one so it should be uh greater than the value which is already present in DP ofi if it is less than then we don't need to update it because we are already find the max subset Max I subset but now if uh after adding this uh I we are finding if after adding this element we are finding one greater subset then in that case we have to add that element okay so if DP of J + 1 is greater than okay so if DP of J + 1 is greater than okay so if DP of J + 1 is greater than DP of I okay so in that case only we have to update what so I have told you that we are going to update the DP of I value okay this DP of I value with the previous values if I'm going to add the DP of J + one so can I write it like DP of J + one so can I write it like DP of J + one so can I write it like this DP of I is DP of J + this DP of I is DP of J + this DP of I is DP of J + 1 right and I'm also going to update my previous index okay I also going to update my previous index of I with but with my J value previous value because there is a reference to the previous value only so this is clear okay so I hope this is clear this is what I'm doing here in this step once I'm going to chuse this element then I'm going to add the size here to and here it is going to point the previous element so this is what I'm writing here so I hope this is clear now after that I have told you that I'm also going to update this max length and Max index side website so in order to update it this is my if condition and this is my full group okay so now after that I am going to write one if condition and in this if condition I'm going to check if DP of I okay if this particular I is greater than my max length which is initially given as what one if it is greater than this max length then in that case what do we do you just update this max length with the value which is present at this index DP of I and also update the max index and we are going to update Max index with which the value which is at a max length where max length is available so I so here again I'm right the wrong spelling okay Max of length is equal to DP of I and Max of index is I because this is a particular index where the maximum length available okay so this is it now after that now code is very simple okay so here we have written one if condition and this is where our for complete for Loop ends now after that once we get everything I'm going to write one create one list and list this list is simply what subset where we are going to add the elements okay so list of integers this is a list of integers only Now list of integer and let's name this list of integers as subset because we are creating the largest divisible subset okay so can I create it name as subset yes I can and I will okay subset okay and then this is a ARR list so new array list and then close it okay and after that first I told you that we are going to add what element the element which is available at the max index we are going to directly add that element into our list so can I write like this subset do add but after that the element which is present at the Max of index so the element which is present at Max index I'm going to add this element into my subset and then I'm going to run one while loop and in this while loop I am going to check for the previous index array elements so when previous index I is capital right I is capital previous index when previous index the element which is available at Max index okay the element which is available at this Max index if this Max index element is not equal to uh this Max index okay if this is not equal to Max index then in that case we have to just update our Max index with which uh the we are going to update our Max index with the previous index of Max Index right previous index of Max Index this is going to our new Max index and then we are going to add this element again subset do add and the element which is present in the nums array for this particular new magx index okay so here that's it and then in the end we have to just return the subset return subset okay so now let's run our code and see if there are any spelling mistakes or any code issues let's run it okay so I see first spelling mistake nice A R A Ys okay next let's go next oh nice so all the test cases has been accepted here now let's submit our code and see good so our solution is accepted okay so I hope that you guys are able to understand today's problem if you guys still have any questions then please feel free to ask in comment section till then keep coding and keep practicing and don't forget to subscribe my channel like and share this video with your colleagues your friends okay and meet you in the next video thank you bye-bye
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null
77
the question is combinations okay statement is given two integers n and k return all possible combinations of k numbers out of the range 1 comma n you may return the answer in any order okay look at the first test case we have n is equal to 4 and k is equal to 2 what they mean is we have to make the arrangements or combinations of k elements means here k is two means here the one arrangement will consist of two elements okay and how many possible arrangements are there how many possible combinations are there of k elements that we have to return okay now n is four what does that mean that means we have four numbers one two three and four why because our range is inclusive one comma n means we can include 1 as well as n so when n is 4 we have these numbers okay 1 2 3 4 what does they mean is we have to make all possible combinations how we will make the combinations okay just go manually okay let's start if we started from one okay if we took one then how many combinations can we make from one see we have to start from the next number okay one comma two okay then one comma three then one comma four right one comma four this much common this many combinations are possible with one now let's start from two yeah if we started from two then how many combinations will be possible two comma three and two comma four okay we have to see for three and four if we start from two now let's start from three how many combinations are possible with three starting from three 3 4 that's it if we started from 4 there are no numbers after 4 so there will be no combination starting with 4 how we will solve this programmatically okay so let us imagine we have an empty array first okay we have an empty array so now we have to start each time we are going to start firstly we started from one wrote all the combinations starting from 1 then we found all the combinations starting from 2 then we found all the combinations starting from 3 then we found all the combinations starting from 4 means one by 1 we are finding the combinations starting from each number firstly 1 then 2 then 3 right what does that mean we will go one by one and we will traverse each element that means we are using for loop okay remember this thing firstly so what we will do imagine that firstly if we started and we appended one in our array okay we appended one in our array as a as we are starting from one now we will ask the function to give us all the arrangements or all the combinations that are starting from one how what it will do it will look at which is the next element after one it is two so it will append this to one comma two now again what we will do we now have an array of one comma two now we will ask how many possible combinations are there with this array start with starting this array one comma two so three will be there so we can also do 1 comma 2 comma 3 but we are not going to do it why because we are having the condition that we should involve only k elements and here in our case k is 2 so we can take only two elements so we will return from here as soon as we get two elements in our array we will return okay remember this thing also so now we made one combination one comma two now we will make one comma three and we will make one comma four as i explained earlier right these are the possible combinations after that we will we are going to return right because the k elements have been fulfilled so now we are here at one now what we have to do we have to remove this one and instead of one we will start now from two okay so we will pop this one out and we will append again what two and we will start from two how many possible combinations are with two comma three then what we'll do we will pop this three and involve four instead of three so it will be two comma four right now we will start from three we have popped this two and involved or appended three instead of these two and we are seeing the combinations starting from three that are three comma four and there is no possible combination starting from four why because there are no elements after four okay so this will return from here itself so this much possible combinations are there okay here also they are written okay so now we will see the coding part how can we do this initially we have to return one base condition what will be the best condition that if the length of our array or if we have k elements fulfilled then we will return like here we got two elements we returned so every array will be of two elements and as soon as we get this array of two elements we will append it in one variable called as our result and finally we will return that result so how can we do it let us see in the coding part now we will see the coding part we will make one variable one array as a result so we are going this we are going to return this list of all the combinations we will make one function called as backtrack which will take an empty array as an argument and one variable we will call you call it as current number now we will write our best case that if lane of array becomes equal to k means if we have the combination that is having k elements in the array so what we are going to do we are going to append it into the result we are going to make further changes in array that's why we are appending the copy of array instead of array directly and we will return after appending we have to check the combinations starting from each element initially one then two then three so what we are going to do we are going to write one for loop it will be from current number to last number that is n okay what will be current number initially current number will be 1 so we are going to check the combinations for 1 comma 2 1 comma 3 1 comma 4 if the current number is 2 then we are going to check for 2 comma 3 to comma 4 so likewise we are going to check so what is the next thing that if we are checking for one then we have to append that one into the array so array dot append one then not one start because after one we are going to call the function we are going to check the combinations for 2 then for 3 that's why we are appending start in the array then for checking the combinations starting from this start variable what we are going to do we are calling the function backtrack this will give us all the combinations that are starting from this variable start are getting means initially combination starting from 1 then combinations starting from 2 so initially start will be one then start will be two this is how it will work now backtrack array comma start plus one we are calling the backtrack function for array containing one element and then we are going to move to the next element that's why we have done here start plus one okay after that what we will do if we check all the possible combinations that are starting from one then what we'll do we'll pop this one this last element that we checked now from the array and instead of that element so if we popped one then what will happen this for loop will run for the next element so it will append 2 it will get all the combinations starting from 2 then it will pop the 2 then it will append 3 then it will this function will give us all the possible combinations starting from three then it will pop three and then for loop will continue for four then four will be appended then the function will be called for the for all the elements after four but there are no elements after four then finally it is going to pop 4 also and now the for loop will also vanish because it is on 4 and after for vanishes it is going to return none right so this is how our function will complete and finally we have to call this function initially we will give it an empty array for combinations and we are going to find the combinations starting from 1 initially then it will keep running for two for three whatever until n and uh this combinations will be stored in our array so finally what we will do we will return our result right the array scopy is being stored in result right so finally our result is something that contains all the possible combinations and we are going to return it okay this is running fine so we'll submit it yeah it is running good right if you have any doubts regarding this then ask in the comment section focus more on the recursion part just learn how to solve the problems instead of focusing on just one problem because if you learn the algorithms then you can use the same algorithm for so many different problems okay
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
102
hey everyone welcome back and let's write some more neat code today so today let's solve binary tree level order traversal it's basically just like it sounds so we're given a binary tree and we want to return the level order traversal of its nodes so basically going through every single level of the tree and going from left to right so for example for this tree we have this level so that's going to be one list we have the second level 9 and 20 and then we have the third level 15 and seven so we have one two three lists and these lists are going to be put together and that's going to be our result the three lists in that order so to understand what we want to do is pretty straightforward right so basically we have the first level right go from left to right we see that there's only a single node in this level three that's going to be one list we see the second level right that's what we want to do we want to traverse this tree every single level right one level at a time going from left to right so the second level we'll see 9 and 20 right we want to add that to a separate list and lastly we'll get to the third level going from left to right we have a 15 and then a seven we're going to add that to the third list and so we've traversed the list in level order traversal and each of these sub lists are going to be put together into a single list and then that's going to be our results so that's what we want to do we know that's pretty straightforward so the only question now is do you know an algorithm that can do that can traverse it level order and if you don't the algorithm is breadth first search so we want to run breadth first search on our tree and then add the values into lists and the second thing to notice is do you know how to implement this breadth first search so we need to know this is the algorithm to use and now we need to know how to implement it and let me show you how to do that so we have a tree and we want to run a pretty standard algorithm on that tree called breadth first search and you might know how to already implement this algorithm you need a q data structure because we're going to be inserting elements to the right meaning we're gonna you know insert an element here right we're gonna be adding elements to the right portion and we're gonna be popping elements from the left portion so as soon as an so basically we're following first in first out right the first element that gets inserted over here is going to be the first element that gets removed right so that's the order we're going to be doing things in so the first thing we're going to do is take the first element 3 and add it to our queue this is based basically to initialize the queue right and we know we're creating sub lists right so what we're gonna do now is see that okay how count how many elements are in our queue initially right there's one element in our queue so we're going to basically remove one element from our queue we're going to see okay the 3 is in the queue now let's get rid of the 3 and add it to a sub list right now the queue is empty so we know that this sub list is complete and what that tells us is basically we went through the entire first level right that's what we're trying to do we're going through every level we know that the first level only had one element in it so now we're done but when we pop that three we need to add its children right it has two children it has a child nine and a child twenty so we're gonna add those children to our cue and we're to do it from left to right because that's important right we're doing this from left to right so we're going to add a 9 then we're going to add a 20. okay so now we want to go through the second level of the tree right so we're going to have a sub list for the second level clearly we have two elements in our queue so we're gonna basically pop these two elements from our queue from left to right so the left is nine we're gonna pop nine from the queue add it to the sub list so nine is added to the sub list and notice how nine did not have any children right so we don't have to add any children for nine into our queue so next we still remember we had two elements we were trying to remove we have two elements in this level so let's now pop 20 so we can add 20 to our sub list right so now clearly this level is complete we added both nodes in the order 9 and 20 to a sub list but notice 20 had a couple children had 15 and seven so as we remove 20 from our q we're adding its children to the queue for the next level right because we know we want to keep going down a level so when we get here the values will already be added to our queue so 15 and 7 are added to our queue we're done with the second level now time to go to the third level we see that there's two nodes two values in our queue so we're gonna pop both of these values first we pop 15 add it to the sub list for the third level and then we pop seven add it to the sub list for the third level neither of these nodes had any children so now we're done we know we're done because our queue is now empty right there's nothing left in our queue so we created a sub list for every single level and as the question wanted us to do we're going to package all three of these sub-lists into one all three of these sub-lists into one all three of these sub-lists into one list and then return that as our result so we're really just doing a breadth first search algorithm with a queue on this binary search tree and since we're doing it like that the time complexity is going to be o of n we're only visiting every single node a single time the memory complexity is also o of n because our q at any given point in time our q could have up to n divided by two elements in it because the biggest level of a tree could be n divided by two that's how trees work binary trees at least and so we know that n divided by 2 can be rounded to big o of n so the memory complexity is big o of n with breadth first search so with that being said let's jump into the code so first let's initialize an array for the result and we also remember want to have a q so in python we can do that with collections dot deck this will give us a q and the first value we want to initialize this q with is the root node that we're given so with that we can start running the breadth first search and we're going to run breadth first search while our queue is non-empty remember while our queue is non-empty remember while our queue is non-empty remember and since the queue is not empty we're going to get the length of the cube right so we're going to get the number of nodes or values that are in this queue currently and we're going to go we're going to loop through every single one of those values this q length is basically ensuring that we iterate through one level at a time we're going through one level at a time and with those nodes from that level we're going to be adding them to its own list right and then we're going to add that list to the result list so i'm going to loop through every value in this queue currently so for q length i'm going to pop nodes from the left of the queue right first in first out and it's technically possible that the node could be null so i'm going to have a check to make sure it's not null then we're going to take the node value and append it to the list level and don't forget this is also important that to our queue we make sure to add the children of this node so node.left node so node.left node so node.left and node.right technically these could and node.right technically these could and node.right technically these could be null but that's why we have this if statement so then when the next loop comes around right we come around to the next iteration of the while loop it'll make sure to check that these nodes are non-null check that these nodes are non-null check that these nodes are non-null before adding them to its own level list okay so now we have the loop in place that's going to iterate through every node of a single level after we've done that entire level what we're going to do is take our result and make sure we add every single level to that result right and then we're going to keep running this outside while loop the outer while loop until there are no nodes left in our queue that's how we know we've gone through every single level added it to the result and then at the end we can finally return the result and one last thing we want to do is make sure that if we're adding a level to the result we want to make sure that level is non-empty because we know technically non-empty because we know technically non-empty because we know technically our queue could have null nodes we're not adding null nodes to the level list so we want to make sure that level is non-empty if we're adding it to the non-empty if we're adding it to the non-empty if we're adding it to the result we can run the code and see that it does work and it is pretty efficient this is a breadth-first search a breadth-first search a breadth-first search level order traversal of a binary tree and we did it in linear time and i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
424
hello everyone and welcome to my first liko tutorial it's lee code number 424 the longest repeating character replacement so basically with this problem we're given a string s and an integer k we can choose any character of the string and change it to any other uppercase english character and we can perform this operation at most k times our task is to return the length of the longest substring containing the same letter we can get after performing the above operations okay so looking at the first example we're given a string s equals a b and we're given character replacements of at most two so looking at this string we can see that if we change the two b's to a's we can get a length of four a or vice versa we can change the a's to b's and get b right for the second problem if we look at a character a at index three we change that to b we also get a length of four right we have at most one um character replacements um allowed right so what are some of the edge cases well with this one we know right off the bat if a string is has a length of one or less then we don't need to do any further operations so we can actually write that here and just get rid of that scenario right but how do we solve this we are given kind of hints and we have some constraints here we can see that we don't need to worry about other characters it's only we're only dealing with english uppercase english characters and we're given another hint we're looking for the longest substring so this tells us that we're gonna probably we can use um slide in window um pattern to solve this problem and typically sliding window um problems are solved with two pointers one on the left and one on the right and we're gonna see how that what that looks like in a minute just in a moment yes all right okay so this is what the algorithm looks like typically so what we want to do is look at each character in the string and then increase the count of the character in memo for the current window after we're done getting this count we then need to find out the frequency of the character which occurs the most or the character which has the max frequency this max frequency we will then subtract it from the current window length or the current substring length right which will then tell us how many characters we need to replace if the value is less than or equal to the k allowed replacements then the window is valid and we can continue all we need to do is then need to update the max length or the longest repeating character length this is the value we will ultimately return otherwise this means the value is more than the key allowed replacements the window is not valid and we need to decrease the count of the character in memo at the current pointer and then we need to increase the pointer so let's go ahead and code that what are some of the variables we'll need well we mentioned that we need to return like a length and we just call that max that's what we're going to return our result we also need the window length or the current substring that we are looking at and we can call this temp max we need a pointer we'll start it at zero that's the first index in the string we need a memo that's for keeping track all the counts uh or the frequency of a character in the string right we need a difference because we mentioned that we are gonna this max frequency will then subtract it from the current window length which will then tell us how many characters we need to replace so we also need a max frequency to count so this max frequency count represents um the character which occurs most the most in this string or the current window that we're looking at so we know that we're going to need a loop because it mentions that we are going to need to look at each character so that tells us we need some sort of loop and we can return max because that's what we're gonna be returning okay so we're gonna be counting up after we look at each character we need to keep track of its frequency and so we need to check that this if it's not undefined first there is a one-liner for this but to there is a one-liner for this but to there is a one-liner for this but to keep things readable we'll just do it like this for now so we just check if it's undefined we initialize it to zero and then we can just increment for that character the next thing we need to do we need to keep track of who has the max frequency count against the current what we just currently looked at to see if that was that actually is the new max okay then we need to get the length of the current window and the way in which we do that is temp max we have that as temp max i minus p which is the right pointer minus p the left pointer plus one and we are adding one because we are dealing with zero indexed arrays and now we need to get the difference we said that this max frequency will then we will then subtract it from the current window length so let's do that now so the current window length temp max minus the max frequency count and then now we need to check that this if it's greater than the k allowed replacements then we have a problem otherwise we can continue we can check our max against our current window let's see if we got anything higher or longer so we mentioned that we need to decrease the count of the current point of p and then we need to increase the pointer right so that should be it let's run this in c and there we go four so let's try with another b and we should get five we get five okay so we decreased the count but why didn't we continue to keep track of this one um one of the reasons why we're keeping track is so that we don't have to continuously loop through the entire memo to see who has the max we're keeping track here but if we do a loop here that kind of defeats the efficient purpose of making our algorithm more efficient however technically we don't need to update this because the result max is only ever updated whenever max frequency count is increased so it's not going to affect it um we can you know if we you know we can debug this and go through line by line and we'll see that we technically do not need to do something like max apply math object values memory so this call here already has an op um has a complexity of time complexity of n and math max apply is another plus another organ so this defeats the purpose of actually keeping track here r01 operation here so um but we as i said we technically don't need to update this because the result max is only ever changed when this is increased so we can remove that okay and our algorithm will work just fine so here we added our drawing board and we're going to look at the string a b a and when i is equal to 0 and our pointer p is also equal to 0 we're then looking at a right so if we're looking at a index 0 add that to our memo and what do we need next well we know we need to get the length of the current substring the current window and we can see that's one but how do we get that well remember we had our little formula i minus p plus one this gives us our temp max or the length of our current window or substring and using the temp max we're gonna take away or subtract the max frequency count and this is going to give us the difference and the difference tells us how many characters we need to replace so using this formula we know that our temp max is going to be one and the max frequency is one which is going to give us zero which is our difference and this difference with a zero it's less than k so our window is valid and so we're gonna have a max result of one okay now when i is equal to one we now add another a we increase that and we're gonna get for our temp max or the length of our window to be 2 minus 2 which is the frequency and we're going to get another 0 which is less than k so we're good our window is good and we can update our max result now when i is equal to 2 we're now at b is going to be one the length of our window is now going to be three minus two which is going to be one and it's equal to k so our window is still good now we're gonna get a max result of three now when i is equal to three now we're in another a so a is going to be three and the length of our window is going to be four and a four minus three is one which is still it's equal to k so the our window is good now we get a max length of four now when i is equal to four we're now at this b so now b is two and the length of our window now becomes 5 minus 3 is 2 which is more than k so our window is not valid and so we need to decrement at pointer p which is a so we need to decrement a get two and we need to increase pointer p and subsequently i is going to be increased so i is going to be 5. and so our window is now going to be here oops let's write that properly so we can get this mouse and i is now at five which is another b so we're gonna get three and the length of the window is still gonna be five so it's five minus three which is two which is still not valid and so we need to decrement at pointer p which is now at one and at one it's a so now we get one and we need to increase pointer p and subsequently i is going to increase to six and so our window is now going to be here over here and actually a is also going to increase to 2 once again because it's another a so now we have a window length of still five and the frequency is still three b is still in the window and we're still going still invalid and as we can see we never update max result and so since i has already reached the end then our loop stops and our result of four is returned and that's it so we're done here so if this tutorial was helpful to you let me know in the comments below if not also let me know in the comments below thank you so much for watching take care
Longest Repeating Character Replacement
longest-repeating-character-replacement
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times. Return _the length of the longest substring containing the same letter you can get after performing the above operations_. **Example 1:** **Input:** s = "ABAB ", k = 2 **Output:** 4 **Explanation:** Replace the two 'A's with two 'B's or vice versa. **Example 2:** **Input:** s = "AABABBA ", k = 1 **Output:** 4 **Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ". The substring "BBBB " has the longest repeating letters, which is 4. **Constraints:** * `1 <= s.length <= 105` * `s` consists of only uppercase English letters. * `0 <= k <= s.length`
null
Hash Table,String,Sliding Window
Medium
340,1046,2119,2134,2319
3
hello everyone so today we are looking at lead code number three longest substring without repeating characters uh this is a very popular question that's asked at a lot of companies you can see here in the last six to eight months very frequent at bloomberg amazon microsoft facebook all around so i highly suggest that if you're not familiar with this problem and the patterns that it uses to take some time to definitely familiarize yourself because it's a good probability that you might see it out in the jungle okay so here we have our prompt here given a string s find the length of the longest substring without repeating characters so here we have a string abc bb the output is three because the longest substring without a repeating character is abc however example two we have just a substrate or a string with all repeating characters so the longest substring is one example three we have pww kew so our longest sub string is going to be 3 again it can be kew or wke all right moving on we can also have an empty sub string and with an empty string our output would be zero okay so let's take a look at a brute force way to approach this problem and then let's look at a more efficient way which is using a pattern called sliding window and it's definitely a pattern that you want to be very familiar with because you're going to see the sliding window approach can solve a lot of problems anytime you're dealing with strings contiguous strings sub strings it's a great way to solve those types of problems so let's look at both approaches so here we have a string abc bb so let's jump over here okay so we have a string uh a b c b okay and we want to get the longest substring which is going longest substring without repeating characters so what would be a brute-forced way to so what would be a brute-forced way to so what would be a brute-forced way to do this well what we could do is we could find every single substring in this input string and then we could go in and hash every single one of those substrings and count the frequency if the frequency of the characters is greater than one then we do not accept that string and we want to find the longest substrings where all the frequency count of the characters are one so let's take a look here so what if we found all the substrings so we're going to have a b abc a b a let's see a b c a here we're going to have a b c a b and so forth and so on okay so we're going to get a lot of substrings with this and then what we can do brute force is we can go ahead and hash this a so we can have an a and a frequency of one so that could be a potential substring we could have hash this so we could have a b and count the frequency there we can count the frequency of this substring this will be a1 b1 c1 and then here this substring you can see that a is going to equal 2 b is going to equal 1 c is going to equal 1. so this will not be a potential candidate neither will this because we have a repeating character there and a repeating character for b as well and so what would our time and space complexity be for this well to get every single substring brute force it would be o of n squared would be our time for getting all the substrings then we would have to run a linear operation on every single one of those substrings so our total time complexity would actually be o of n to the third and what would be our space complexity well to get every single substring we're going to have o of n squared space plus we're going to have to also have o of n spare one more o of n square space to hash every single one of those substrings it's going to be o of n squared plus o of n squared so our total space or approximate will be o of n squared space so we have o of n cubed time and o n squared space which is not good which is not great right so could we do better okay let's take a look at the sliding window approach how do we approach that let's clear this b abc b okay so here we have the string a b c b what i'm going to do is actually just make it a little bit bigger a b c b okay now with the sliding window approach we want to have two pointers we want to have a window start and a window end and i'm going to just keep these variables here just so we can keep track of everything here will be our windows start here will be our window end we're going to have a running max okay we can initialize that to zero because we can have an empty string as an input and if we do have an empty string then we want to return zero so our max is we can initialize that as zero we wanna have an ith index or where we are iterating start and end we'll i'll just keep track of the values and i will be keeping track of really end but at the index and then we want a variable so far i'm going to actually put it up here okay and so if we have so when we have so far what do we want to use what data structure we want to use well i think using a object would be a great way because we can keep track of the frequencies using an object and then if the frequency ever gets above 1 then what we want to do is remove we want to decrement start and increment the start position okay this will make a little more sense as we step through this all right so let's say we are at index zero s start is going to equal a the character at e end is going to also equal a and our max now is going to be one okay and what are we going to have here at so far well so far we're going to have a with the frequency of 1. now do we have anything that is greater than one in terms of do we have a repeating character because we want to get the longest substring without a repeating character so we want to create a window that moves forward or contracts depending on making sure that every time in inside of that window we have a substring that does not have any repeating characters so our so far is good we can go ahead and increment our end okay and now what are we going to do we're going to be at index 1 a is s's start is still going to equal a end is going to equal b and we can add this b here to equal 1 and we can say that okay we are still in a substring that's valid in our so far okay so we can now increment max to 2. okay let's keep moving end equals c so now we have c that equals one again we're still good we have a sub string here that is valid there's no repeating characters in it okay so we can uh increment this to two it'll still equal a this will equal c and we can increment our max to 3. now what happens here we get to a okay and so this is going to equal 2 and now this is not valid right we do not have a valid substring here so what do we want to do well what we want to do is we want to move our window at start position here our window here at start position and we want to decrement this a out of our so far and see if we're still valid okay so let's say we are at s here and we decrement this a back to one and move this start over there okay so now we're valid now everything is still valid okay so i is going to equal 3 start is now going to be at b end is going to be at a and the max is still going to be 3 right let's keep moving you can see that this pattern starts making more sense here end is b then increments to 2. this doesn't work we move start over we decrement b out of our so far and now it's valid and we can move forward we can update max and we can keep on going all the way to the end until we reach the end and we can then deduce what is our max and that's going to be our answer okay so what is our time and space complexity using this method well our time complexity how many times are we hitting each one of these variables right so our time complexity here is going to be o of n squared right because we can contract and expand so worst case we would have we could go through everything twice and what would be our space complexity well we our space complexity is going to be our so far here that's going to be the worst case so it at worst case we could have every element in our so far if the whole string is there are no repeating elements in the entire string then our space could be at worst case o of n okay so this is much better than the brute force approach which was o of n to the third and o of n squared space here we brought it down to o of n squared for time and o of n for space okay so let's go ahead and move over to the code all right and so what do we want to do here first what we want to do is we want to create a max variable so we can say let max equals zero we want to have a start for our window so let window start and we're going to set that to 0. we want a hash so we can do const so far and we'll set that to an object okay and then we want to iterate over our string so 4 let window end we'll set that to 0 when window end is less than s dot length window n plus okay so here we're substituting i and the end as the same variable okay it's just going to be the window end is this right here and that's what's incrementing moving to the right all right so here we have window n and now what's the first thing we want to do we want to update our so far so we can just put this in a variable we can just say let write char which is going to equal s of window end all right and then we want to update our so far variable so far at right char now this is going to equal if there is nothing in the if there is already something in the right chart we just want to add one to it okay so we can do so far right char if that's true we're going to add 1 to it or we're going to set it to 1. okay all this is doing is it's checking do we have something in so far if this is true then what we want to do is go ahead and use this expression right here which is going to take the current value and add 1 to it if this is false if this is undefined then we're not going to use this expression we're going to set it to just 1. and that's what this will equal right there so that's all that one line of code is doing all right now what we want to do is we want to decrement we want to check if that's so far if the value is greater than 1. so while so far at right char is greater than 1 what do we want to decrement from the left we want to go ahead and take whatever's at the start position decrement it from so far and then move windows start over one so let's go ahead and get our left char and that is going to be s of windows start all right and now what do we want to check what is the value at uh our left char okay so if it is greater than 1 we want to decrement it if it is 1 we want to delete it all right so we're going to say if so far at left char is greater than 1 then we want to just go ahead and decrement this we want to do so far at left char minus else we want to delete so far left char because if it's at one then that means it's going to be at zero and we want to just delete that element out of our hash and then we want to increment our window start plus and then what do we want to update our max so max is going to equal we can do a math dot max of whatever is current whatever our current max is and window end minus windows start and we're going to add one here because you can see that the prompt wants the length the prompt is asking for the length not the indices so when we're looking at e k w k e we want the length which is three and that's why we're going to add one here because the indices will give us one less than the length and then all we want to do is just go ahead and return max okay we can run that and that is looking good so that is leap code number three longest substring without repeating characters it's using a very classic pattern which is the sliding window pattern and you can see that this is a question that can be solved very quickly if you understand the sliding window pattern and you see how frequently it's asked and so if you ever run into this problem out in the wild and you know the sliding window pattern you can literally solve this in just within a few minutes and there's so many other problems that are basically just variations of this same pattern so i can see why it's asked because if someone can solve this quickly it does let the interviewer know that they are prepared like they did go through the preparation process and that's a lot of times what they're looking for at these interviews anyway that is lead code number three i hope you enjoyed it and i will see you on the next one
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
605
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question 605 can place flowers we are given one integer array which represents the flowerbed and this integer array can consist of only zeros or ones where one represents the twice um this place is not empty and the flower is already there and zero represents that this place is empty and maybe potentially we can place a new flower there and integer n represents it's like basically it's asking us can we place an amount of flowers giving this flower bed and we need to return boolean whether we can or can it and there's one important rule that the flowers cannot be planted in adjacent ports so if that's the inventory right they're asking us can we place one flower okay let's think this place is already occupied then on this index we can't waste any flowers because like there's another flower on the left side and flowers cannot be planted in adjacent pots however if you go to this index okay everything is fine on the left side everything is fine on the right side it means that like okay we can place it we can place a twist one four over here so we are happy to do it and we just returned true because yes it's possible to point the flower and in case if we cannot do it we need to return false okay let's think about the base case so in which scenario can we return like an answer straight away you can return the answer straight away if n is equal to zero so can we place zero for hours of course we can why not we just return true in this case then let's declare an integer to just keep track like what amount of hours can we actually plant so just call it count and now let's iterate through the whole flowerbed we are iterating right and there's no point to consider the indexes which points to value which is equal to one right so we're only interested in these zeros if flowerbed of index i is equal to zero it means that okay this is the empty phase and potentially we can find the flower there but to make sure if you can't point the forward or not again guys flowers cannot be found in a json port so if you're considering this example again right and we reached the first zero value we need to check the left side and the right side they both should be equal to zero we need to act two extra conditions if the value at index i is equal to zero and the value at index i minus 1 is equal to 0 so the left side and also the value at index i plus 1 so the right side is also equal to 0 in this case yes we can do it we can quantify there so we can increment our counter and also we can check if the count now is equal to n because if you reach this point when the count is equal to n it means that yes we can return true straight away because it means that like we can plant at least n amount of hours so we just return true or if iterating through the whole input array and we will not return true in this case after the forward we can just return false which will mean that no we cannot plant ant amount of hours but elsa think about that imagine that like basically we found the first flower but we need to check the second one right if you can point it with two flowers there's no point to just you know go after that to the next index as we know that like the flowers can be pointed in adjacent ports so there's no point to check the next index we can just jump like on the next index you increment i by one anyway but we will go next iteration of the forward but if you found the place where we can point the flower you can do iphos plus here as well so on the next iteration of the four of you in total do like ipos2 and just will skip the next index and you'll go to just next index right away then this is what we need to do to just you know avoid unnecessary extra steps and extra checks because there's no point to check the next um index once we found that you know we already can 24 hour on the current i index so this should be enough to pass the first example let me run the code and yeah it passes however imagine that i don't know you would have like the following input array which starts with the zero and in this case our program is going to break because you know you will get array index out of bones exception because we'll start our iteration and the first value at index zero is equal to zero and you know we'll try to check the value on the left side but you know there's nothing on the left side because it's just the beginning of the array so we are going to get an exception how can we avoid these cases we definitely want to have an extra check if our bet i is equal to zero and else i at the same time is equal to zero or if this condition applies uh java will not even go to the to do this check and you and will not do i minus one because it's like an or statement in this case our program will not break and you know it successfully will check because if i is equal to zero if we don't check the website we can only just check the right side so and also if we will go to the end of the array we can face like the similar situation with the end of the array it also controls the array index out of one's exception so we can else we should also do the similar thing here if i is equal to flowerbed dot lengths minus one or powered by i plus one is equal to zero blah then everything is good we increment the counter in the m things like that so this is just the extra condition which will allow us to pass the other cases as well okay let me run the code cool let's submit guys perfect guys hundred percent i hope it makes sense thanks for watching guys remember lead code today keeps an employment away so make sure you practice your legal skills challenge your friends to see if they can solve this question or not and guys please in order to support me and my channel please subscribe to my channel i will really appreciate that and i will see you next video guys good luck
Can Place Flowers
can-place-flowers
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` _if_ `n` _new flowers can be planted in the_ `flowerbed` _without violating the no-adjacent-flowers rule and_ `false` _otherwise_. **Example 1:** **Input:** flowerbed = \[1,0,0,0,1\], n = 1 **Output:** true **Example 2:** **Input:** flowerbed = \[1,0,0,0,1\], n = 2 **Output:** false **Constraints:** * `1 <= flowerbed.length <= 2 * 104` * `flowerbed[i]` is `0` or `1`. * There are no two adjacent flowers in `flowerbed`. * `0 <= n <= flowerbed.length`
null
Array,Greedy
Easy
495,735
1,884
hey everybody this is larry this is me doing a bonus question so hit the like button hit the subscribe button hit join me on discord leave a comment whatever you like to do uh it's august 12 2022 here i am doing a random question hopefully is one that is not premium because i have to subscribe to unlock maybe one day i'll just actually subscribe or if you want to sponsor it uh you know then i'll start doing these premium questions eventually but uh let's keep going until we find one that i haven't done that is not premium oh this one uh let's kind of see how this goes um i don't know if this is the one that i was thinking of but i do remember oh this is only 2x because i think when i was younger i do remember seeing a really hard problem that i don't know that i know how to solve where it has mx or something it might not even be just relating to this question but uh but i think this is a brain teaser thing so let's think about this uh anyway this problem is 1884 egg drop with 2x and n4 let's see if this is the problem that i remember uh yeah anyway let's see we're given two identical eggs just some for me okay so the idea i think is okay so i think the way that we can think about the strategy is minimum number the moves right so let's say we can binary search on the number of moves i think that's one way to do it how do we binary search on the number of moves well uh i think that's the tricky part the idea here is using a function to do it but okay let's write the binary search first and then we'll maybe think about it right so left is equal to zero right is equal to n because in the worst case i like bigger n in the worst case and i guess you always have to start with one move but because the idea here is that in the worst case you just you know start at the first four started the second floor dot and then you could find out right um so okay so down here if good of mid let us go to left plus right over two and this good of mid means basically if mid is uh yeah let me actually write it here instead so let's say we have a good function we have some x and this means that we can determine or we can determine all cases where with extra that's basically the idea so if this is good then we want to try a bigger number so that's why we set left until you go to mid else right is equal to mid minus one so in here we do want to okay so that's basically the idea um i'm i really need to publish my binary search video so i will uh skip this a little bit but the idea here and i've done a lot of binary search videos so if you struggle with this one check one of those out um but the idea here is that my left is equal to right um so i'm doing inclusive bounds so if left is equal to right that means that's the answer that's why we turn left um but okay so uh x moves i suppose maybe that's a different okay so then what happens right so with two drops with x moves what can we do well that means that i think this is a tricky one to articulate so that's why i'm thinking about it i think i have it in my head but the idea here is that let's say you have 10 moves for 100 right um then let's say we have 10 total moves then here we check zero to uh well not zero that's one index but one two ten with the first drop right so that's one drop because of th if this breaks then we have nine more moves because it's um because we can determine one two three four five six seven eight nine with nine moves and if it doesn't break that means the tenth one is it anyway right so you can do that and then the second drop is 11 to um you may to 19 because now this is the second move and then on the second move you only have eight more moves right so that's basically the idea and i think we can determine this by figuring out how many force is good here force is equal to zero to interpret but then the first move is basically the first move is um yeah while x is greater than zero maybe i don't know if this is a great while loop but i'm thinking about for a second remember to document i guess um then here we are we do force to do x right because basically yeah i think this just follows this pattern and of course then now you can figure out that this is essentially x um i mean you know we'll do we'll keep this here but you can also think about uh so force is greater than or equal to n um so that's basically the idea let me kind of run it real quickly but okay so i'm really wrong that isn't my implementation because the idea this is just basically that but i don't know why i'm getting a hundred did i get it well so if 100 is good then oh no okay i did say this wrong that's why because if we can determine with mid move then obviously we can do it with more moves so we actually want it to be right is equal to mid and then here we want left is equal to mid plus one because we want more moves um and yeah okay so i said that one wrong yikes okay and of course you can simplify this with a formula because this is just um you know this is the opposite of but if you construct it backwards this is just one plus two plus dot plus x and i'll leave it to you at home to figure out what that formula is um but yeah i'm just gonna give a submit cool um what is the complexity here well this is gonna be binary a binary search so given n things this is going to be linear in the number of bits this one you can actually do with a formula so this is depending how you want to say it's going to be linear in the number of bits because um if you do the formula i guess yeah i guess technically it's n squared the number of bits because there's a x times x in there right um but i don't know however you want to say it um this is yeah but in that case this is going to be o of n squared where n is the number of this number of bits maybe uh or enter the cube depending on how you want to define the things but in terms of this end um this is going to be o of log n plus o of 1 for a constant n so that's going to be it uh well a constant length n in terms of not a constant n but a constant length and uh meaning constant number of bits um yeah that's pretty much all i have um i think so there is a tougher problem where that gets that's a minute yet okay there is a tougher version where you have to try with multiple eggs and in that case it's tougher i don't know that i know how to do it off my head but the idea is that you know if this is two then you have a function that calls this after the third one and then you try to do a binary search on the third one um instead right and the fourth egg as well etc but how you choose those binary search is basically you get x binary searches and then you start from that number and then you kind of do it that way um i think that's the idea anyway uh i don't i might have to do some proofs but that's not this form so maybe i'll do in the future anyway that's all i have for a bonus question let me know what you think stay good stay healthy to good mental health i'll see y'all later and take care bye-bye
Egg Drop With 2 Eggs and N Floors
minimum-changes-to-make-alternating-binary-string
You are given **two identical** eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. In each move, you may take an **unbroken** egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** We can drop the first egg from floor 1 and the second egg from floor 2. If the first egg breaks, we know that f = 0. If the second egg breaks but the first egg didn't, we know that f = 1. Otherwise, if both eggs survive, we know that f = 2. **Example 2:** **Input:** n = 100 **Output:** 14 **Explanation:** One optimal strategy is: - Drop the 1st egg at floor 9. If it breaks, we know f is between 0 and 8. Drop the 2nd egg starting from floor 1 and going up one at a time to find f within 8 more drops. Total drops is 1 + 8 = 9. - If the 1st egg does not break, drop the 1st egg again at floor 22. If it breaks, we know f is between 9 and 21. Drop the 2nd egg starting from floor 10 and going up one at a time to find f within 12 more drops. Total drops is 2 + 12 = 14. - If the 1st egg does not break again, follow a similar process dropping the 1st egg from floors 34, 45, 55, 64, 72, 79, 85, 90, 94, 97, 99, and 100. Regardless of the outcome, it takes at most 14 drops to determine f. **Constraints:** * `1 <= n <= 1000`
Think about how the final string will look like. It will either start with a '0' and be like '010101010..' or with a '1' and be like '10101010..' Try both ways, and check for each way, the number of changes needed to reach it from the given string. The answer is the minimum of both ways.
String
Easy
null
331
welcome to august seleco challenge today's problem is verify pre-order today's problem is verify pre-order today's problem is verify pre-order serialization of a binary tree one way to serialize a binary tree is to use pre-order traversal prior traversals use pre-order traversal prior traversals use pre-order traversal prior traversals can be the root left right when we encounter a non-null node we when we encounter a non-null node we when we encounter a non-null node we record the node's value if it is a null node we record it using a sentinel value such as this hash symbol so for example the above binary tree can be serialized to the string 934 hash one hash two hash six hash where hash represents a null node now given a string of comma separated values pre-order return true if it is indeed a pre-order return true if it is indeed a pre-order return true if it is indeed a correct pre-order traversal correct pre-order traversal correct pre-order traversal serialization of a binary tree so it's guaranteed that each comma separated value is either going to be an integer or the character hash representing the null pointer and you may assume that the input format is always valid so we're never going to have like a 1 empty string three or something like that so note you are not allowed to reconstruct the tree which is unfortunate but honestly it's not like even if we could do that this would be a lot easier all right so what are some key insights here the first thing is to note that whenever we see two null nodes uh coming after a number that kind of marks a leaf node right like this four here is going to be a leaf node it's got no more nodes below it so that's kind of one key inside so if that's the case there should never be a situation where there's three null nodes in a row like we can't have four no that makes no sense right uh so that's one key insight if we see that there's two hashes at any point we can keep track of the values that we've seen inside some sort of stack and we see that we've seen two uh hash symbols here that means there's two null nodes right so what we can do is pop off this number here to mark that this has been accounted for as a leaf node so say that we pop off four from our stack and then we come to one right and we see one is also a leaf node so we pop that off now at this point we'll have three four and we i'm sorry nine three and four hash and one hashtag are popped off right but there's really nowhere to go from there like we need to figure out if this notes also been accounted for and so what we can do then is whenever we find a leaf node here like four hash we'll pop off these three values for hash but we'll also add back a hash value and what that does is basically says this has been accounted for and we can mark that with a hash one and it's almost like this is a null here so at this point there'll be a hash and we'll pop off one and then also be another hash so then we can just have a while loop to say hey could we also knock this one off because at this point we should have three hash and that will get popped off and we'll continue on this algorithm at the very end if this is a valid binary tree we should only have one symbol left marking a null so that's the thing like if we have two hash symbols there should be a number that's paired with that if we ever have a situation where we have multiple hashes without a number that means it's invalid okay all right so let's begin what we'll do is first create a stack and we'll say four and in keep in mind this is a string so what we'll do is we'll split it by the comma values and first we'll append it to the stack right oops so in our while loop we have to first make sure that there's indeed three values here so if the stack is greater than length two and the last two values in our stack if it equals what hash times two like this that means that we should have found it a leaf node and we also need to make sure that stack negative three here is not equal to a hash symbol so this is the case then let's pop off our stack uh we gotta pop off three times right we gotta pop off hash and then the number itself but we want to add back then another hash symbol to mark that this node's been accounted for and it's almost like it's a null so at the very end after this loop we should if this is valid see that this is equal to just a single hash here okay so let's make sure this works okay it looks like it's working so submit it and there we go accepted so time complexity is going to be old n space complexity should be the same uh and that's really it there's definitely some other approaches you could take you could even you know simulate building this tree but i think this is probably good enough and it wouldn't be any faster doing it that way anyway so okay thanks for watching my channel remember do not trust me i know nothing
Verify Preorder Serialization of a Binary Tree
verify-preorder-serialization-of-a-binary-tree
One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`. For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node. Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree. It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer. You may assume that the input format is always valid. * For example, it could never contain two consecutive commas, such as `"1,,3 "`. **Note:** You are not allowed to reconstruct the tree. **Example 1:** **Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#" **Output:** true **Example 2:** **Input:** preorder = "1,#" **Output:** false **Example 3:** **Input:** preorder = "9,#,#,1" **Output:** false **Constraints:** * `1 <= preorder.length <= 104` * `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`.
null
String,Stack,Tree,Binary Tree
Medium
null
1,171
hi let's solve today's daily challenge that is remove Zero Sum consecutive notes from link list so first let's understand what the question is so in this question you given the head of a link list and you need to repeatedly delete consecutive sequences of nodes that sum to zero until there are no such sequences all right so let us understand using the example so this is the first example given to us now this is the head node all right okay now what we are being given is this head and we have to remove all the sequences which sum up to zero okay so here inside of this link list I can see that this part right if I sum it up what value am I going to get zero right 1 + 2 which is 3 plus - 3 zero right 1 + 2 which is 3 plus - 3 zero right 1 + 2 which is 3 plus - 3 which is 0er so I have to remove this part and return the rest of the link list apart from this there is no other part see after you have removed this you cannot consider this as a sequence right because this part is already removed you'll be left with 31 and inside of 31 you have to find the sequence so if it is not present let simply return the link list so that is what's happening here so you have to Simply return this link list which is remaining just three and one and this so this should be your answer okay let us look at another example right so here again this is my head node and here if I go and see which nodes or sequence of node is giving me zero sum so I can clearly see it's that this part right 3 and minus 3 which is going to give me zero sum so I have to remove this part and I have to return the rest of the link list so rest of the link list is what 1 2 4 and N9 right so this is what I have to do all right so I hope you understood what the question is now how to solve this question right so first thing is you can definitely solve it using the bigo of n Square approach so in this approach what you're going to do is you're going to iterate in the link list twice right and for each and every node you're going to iterate in the link list and keep checking for these sequences and remove if there are any such sequences right and after that you will definitely get an answer but can we reduce this time complexity right so yes we can and we can bring down it to Big of n how is that right so let us look at the intuition for that okay so the only thing that matters in this question for you is to know what prefix sum is all right so we are going to Leverage The Power of prefix sum all right so what is prefix sum so let us say we are given an array right let say we given an array let me take these values 1 2 3 - 3 and 4 we are given values 1 2 3 - 3 and 4 we are given values 1 2 3 - 3 and 4 we are given these values so the prefix sum array looks something like this so you keep adding the values right so each and every element of this prefix some array denotes up to that index what is the sum in the array right so this is 0 1 2 3 4 these are the indexes that I've mentioned now up to zero index if I go inside the AR what is the sum it's one up to one index what is the sum 1 + 2 3 up to one index what is the sum 1 + 2 3 up to one index what is the sum 1 + 2 3 up to two index what is the sum 1 + 2 + up to two index what is the sum 1 + 2 + up to two index what is the sum 1 + 2 + 3 which is six now up to third index what is the sum right 6 minus 3 so you will get uh three in this case right and then up to Fourth index what is the sum it's going to be seven so this is what the prefix sum array is now how are we going to leverage the use of this prefix sum see okay so here you can notice one thing that three and three have appeared twice which basically means here right here sorry after this right I added something which made my sum become equal again right so I'm adding something to three right I'm adding something to three something we can write and its value is three so this something has to be zero right which simply denotes that this particular part right this particular part that we have added is a zero sum sequence right which you can see from here also if you add three and minus 3 what you get zero so the sum here is zero so that is why we are getting the sum right this particular sum so we had to add something to it right so what is that we added zero so that means that I can use this prefix sum and keep tracking duplicate values right so if there are no D duplicate values well and good but as soon as I get a value which has been already present I can know that okay there was a zero sum sequence that was being added and that is why my prefix sum value is same right I got the same prefix some value right so you can see from this example that you have two 3 - 3 so up to two the sum was three 3 - 3 so up to two the sum was three 3 - 3 so up to two the sum was three correct and here the sum became six and here the sum became three so basically from this three sum right from this three sum you have to skip these two notes up to this node and you have to make it point to the next node so basically if somehow you can get this node right with this with the same sum that you're getting here right you can es skip the this part of the sequence right or of the link list so I hope up till here everything is clear you right why we are going to use prefix some and like what is the intuition behind using prefix some right it's the it's this only that whenever you have a sum if it get gets repeated then you know the sum has already been present and we had to add some value which is zero right so that particular sequence is giving us zero value all right so as I said we will have to keep tracking these values right that at what node what was the sum basically kind of like that so instead of an array we are going to use a map right so inside of our map what are we going to store first of all this prefix sum value right we need the prefix sum and along with it for that sum what was the node right so like three sum I got at this node right let me show you here okay so all right let me remove this part let me draw this again so you have this Node 1 2 3 - 3 and 4 so what you're Node 1 2 3 - 3 and 4 so what you're Node 1 2 3 - 3 and 4 so what you're going to do is you're going to make a map now let's say its address is a b c d e so inside of your map you're going to store the address of the node up to which you are getting that prefix sum okay so here you're going to store the node so this map you will create all right so let's start doing it right so initially it will be zero right our answer will be zero okay like our sum prefix sum value will be zero now we'll start calculating so here my sum will become one so at what note I am getting this prefix sum one so I am getting so inside of my map right map M of one is going to be what a all right keep moving add two to your sum right so this is your sum value now here your sum value will become three so add it to your map so it will get it will become B right up to this prefix sum the value is B okay move ahead and add the next value which is giving you s is equal to 6 so for this sum value six add that particular node up to which you are getting this value then d right so D node will give you a sum of three so add it in your map right so now okay wait you will not add values right that are already existing that means I have got a duplicate value s is equal to 3 it's already present inside of my map so you have to keep checking if this value is occurring in inside of the map if it is occurring so you have to perform some deletion if it is not then you have to Simply move ahead so we will remove this now what I have to do I have to take that node where the sum was three previously right here is also three but we have to take that node where the sum was three so which was B right so this is the use of the map right that is why we are using map so from MP of 3 I can directly get this B right so of B right I have to delete this particular sequence so I have to make B's next pointer point to the next pointer of your current node right so current node is D so you have to basically make whatever pointer you are having here so basically here you are making B of next equal to what D of next D was your current node right so this is how you have to like keep doing keep adding these values and keep checking if this value exists then you have to per uh like perform this deletion all right let us do a dry run quickly on another example right so here is the third example okay before I explain you the third example I have to also explain you that see if we see the first example right so we can see that there is a possibility where your head node will also be deleted your head will become a new node right so for that we can simply fix it using a dummy node so I will take a dummy and also here you can see that if you will you know uh try to add values inside the map here it will be one here it will be three here it will become zero so from where are you getting going to get zero see whenever your head has to be deleted right you will definitely get a some value zero right from your head if there is a sequence which has to be deleted then you will definitely get a sum value zero so you have to also hash it in your map and at this particular zero you have to place this dummy node right so this way you will be able to handle uh this condition also so right and in the last you know that you can always return dummy off next right and this basically makes the uh job easier right we are able to handle these H cases efficiently all right so we're going to take dummy node and then we are going to create the map and please do not forget this because in case there is a head right um there is a sequence in which the um sequence starts with the head node right there you are going to get zero some right and that should be present inside of your map uh but if you keep doing it like this it will not be right so include these two right so declare a d node and also declare MP of Z as tummy all right now let us go ahead and see the third test case Okay so this is the case now let me start doing a dry run so as I said first take a dummy node make it point to your head right this is your head now after you are done with that also hash your map of zero value as this dummy node right so let me say this is dummy okay so your map of zero is going to take dummy all right now start iterating inside of the link list so sum initially will be zero here your sum will become what one so hash it in your map right so map of one right the sum will be a then do it for B so 1 + 3 is 4 so this value do it for B so 1 + 3 is 4 so this value do it for B so 1 + 3 is 4 so this value is not you have to only add if the value is not existing correct so MP of 4 will become B then come here your sum is now six so it's not present so hash it so what will you do c you will add right here 6 - 3 you will do so sum will right here 6 - 3 you will do so sum will right here 6 - 3 you will do so sum will become here three so this is also not present so put it inside of your map and put the node now at e now see here your sum is becoming one and one is already present here inside of your map so what you have to do now you have to you know that this is that sequence right which is of Zero Sum and you have to remove it right so what you will do you will remove this particular part so how will you remove this particular part get the node from here map of this prefix some value that you're getting again get this value and make its next point to F all right okay now let us continue our iterations so you have some value as one here so some value will become six here okay now this six is already existing here right but don't you think it will give you wrong answer because see you don't have to delete this right because you are considering this not part of your link list so you have to remove all these values from your map also so what you have to do is as soon as you get this node right so you have to start from this node and again calculate the prefix sum right with one calculate the prefix sum with up to b c d and e and remove these sums from the map so you have to use MP do arrays and remove this from your map and this is because you can see that the sums can repeat but this should actually be uh should be put inside of your map correct but because of this s is equal to 6 which is a part of your deleted sequence you are checking this and you will again you know try to delete up to this part right so which will give you wrong answer isn't it so you have to keep in mind this also that you have to erase the values of the deleted sums from the map all right now okay so s is equal to 6 so basically if I have to delete all these so I will be removing all these values from the map so I'll be left with this now if I'm left with this then I have to harh this six value and it will be what now it will be F correct then move ahead add next value s is equal to 11 so now map of 11 is going to contain G all right now here is okay it became equal to 6 because 11 - 5 is 6 it's already present because 11 - 5 is 6 it's already present because 11 - 5 is 6 it's already present inside of the map so you know you have to delete this sequence what is the sequence that you have to delete so you have to get MP of six which is f right so after F all these values right up to this is your current node correct so you have to delete these values so as soon as you delete these values you have to make its pointer point to this particular node correct so now you can see um yeah all right now let us keep moving ahead also as I said you have to remove these values from your map right so it is repeating but you have to remove this 11 from your map so you will remove this 11 from your map and keep doing the iteration then you will be having map of 6 + 1 that is 7 is equal having map of 6 + 1 that is 7 is equal having map of 6 + 1 that is 7 is equal to I and then you will reach null so basically you have completed the iteration and here you have to Simply return see the remaining link list is now this right you can also see your pointers pointing like this right because we are doing that now after this you will be having your dummy node here correct your dummy is present here so you will simply return dummy off next so I hope the approach is completely clear right okay so now let us look at the time complexity before we see the code right quickly so time complexity you can already see here is we are only iterating the link list once right so it will be big of n there is only one iteration uh sorry there is only one part of the whole link list then your space complexity is going to be because of the map and in the worst case it can be up to Big of n right so I hope this time complex and space complexity are also clear to you now let us go ahead and quickly see the code right okay see so the first thing I did is decare the tummy node after declaring the dummy node I am getting the dummy next Das head right so I'm uh attaching this dummy to your link list and before head after that I'm taking this sum right so the sum denotes the variable in which we will be calculate calculating the prefix sum right then we are declaring the map inside of this map as I showed you what we are storing the prefix sum value and we are storing the node up to which that uh that's this particular int value was your perfix sum right then uh I already told you that in cases where you have to delete right from the head node right if the sequence includes the head node also then for that sequence you're going to get zero sum right so you have to Hash it also and make it equal to dummy so that the deletion will be much easier all right now start iterating and I'm taking the head and up to head is does not become null right we are iterating calculate the sum now do the main thing here right check if this sum already exists inside of the map right if it doesn't you have to Simply add it but if it exist what you have to do you have to perform deletion correct so you could have done this right you could have directly made like get this particular node from the map and directly make its next point to your current nodes next but as we saw that we have to delete these prefix some values right because they can appear again right but that will give you the wrong answer right so you have to remove these values from the map right so for that reason we'll have to iterate in this particular sequence again all right so basically you will take this node right so MP of some basically denotes the node where that prefix sum was already existing right and we also taking the start node right so basically start is the start of the sequence right and node simply is going to iterate in the sequence okay so start your traversal and make it equal to next and keep calculating the prefix sum so here what we are doing is we are taking okay up to here the sum was what one so keep adding this node so sum becomes four erase it from the map right erase it from the map then okay 4 + 2 6 erase it from the map then okay 4 + 2 6 erase it from the map then okay 4 + 2 6 erase it from the map then 6 + - 3 erase it from the map then 6 + - 3 erase it from the map then 6 + - 3 erase it from the map then 3 + - 2 1 right so one from the map then 3 + - 2 1 right so one from the map then 3 + - 2 1 right so one um obviously we don't have to go up to one right so that is why we have added this condition please don't remove this particular one value from your um uh sorry the map right okay so this is what you're doing so you're doing up you do not reach the head only then you have to remove okay after this you have to Simply make your start of next point to your head of next okay um okay I have added it at the wrong place you have to basically add it here after the while loop all right so after your while loop is done you have to Simply make your start of next point to head of next because now you have removed the values from the map and yeah so we have basically done what whatever we had to do correct now uh you can simply see that here we are iterating and simply return dummy off next so this is how you have to like solve this question and this is how you Leverage The Power of prefix
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
hey guys welcome back to helper function in this video we will discuss a question power of two so the problem is pretty straightforward given an integer write a function to determine if it is a power of two or not so we just need to return true if the number is power of two otherwise false so for the numbers like 1 2 and 64 as they can be represented as 2 to the power 0 2 to the power 1 and 2 to the power 6 respectively we will return true and for the numbers like 0 13 62 they are not a power of 2 so we will return false so let's see how we will solve this now the most basic approaches to check for all power of two's will take a integer and initialize it to 1 and will keep multiplying it with 2 until it becomes greater than n meanwhile every time we multiply it with 2 we will compare it with n now if they are equal it means that it is a power of 2 and we will return true otherwise the number will become greater than M and the loop will terminate and we will return false so here is the code for that we declared a long length answer and initialize it to 1 we have taken long end to avoid overflows now this while loop will work until answer is lesser than equals to n so every time in a loop if my answer is equals to n we will return true and also every time answer gets multiplied by 2 now if answer becomes greater than n we will come out of this loop and will return false which means that the number is not a power of 2 this approach works fine but we have another approaches which can give the solution without using loops one observation is that if a number is a power of 2 then the number of set bits in its binary form will be 1 now set bits are the bits with value 1 this is because in the binary form every bit is represented as a power of 2 so for a number to be a power of two the number of set bits should only be one so the solution to our problem would be to count the number of set bits in n and if it is one then return true otherwise return false now there can be different methods to find the set bits but C++ has methods to find the set bits but C++ has methods to find the set bits but C++ has a predefined function called built-in a predefined function called built-in a predefined function called built-in pop count which returns the count of set bits of a number so if this function returns 1 this means that the number of set bits in n is 1 and hence we will return true and otherwise we will return false now note that and greater than zero is the primary condition for checking the power of two as a number lesser than or equals to zero can never be a power of two now another observation is that for n the number of set bit is 1 but if we look at n minus 1 we will see that all the lower bits are 1 and the big that is 1 in n will be 0 in n minus 1 thus doing a bitwise and operation between n and n minus 1 we will get 0 because an operation gives said bit only when both the bits are set but here in the figure we can see that no bits are set for both n and n minus 1 thus if a number is power of 2 then the bitwise and between N and n minus 1 is 0 and here's the code for that if n is greater than 0 and bitwise and between N and n minus 1 is also 0 then we will return true otherwise we return false so the time complexity for this problem is order of number of bits which is very small and very between 0 to 32 for 800 2 bit in diesel and the space complexity is constant as we are using no extra space so these were the different ways how we can approach this problem if you like this video then do like share and subscribe to the channel thank you for watching you
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
1,200
Hey guys, don't increase them by 1 and in this video I'm going to explain to you how to solve the problem one thousand and two hundred of the cold the minimum program absolut flex what this problem will want you to provide it will want you to build a method in which this method will receive a vector of integers and you must return a vector of integer vectors and how are you going to construct this vector of vectors in god basically the vector of integer vectors you will construct is a vector of installments so instead of a vector of vectors you can see that as being a paris vector of elements and how are you going to construct these pairs of elements basically what he wants here are the payments that have the smallest possible difference so we can find out what the smallest difference is between two elements a The idea would be to go through all the possible steps, but if we analyze the size of the vector here, we will see that the size of the vector goes up to 10, thus raising us to go through all the possible pairs, we will need to perform at least this amount of armaments squared to get a table in the corner that would give 10 to the power of 10 in the very large number of comparisons so we can make a slightly faster strategy that we could be using would be to order this vector and compare only the consecutive elements because if we analyze we always compare consecutive elements in an ordered form, we will always be comparing the element with the one closest to it and this way we can get it with a smaller difference much faster than going through all the possible steps so the first thing we what will do is take the smallest difference to get the smallest difference we will initially coordinate the vector that we received to sort the vector we can use the luck function from the algoritmi library we don't need it we are including libraries they are low use the luck function to store we have to provide two memory positions, the position at the beginning we can do using the begin method of the vector and the end position we can use an and method of the vector then we order the vector we want to analyze all consecutive elements taking what is the smallest difference so I'm going to put a new integer called smallest taking the difference of the first two elements a is 1 - a r 10 and analyze elements a is 1 - a r 10 and analyze elements a is 1 - a r 10 and analyze all the other elements so let's do whatever starting parliament two going up to final while it was smaller than a is oe is increasing and always vote by comparing the difference - a and minus ones this the difference - a and minus ones this the difference - a and minus ones this difference was smaller than the difference that I'm saying is smaller I'm going to replace it is the smaller one will receive less now that we have the smallest difference what we will want is to build my answer is nothing more than a vector of installments so I will start with an empty veto director environment call that gives an answer and I will always use an auxiliary vector of two elements we are building his answer and adding my answer to the vector of imt chamma and tempe and already placing two of his elements using the vector constructor in dia' unfreezing vector constructor in dia' unfreezing vector constructor in dia' unfreezing we will have to see everyone get all the pairs below we go through the entire vector again this time I will have to go from index 1 to get all the consecutive pairs while this was smaller than a and punctual the iran if by any chance the difference between a this is and minus right and minus ones this difference was equal to the smaller difference means that I will have to add to these guys in my answer is to assign the temp with the larger of the two elements which in this case is and in front because we ordered the use of the default nation that it will order from crescent form so the largest lament goes to position is the smallest element of them two goes to position 10 and minus one so I take these two elements here make our pa and I will add s pa in my view tom response to west beck's response kemp and after that we are just returning this response vector a rectangle response let's test this code hum code in this case it worked let's test another case copy/paste wool leather in the second case it also worked, the case it provides with is happening. we, the holding company, which also worked, now we are going to submit it to the school, just wait to judge, it is playing in our solution, it was accepted, it was a very quick solution, it scored 93 points, 93% of users who use c++ points, 93% of users who use c++ points, 93% of users who use c++ and used the smallest amount of auxiliary memory possible within of the user to be more, I believe that we could try to increase here to make our algorithm even faster if we use some form of quick reading that people usually use to increase the speed here of codes in milk code guys, I hope you have liked what is the vision comment see you next time thanks
Minimum Absolute Difference
remove-interval
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are from `arr` * `a < b` * `b - a` equals to the minimum absolute difference of any two elements in `arr` **Example 1:** **Input:** arr = \[4,2,1,3\] **Output:** \[\[1,2\],\[2,3\],\[3,4\]\] **Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. **Example 2:** **Input:** arr = \[1,3,6,10,15\] **Output:** \[\[1,3\]\] **Example 3:** **Input:** arr = \[3,8,-10,23,19,-4,-14,27\] **Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\] **Constraints:** * `2 <= arr.length <= 105` * `-106 <= arr[i] <= 106`
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
Array
Medium
null
127
hi guys over here to increase our today's question is word ladder given two words begin word and end word and a dictionary is word list find the length of shortest transformation sequence from begin word to n-word such that only one begin word to n-word such that only one begin word to n-word such that only one letter can be changed at a time each transformed word must exist in the word list note that begin word is not a transformed word note return 0 if there is no such transformation sequence all words have the same length all words contain only lowercase alphabetic characters you may assume no duplicates in the word list you may begin you assume begin word and Edward are non empty and are not the same okay so it has covered a lot of these conditions for us so we don't need to really bother about those so for example the begin word is hit and the n-word is fog and word is hit and the n-word is fog and word is hit and the n-word is fog and the word list is given as such we need to find the length of the shortest transformation sequence in which we can convert hit into fog but the condition is that we can only change one character of the word at a time and that character that we have chained in the word that we get after changing the character should be in the word list right and we need to return the shortest such transformation sequence so for example here these are the given list of words right so we convert hit to hot and just transforming I into oh right okay and then hot to dot so just H is being replaced by D then dot to dog then just T is replaced by G and then dog to cog and then we have our end word which is coke right so the answer that we have to return is five okay another example is hit cog but now the list is different and there is no way of transforming this hit to cog because if the given words here so we probably return zero all right okay so our input is an array and unsolder array and let's have a look at the way this approaches we can take so pause the video think for a moment and come back okay so this question has a lot of components to it and that's why understanding which approach to take is not very straightforward however there is a slight hint of us trying to use a collection and just you know trying to traverse the array in a way that we are able to find that transformation sequence right so in questions like these guys it's always important to understand that if you have seen this question for the first time in the interview right preparing for your interviews by doing a lot of questions will definitely help you in suggesting good approaches right which might be impressive to the interviewer but you cannot guarantee of being able to derive the solution right or the best possible solution in the interview right so don't be intimidated by the thought that how would I think of such an approach in the interview these questions not only help you understand the solution for this question but they also help you develop and approach right so there might be similar questions out there and were after solving this you will know that okay there is this way of solving this question and you will be able to apply that so that's why practicing data structure problems is extremely essential because you have to understand the question and the underlying concept that we are using in the solution and that is what helps you cover a lot of similar questions and that's why we focus in our videos on the approach to solving rather than just the question at hand right so um alright so we will be taking this approach we'll be using a collection okay we'll be traversing through the list of words and that is how we will be solving it and I hope the solution will get clear as we develop it so the idea behind it would be that we want to compare the work the word at hand with the other words in the array right in the word list and the dictionary and see if it is adjacent means just one character away right so we replace one character and we get that word right once we have got that word we don't want to come back to that word again for this from this at least from this word right so what we do is we remove it from that list okay and we want to put this word which we have just transformed into something so we put that into a queue okay then we pull the word from the queue and we find its next adjacent word right so in this process there will be words that will not be etched adjacent and we'll just ignore them and move on to the next word and we might also reach dead ends where we don't find any adjacent words and that's what that is when we get to know that okay there's no transformation sequence possible for this right so yeah that is roughly on a very high level the approach let's start developing and it will get better okay so first of all what we need to do here is that if the length of the begin word or the N word or the word list if either of these is 0 then our answer is 0 correct so that's a base check that we just have to make it's always good to make such base checks because that gives the interviewer and impression that you do have you're thinking beyond the question you're thinking for every aspect of the question in trying to cover a lot of base cases as well and that definitely is a desirable quality to have in any candidate so yeah okay so in any of these cases we just have to return what zero good so now we have to find the length of the transformation sequence right so whenever we are traveling from one word to the other we are adding one more to the sequence still here right because we have added one more word in this sequence we want to maintain that length as well and that's why we need a structure that stores this string right and also the length of the transformation sequence we have used till to get to this word okay and to represent that we will create another class let's call it just this okay and it has the string okay which is the word and it has an integer called length just let's keep at this and we just need a constructor okay so word equals two would okay and this okay good now what we do is that I will say as I was saying we will keep a queue okay so we need a queue of type objects right and they just go like this LITTLEST is the implementation of queue in Java so yeah you might want to keep that in mind okay and to the queue we will add the begin world because it's not part of the dictionary right so we just want to add that because we want to start from that so we just add the begin work to it okay yeah but we have to create an object out of the first this and it's just one okay yeah okay fine now we want to keep traversing till the queue has something right it's not empty because it means that we have something to consider which might give us the end work right so that's what we do and as it was saying we just pull out the current word that is at the peak of the queue so we'll just do a Q dot okay we just get the first element that is at the top of the queue okay now the front of the queue so we have the current word now which is represented by an object and now we want to find the next element that we can use right so what we'll do is that we have to compare this with every other word in the word list and see if we are able to find a word that is adjacent to this word okay so what we do is that we just so we can create another method called is adjacent and we will give it the word of current right and now for all the other words so we need to either it through this word list and we will be using a list idolater here the reason is that when we find a word that is adjacent to this current word you want to remove it from the list and if we just iterate through it simply using a for we cannot remove it while we are trying why we are traversing through it right whereas using a list idolater we can do that so this question not only teaches you how you can encapsulate information into an object but also teaches you where to use what constructs of Java to tackle your problems better right so what we do here is we'll create a list I diretor iterator of type spring okay and let's call it IDR equals to word list dot list iterator okay fine so now just like any hydrator we'll say it's next so why it has more elements okay put this here right and let's first get the word so this is just a string so let's call it 10 and ID r dot next so we get the word right and then we give them okay so we'll get to what we need to do but let's first implement is adjacent method so this method of ours is a very simple one it will return a civilian value yes or no if there are JSON or not okay and we'll just get two strings s1 and s2 right and we know that by the question that all the words are of the same length right so we don't have to worry about one string being shorter or longer what we just have to do is that yeah we just have to create this for Trevor still any of the two strings Lin okay and compare the character at I okay so if the character add I in s 1 is not equal to the character at I in s 2 we are okay with it being not the same once ok just once because that will be adjacent right if it's not then we have to have a count which we'll just declare here goes to 0 okay and we increment the count right now we check that if our count is more than 1 okay it means that I've been more than one characters which are not same in the string we just straight away return false now once this is done just to just in order to be careful about the last one so we'll just return found more than 1 return false else return true okay so this is the implementation of is adjacent now here if we find that this is a jason what we have to do is that first of all remove this from the word list okay because we have we are going to be consuming right so we just remove that and then we have to create another object right so or we can just directly Q dot add new object and we give em as the word and whatever was the lens for current we are adding one more to it so one do it we add one to it right and we check that if M is equal to okay that's a string so it equals if this word is equal to the N word right then we have what we needed to get through right so we just return current dot length last okay because we have arrived at the N word we don't want to deal with the Q anymore we don't want to find anything else we are where we wanted to reach so that's the end of the story otherwise we just keep going and if through this whole while there was no such instant where we could have returned something it means we have not found anything right so that because that's also a valid case in that case we have to return 0 okay fine let's see if this works so you got that okay we named it just a lien okay let's submit it great it works okay so mm time complexity so the time complexity for the solution is o of n square multiplied by K where K is the length of the largest string in the given word list that's because we are traversing so first of all we are traversing through all the strings in the given word list using the Q and then for every string we are also traversing through the whole list iterator and then we are comparing that string with all the lists now all these strings in the list so that multiplied by the largest or longest string in the word list so that gives us an of n square into K time complexity and the space complexity is o of n because we are using a queue to store this exact same elements again in the queue so I think it should be O of n so I hope you learn a lot of aspects not just to solve this question but also in general problem solving from this question if you do please like share and subscribe and keep coding and take care guys you
Word Ladder
word-ladder
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._ **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** 5 **Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long. **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** 0 **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 10` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 5000` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**.
null
Hash Table,String,Breadth-First Search
Hard
126,433
1,460
and today we will be solving a new lead code question that is make two strings for image two arrays equal by reversing summaries so let's read out the question what the question I'm asking from us you are given two integers arrays of equal length Target and error in one step you can select any non empty summary of ARR and reverse it okay you are allowed to make any number of steps return true if you can make space equal to Target or false otherwise so we can this is the eating here we can make n number of steps to make it uh equal to this thing here so what I will be doing here I will explain it to you what will be my Approach here so let me before that let me explain it to you what actually they are asking us to return true if each individual element in this array is equal to this these elements in an array so if they are equal then you should return true as we have written false so that would be my Approach here uh like I will be telling you what would be my Approach and just before starting the question guys please go update to the channel and hit the like button press the Bell icon button and bookmark the playlist so let's start solving this question my Approach would be first of all I will be sorting this array so when I will be sorting this array let me explain to you what I will be get when I will be sorting both of this array so after sorting I will be uh getting what I will be getting uh Target is equals to what one two three and four in the example number one and Target and ARR would be again one two three four so if you see that when we will be sorting this array see if we sort this array we will be getting it in ascending order here we will all be getting a spending order again due to the Sorting yesterday we can check that both these elements in this and this Target and AR both are equal so then I will be when we will arrange this in the these array in ascending order I will be then converting them into string so when they are converted into Stringer it will be one two three four and this will also be one two three four then I can compare the value and get the answer if they are not equal I will return false if they are equal I will return true so let's do it here so let's target dot sort and error dot sort okay now when I have sorted this array I will be saying return Str AP Stargate Target s t is equals to strx FR underscore now let's see what we are getting here so you see that even by my uh checking for multiple test cases already we are getting the answer so this was all in the it was quite simple and straightforward just we took to apply allow it by sorting the array so I hope you have understood the concept I have just used two things here which I used to sort here and I put the logic that is they are in ascending order then uh I just have to convert this to array into string format then I will be converting these between this stream for format so this should come in equal form if it they are not is equal then I will return false as we as it could be Pro so this is all we have done here thank you guys for watching the video if you have any doubt please guys in the comment section and see you next time
Make Two Arrays Equal by Reversing Subarrays
number-of-substrings-containing-all-three-characters
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\] **Output:** true **Explanation:** You can follow the next steps to convert arr to target: 1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\] 2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\] 3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\] There are multiple ways to convert arr to target, this is not the only way to do so. **Example 2:** **Input:** target = \[7\], arr = \[7\] **Output:** true **Explanation:** arr is equal to target without any reverses. **Example 3:** **Input:** target = \[3,7,9\], arr = \[3,7,11\] **Output:** false **Explanation:** arr does not have value 9 and it can never be converted to target. **Constraints:** * `target.length == arr.length` * `1 <= target.length <= 1000` * `1 <= target[i] <= 1000` * `1 <= arr[i] <= 1000`
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Hash Table,String,Sliding Window
Medium
2187
1,029
hey everyone welcome back and let's write some more neat code today so today let's solve the problem to city scheduling so a company is planning to interview two times n people and we're given an array costs which they don't really mention here but at the bottom of the description they say that the length of costs is two times n and each value in costs is actually a pair so a cost and b cost a cost represents the cost of flying the i th person to city a b cost similarly represents the cost to fly them to city b now we want to return the minimum cost to fly every person to a city such that n people arrive at each city so when you see minimum cost the first thing you might think of even looking at an example is okay let's choose the minimum 10 of the two values 10 is the minimum let's choose the minimum again 30. let's choose the minimum again 50 and choose the minimum again which is 20. and the first example is a little bit misleading because you can just take the minimum of each pair and get the solution because notice how two people these two people went to city a and these two people went to city b but it didn't necessarily have to be the case it could have been that this is a 200 rather than 20 and then we would have chose this as the minimum and in that case we would have gotten three people going to city a and one person going to city b which is not what we want to minimize the cost but we want half of the people to go to city a and have to go to city b so knowing that the problem isn't that simple we can try a brute force approach and by that i mean we can go through every single possibility where half of the people go to city a and half go to city b and of all of those possibilities we can choose the one that had the minimum cost the downside is that this is not going to be very efficient this is kind of what that decision tree would look like notice how the first choice is between 10 and 20 and remember each pair pretty much represents a person so we're basically saying this person can either go to city a for a cost of 10 or they can go to a city b for a cost of 20. and then next up we'd have pretty much the same choice on both sides of the tree but they're technically different results because we chose for that person to you know branch two different ways and so you can kind of see that we're going to keep branching two times so overall the size of the tree is going to be 2 to the power of n where n is the size of the input but remember in the context of this problem the size of the input is actually 2n so it's kind of confusing i mean i guess you could say this is 2 to the power of 2n but either way this is not very efficient is what i'm getting at now you can actually optimize this with caching which is you know a dynamic programming technique to make it much more efficient and let me talk a little bit of why we could do that suppose we just had a function you know whatever recursive function we're doing to do this backtracking i just call it dfs just because it's short now the main parameters we would want to pass into this dfs are going to be i which is the index that we're at and we're also going to pass in a couple of important variables a count and b count which are representing the counts of people going to city a and counts of people going to city b of course we're also going to maintain whatever the total cost happens to be but that's not going to be as important and if you did do it this way recursively you could cache it based on these two variables alone i'll go into detail a little bit why suppose we took uh this branch so we put one person in city b and then we took this branch and we put one person in city a we have two more values in our array so we need at least one more person going to city a and one more person going to city b now from here we're going to recursively call this function again with these parameters now but also notice if we took this path we put one person in city a and then we put one person over here in city b then recursively we would call this exact same function with the same variables for these at least because we still need one person to go to city a and one person to go to city b so using this idea we would do caching which we can do with two variables and that will lead us to a solution of n squared complexity you don't have to do it recursively after implementing it recursively it's usually easier to get the true dynamic programming solution which will also be n squared this is a valid solution i think it does pass on leak code but it's not the more not the most efficient solution because there happens to be a slightly better solution which is greedy and i think that's what's hard about this problem because there's multiple solutions and if you go down the dp track it can take up a lot of time and then you don't realize that there actually happened to be a better solution but i think in a real interview hopefully you would still pass for doing the dynamic programming solution now consider a pretty simple example like this one where we have two people for the first person we can send them to city a for a cost of 10 or to city b for a cost of a hundred similarly the second person can be sent to city a for a cost of 10 and to city b for a cost of a thousand now to minimize the cost it's obvious we would send both of the people to city a but we have to send at least one of them to city b now you tell me which one would we rather send to city b probably this person because yes it costs a hundred but at least we save that thousand and that's really the important part right because then the total cost will be a hundred and ten if we do it the opposite way the total cost will be a thousand and ten now going down this train of thought we can come up with a greedy solution so the question is how can we quantify how important it is to send this person to city a rather than city b how could we quantify how important it is to send this person to city a or to city b right like what's more important sending this person to city a or sending this person to city a well the easiest way would just be to look at the cost difference if we take the cost of sending them to city b subtract it by the cost of sending them to city a we basically get the cost of how much more expensive it is to send them to city b which is also pretty much the cost that we would save if we rather sent them to city a than city b so if we compute this for every single person in the input array then we can effectively compare all the people so let's do that so for the first one we'll take the second minus the first 100 minus 10 so that's 90 that basically means it's 90 it's going to cost us 90 more to send them to city b than city a that's really obvious by looking at it so let's quickly do the rest so the second one is going to be 990 the third one is going to be 450 500 minus 50 and then the last one 99. so in this case all of them are positive and that really tells us that it would be cheaper to send all of them to city a rather than city b but we already knew that but now we can effectively compare them so now the question is of these four people who should we send to city b probably the ones that are relatively cheap right so these two people should be sent to city b now how would we know that because we need to usually send half of the people to city b well we would probably have to sort this input array so we would sort this in parade and get the first half of them so these are the people we're going to be sending to city b okay so we know these are the people we're sending to city b these are the people we're sending to city a but remember all we wanted to do was return the minimum cost of course we could build this output in such a way where we also preserve you know what the original values happen to be there's definitely multiple ways to do it there's also one way which you might like better where you're just summing actually all the values from the a side and then adding this portion but i think it'll be a little bit easier to actually just preserve the original values because with this drawing it's very clear these are the people we're sending to city a the b actually and these are the people we're sending to city a and we're just going to get the total cost of each of them so if you remember this one mapped to this one which we're sending to city b so we take the second value this mapped to this one and we're taking b the second value this mapped to this one and we're taking city a this mapped to this and we're taking city a again total all of them up i think we get 260 which is the minimum cost that we're going to return and by the way what was the time complexity of that well most of it was big o of n but if you notice we did have to sort this diff array so technically the time complexity became n log n because of the sorting but that's definitely better than the previous dp solution we had that was n squared okay now let's code it up okay so now let's code it up and there's many more elegant ways you could do this in python but in case you're watching and wanting to do this in java or a different language i'll try to write it in a way that you could do that so we have two costs right c1 c2 they call it city a city b but i'm going to stick with this so as we iterate through costs we're going to get the diff and the way i was doing it in a drawing is c2 minus c1 but you could obviously do it the opposite way and get the same result as we take this diff we're gonna want to sort the array based on this diff so actually let's create a diffs array up above we're going to take this diff and add it to the above array but actually let's uh also preserve the original values c1 and c2 as well so basically these three values are going to be added to this okay so now we can have our result which is going to be the minimum cost initially we're going to set it to 0 and then we just want to go ahead and iterate through every single value in our diffs and actually before we even start iterating through the array don't forget that we wanted to sort uh the diffs array so let's make sure to just do that by default it will sort it based on the difference which is really what we care about and remember the first half of them we want to send to city 2 and then the second half we're going to send to city 1 so we can do that pretty easily by just taking the index checking if it's less than half of the length of the array which you know it's pretty straightforward to do and if that's the case then we can add the cost to the result but remember what cost are we getting well let's take the diffs at index i which is the position that we're at right now and then we want the cost to send them to city 2. so we can get that by taking index 2. the else is going to be just as simple so we can just copy and paste it but remember the only difference was that then the second half of them we're gonna be sending to city one so we can get index one to do that and then all we have left to do is return the result and let's run it to make sure that it works and as you can see on the left yes it does and it's very efficient i will mention that there's actually a much more elegant way to write this code you can check that out on the leak code disqus section but i thought that this was a more intuitive way to do it especially the way that i drew out the picture so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
956
cool 9:36 tallest billboard you're cool 9:36 tallest billboard you're cool 9:36 tallest billboard you're installing a build one wanted to have two large aside the people have to still support one on your side each still suffer my superior you go hi you have a collection of watts which can be rode together well together for example you have one two and sexy running together of credit support of sex we turn the largest possible height of your bill boy installation you cannot support the billboard if you cannot support a bill returns oh okay so then this is just subset somewhere largest subset some so then actually n is equal to that's ten twenty so I mean you subset you can solve this in the number of rice but because they tell you that the some of you to order wads is that most five thousand five gonna be subset some you got actually technically if you like to the twenty is like a million which is maybe barely too slow he's on the code and he's on Python Oh Miko because I think a million is way fast but I'm Python it's just a little slower for whatever it is but given that to someone who watches five thousand that means it this is actually give me a subset sum which you know you got your car we just dynamic programming so yeah it's some of the watch someone that I was in ok and in this case you want to use each one and most ones so that's let's get at it Python oh I would do in super sports because that's what you request or maybe snowman you know but I do need more practice to pipeline Italian programming but it's fine it doesn't matter but yeah so now so subset-sum is a but yeah so now so subset-sum is a but yeah so now so subset-sum is a specific type of one dynamic programming in that it is pseudo polynomial not necessary polynomial so we would just do I have a can away is that a good name naming is hard all right also typing is hard too new place huge you can't even okay it's too late maybe next time yeah I'm using seasoned act I think you know people use back maybe I should be better by c plus and like do C++ things by c plus and like do C++ things by c plus and like do C++ things but yeah so and this is technically boolean which I'm still bad at doing sometimes cuz you could actually do input back to and okay anyway so yeah so now you can always get to 0 and then now for each why yeah actually I guess the issue I guess the cool kids use auto kind of except for it's a replacement in the pre-processing replacement in the pre-processing replacement in the pre-processing stage where's this and there's some nuances there but uh that's kind of show on but the essentially you can think of it that way until you can't my neck because of certain situations where not I was oh yeah and then now let's just do and now we just won oh wait hmm they have to be the same some way it's not just as I was thinking of a version where you could cut one off so that in this in some cases okay so whoops maybe this is a little off then but mmm you think about it for a second Oh hmm do I need to take advantage of n is less inch one maybe I do maybe does it make that only time a programming in that case so I do more than that we do it to the end maybe okay why still dynamic programming well have to structure this a little bit differently because I thought for someone like this case you could just do one right because in this case that's not true maybe I just need to count number of ways no you need exclusive sets so another thing that I can do is summon Cora meet in the middle so I wanted to meet in the middle no it's probably not that intense glad to use all the words know cuz I could I should read this farm carefully before I start typing but I thought it was something that I've seen before Ryoga so they took my ad so each of these numbers have three states they like live adjective tops down so okay it's not so bad oh wait a second yeah maybe I don't know how to do it bottoms of potatoes yeah so the recurrence there's a different one so the recurrence is just mr. recurrence the dimensions are index and just left some in the right summon then we could cash based on whether that's possible okay yes that's legitimate okay so yeah that's just to left some and then write some which is what it sounds like and then now okay that's not so bad means and in theory if you look at this if you do it dinette mansion area analysis this means that is twenty times five thousand but actually these two numbers can be represent by one number because you'd sum them at the end so that should be okay but we keep the number so that we could use to we use it to return them max okay cool let's do that okay yeah and just return go now let's be a tune on your words 1 0 okay and then now I had to create a dynamic programming training does not give me the best well 20:20 kind of think a little bit if well what does that mean with this is cached no means the press answer is can you mmm I mean the thing that I worry about is it's just thinking about whether this is a correct state in terms of sub-problem optimum of sub-problem optimum of sub-problem optimum but it's updated sub-problem is optimal yeah maybe it is clean that's how I would structure it now maybe the ordering I'm doing it is a little bit me think about this for a second a lot of lessons initialized our way Roka yeah if this is you just then just return it otherwise type / side okay I think I'll take I type / side okay I think I'll take I type / side okay I think I'll take I think that's it I'll do okay if in Texas you're gonna do activated yet just a base case yeah cause it doesn't matter either way go some windows stuff keeps popping up not a virus return to London maximum made by the Mac so we just returned some ridiculously welcome not such a test to the pass so let's say we only keep track of less left some well we could just keep track up open and / - I guess doesn't matter up open and / - I guess doesn't matter up open and / - I guess doesn't matter but so the best for now is you go to I guess negative infinity the best is going to maximum okay so you that is when you don't use the current one so there's one stone right some and then also yeah okay and just sort of go index past one there's some plus or stop index and that's just yeah I just didn't oops right so and then also possible tax it should be symmetric address is correct so yeah marked by something here because you have to confirm that these are reachable first I guess these are reachable and otherwise they can dig live infinity when they given for use is too high you just want to get under for whatever it's only need to consider one of these cases so otherwise you're gonna double count both sides so I guess we're going to buy two maybe that's good enough finalize it also I need to maybe mmm let's pray more cases huh that's unfortunate but see what we're still better than nothing I guess I always get civil am I missing some yeah she looks okay maybe have some weirdness no I'm just getting our service which is possible good I said there's something more basic and then see what happens probably have a base case issue which is just will always return zero which is a good pace case why is the East not be turning correctly yeah you're interesting okay that's thanks let's see where my prices come so doesn't do any recursion oh I'm just being silly this should not be no I had the base case I don't need to set it mmm okay I think I was still on the mind step doing it by myself which is what it's what I've done okay it's just silly no I just oh and now we can submit the money time seems fast but I'm also not doing any big numbers I'm gonna exceed it huh I mean this these are just like powers of two so I must have done something weird in terms of to the equation step course hmm okay all right let's meet the only whatchamacallit 10,000 times twenty two hundred thousand 10,000 times twenty two hundred thousand 10,000 times twenty two hundred thousand so am I not cashing could be somewhere hmm that's one that's my only yes Chris but each of them obviously do a constant amount work so not to print out no fine print too much but that's why I just want to see whether certain situations aren't being toppled right I guess I need to put this here actually otherwise they might well okay but that shouldn't be the case because you only have I guess I'm like running into some memory SS type things and I'm because I'm God I'm mad but they said the sum is less than five thousand which just appears to be less then I'll put them to exceed it but yeah there should not be five hundred thousand print so that means something is going wrong to caching oh I see what it is I'm just being silly again because I used negative 1 to denote that I'm not visited BAM my best sometimes is a negative number so then it just recalculates okay that's just me masonry so this is nothing wrong to album which this happened some time and time how do I want to think about this I guess doesn't have to be a negative infinity right now has to me because otherwise sometimes you can go on top debts is it okay for it now Chris yeah you're gonna get into weird states I think just well I will say this only happens when is negative one which we can't really touch that whatever I mean I was just bring lazy and trying to save a boolean value so we could just add that learn this lesson Harnish way we're not too bad and now let's say I've just seen we don't do it and then we say cool yeah just silly mistake under impossible cases cool yeah I mean this world to be straightforward dynamic programming pseudocode Ivan do I just had some wasn't sure that there's a prom up optimality is a friend may beg approval later and I maybe I also as practice I have to do bottoms up on this one save memory but not bad of a deal and again going for this problem this is what is Januarius known as a pseudo polynomial dynamic programming for so you get your wish for dynamic programming well but yeah and the complexities end times the maximum you know times two which is obviously all end times to Maxim for kids I'm okay is you're gonna Maxim yeah and that's mostly it space is also the same so you could probably cut a layer of I think now actually I know I could do it would fold up I take that back I've done this before it's similar to what I had already it's just that I had to keep track of do another level I just wasn't sure that this was right to begin with that's why I why but yeah and but if you rewrite it using bottoms up and you can maybe and then you could save you know twenty times the memory ish oh and mayor of memory but yeah I would say subset somewhere or so some or what yeah it's January something that I have seen on interviews so definitely practice this but I mean this one's a little bit our little variation my flag up seems variations of this before and I end up taking half an hour and it could have been faster but about poor I would say definitely people even and me faster but yeah I don't know who my journey tricks but yeah as usual dynamic palm programming the hardest parts to transition and yeah and I think just the way I layer now is actually pretty straightforward I mean the key point is noticing that left someone invites someone not to separate states you could actually just cache to tell two of them and I everything here it's just kind of I'm making sure that it isn't we're gonna go away and so forth cool and then I have a silly mistake because of the way I did to check whether something was cached which is usually works but in this case because of the negative sums that happen I didn't work and cost me a submission but yeah
Tallest Billboard
number-of-music-playlists
You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height. You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`. Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`. **Example 1:** **Input:** rods = \[1,2,3,6\] **Output:** 6 **Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6. **Example 2:** **Input:** rods = \[1,2,3,4,5,6\] **Output:** 10 **Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10. **Example 3:** **Input:** rods = \[1,2\] **Output:** 0 **Explanation:** The billboard cannot be supported, so we return 0. **Constraints:** * `1 <= rods.length <= 20` * `1 <= rods[i] <= 1000` * `sum(rods[i]) <= 5000`
null
Math,Dynamic Programming,Combinatorics
Hard
null
1,312
hey everyone welcome back today we are going to solve problem number one three one two minimum insertion steps to make up string palindrome first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I've taken the second example from the late codep site so we are given a string we need to make this string a palindrome so to make this string as palindrome I can only use the given characters in this string so I need to find the minimum number of insertion of characters in this particular string to make the string as palindrome right so I'm going to use dynamic programming approach to solve this problem so now we will see how we are going to do this so here I've created a dynamic programming array for the length of the characters that is 5 here so I have created a list of 0 for the length of string right then I will be writing two for loops so where my first pointer starts from n minus 2 and reduces to 0 so I will run till my I pointer is 0 right so the N minus 2 refers to the second to last index in the input string so which is nothing but it represents the second to last character in the input string right so n minus 2 will be 3 right 5 is n minus 2 3. so it represents the character d the third index in my input string right so initially my I will start from 3. then I will be having a variable previous where I will initialize to zero then I will write another for Loop where I will run from I plus 1 to m so my J will start from 4 to M right then I will create a temporary variable so aware I will initialize the temp variable with the value of the jth index in the dynamic programming array so jth index is 4 so I need to look the fourth index in my dynamic programming array I will pick that value I will initialize that to my temp variable that is 0 right so now I need to check if my jet character and the ith character is same or not so I use 3 and J is 4. they are not equal if they are not equal I have separate rule here so I will take minimum between the jet index value in my dynamic programming array that is 0 then I will pick J minus 1 value that is 0 again then I will add 1 to it where I will be getting 1 I will place this one in the jet index in my dynamic programming array so here it becomes 1 now J is 4 right so in the jth index value I will replace with 1. so now I will initialize temp value as the previous value right after each and every iteration in the jet for Loop this will be the case here so my previous becomes zero anyways it is 0 previously so it doesn't matter here so now we are done with the for Loop that means the second for Loop the jth for Loop is Done Right 4 to 5 is done we are not going to pick the fifth index which is invalid so we move on to the previous for Loop and this will reduce to 2 now so I will become 2 then I will initialize previous as 0 then I will start my jth for loop from I plus 1 index to n so it starts from 3 now then I will initialize stem variable with the jth index value in my DP array that is 0 so it will be 0 only right so now I need to check the ith character and the J the character whether they are equal or not no they are not equal right then I will pick the minimum between jth index value that is 0 we have 0 at the third Index right then we pick the J minus 1 index value which is 0 again in the second index we have 0 then I will take minimum between these two which is 0 I will add 1 to it where I will place in the jth index now I will initialize the previous value as temp value which is 0 only then my J becomes 4 now so we are running the second for loop from 3 to n 3 to 5 right now if J becomes 4. then I will initialize the temp variable as the jth index value which is 1 we have one at the fourth Index right then I need to check the ith index value and the fourth index value both are not equal so I take minimum between jth value that is 1 and J minus 1 value which is 1 again then I take minimum between these two which will become 1 I will add 1 to it and I will place 2 in the jth index value in the fourth index then I will initialize the previous variable to temp so it becomes one now so we are done with the second for Loop so we are going to the previous for Loop and I reduces to 1. then I will initialize previous as 0 then J starts from 2 to n i plus 1 to n right then I will initialize the jth index value that is 0 as my temp value so now I need to check the ith index value and jth index value whether they are equal or not no they are not equal right so I will take minimum between jth index value 0 and J minus 1 value which is 0 again then I will take minimum between these two which will become 0 and then I will add 1. and I will place 1 in the second index that is the jth index so it becomes 1 here then I will place the then I will update my previous value then I will update my previous variable as the temp variable so previous becomes 0. so now my J increases to 3 again I need to check the ith index value and the Jet index value that is the characters both are not equal I will pick the jet index value and J minus 1 index value which is 1 again I will take minimum between these two which will become 1 I will add 1 to it I will place the index that is 3 right so I will press here 2. so when two characters are equal we will update the jet index as the previous value right so if we keep on doing this we will be having the minimum insertion steps to make of string palindrome value at the end of the dynamic programming array so we need to return that value so when the characters are equal we will not do any updations we don't have to insert anything right so we just replace with the previous value so when they are not equal so in that case we update the dynamic programming arrayability minimum between the jth index and J minus 1 index values right that is what we are doing here so that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I'm taking the length of the input string as m then I'm creating the dynamic programming array with a list of zeros using the input length then I will run a for Loop starting from n minus 2 value till 0 then I'm initializing previous variable as 0 at the start then I will write another for Loop where it starts from I plus 1 to n and I'm initializing temp variable as the current index value right then I will check whether the current character J is equal to the second last character I if they are equal I don't have to make any insertions so I will just update the dynamic programming array that is the jet index value as the previous value itself I don't have to make any insertions here and if they are not equal then I need to make some insertions so in that case I will take minimum between the jet value and J minus 1 index value from the dynamic programming array and I will add 1 to it and I will update that value in the jet index then I will initialize my previous variable as temp then finally I will return the last value from my dynamic programming array right that's all the code is now we will run the code as you guys see it's pretty much efficient so the time complexity will be order of n square and space will be order of n right thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
Minimum Insertion Steps to Make a String Palindrome
count-artifacts-that-can-be-extracted
Given a string `s`. In one step you can insert any character at any index of the string. Return _the minimum number of steps_ to make `s` palindrome. A **Palindrome String** is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "zzazz " **Output:** 0 **Explanation:** The string "zzazz " is already palindrome we do not need any insertions. **Example 2:** **Input:** s = "mbadm " **Output:** 2 **Explanation:** String can be "mbdadbm " or "mdbabdm ". **Example 3:** **Input:** s = "leetcode " **Output:** 5 **Explanation:** Inserting 5 characters the string becomes "leetcodocteel ". **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Check if each coordinate of each artifact has been excavated. How can we do this quickly without iterating over the dig array every time? Consider marking all excavated cells in a 2D boolean array.
Array,Hash Table,Simulation
Medium
221
1,870
hello everyone welcome back curious when I'm saying today we have fascinating tasks to tackle together we will be exploring a unique problem called minimum speed uh to arrive on time so uh where we will be embarking on a journey taking multiple trains to reach the office and our goal is to determine the minimum speed the trains need to travel for us to arrive on time so if you love challenges that involves optimizing pros and time management this one is just for you so all right let's understand the problem statement we have floating Point number hour which represents the total amount of time we have to reach the office and to commute we must take and trains in sequential order so we are also given an integer array dist of length n where this I describes the distance in kilometer of the eight train ride so now here is the case each train can only depart at an integer hour meaning we may need to wait in between each train and our ultimate goal is to find the minimum positive integer uh split in kilometer per hour that all the train must travel at for us to reach the office on time so if it's impossible to reach the office on time the function should return -1 so to solve this should return -1 so to solve this should return -1 so to solve this intriguing problem uh we will implement it in C plus so let's Implement and then I will tell you how implementation so in to end this size and if and minus 1 greater than our hour -1 -1 -1 less than zero we return -1 because we less than zero we return -1 because we less than zero we return -1 because we cannot reach and then we initialize two pointer for our binary search so one and Max element distance begin and distance and in sale of distance so it's post maximum possible uh pointer on the right and while left less than right int midpoint will be left Plus right minus left divided by two and double total time will be zero and or I zero I less than and minus 1 increment and total time Plus sale distance divided by mid and total time plus double this n minus 1 divided by mid and if total time less than hour then right will be meet else left will equals mid Plus 1. and finally we return left pointer okay so let's run to verify everything work for this given test case uh okay so everything's work awesome so uh before we delve into domain Logic the cut starts by performing so input validation check uh it's determine the number of trains uh writes and so the number of trends that write n by ascending uh and assessing the size of the this Vector so if there are no train right so for example it's less than zero so for example uh zero or something or only one train so uh n equals one or if the number of train writes minus one is greater than the given hour uh or if the difference between hour and N minus 1 is less than or equal zero the function return in every this case minus one indicating that it's impossible to reach the office on time due to logic constraints so now comes the health of the solution so the binary search algorithm and the code set up a binary search to find minimum speed needed to reach the office on time so the search space is initially set between the left pointer of one and right where a write is computed as maximum of the maximum element in this and speed needed for the last train to reach on time so the binary search iterates until left is less than right and at each iteration it calculates the mid value as the average of left and right so this value represents a potential speed for the train so next it calculates the total time required to complete the journey at the current mid speed so it does this by looping through the first n minus string rice and adding the times taken to complete it right and the time taken for each right is calculated as the sailing of the distance divided by the mid speed because we can start only on full hour so this ensure that we account for potential waiting time between uh trains and finally it has the time taken for the last train right to the total time and if the total time is less than or equal to the given hour it means we can reach the office on time with the current mid speed so in this case we set right equals mid effectively reducing the search space for the next iteration and if the total time exceeds the given hour it means we cannot reach the office on time with the current mid speed so we set left mid plus one narrowing down the third space for the next iteration so and there you have it uh we successfully analyzed and explained the provided uh task a minimum speed to arrive on time so let's run it four and since cases as well so uh yeah it's working and our implementation beat 93 with respect to run time and 25 with respect to memory so all good and yeah uh I hope you enjoyed this adventure in coding and learn something valuable technique along the way and now it's your cure uh try implementing this algorithm in your favorite programming languages or experiment with different test cases to depend on your understanding of this problem and happy coding keep practicing keep exploring and see you next time
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
404
how's it going guys today we're gonna be going over another problem called sum of left leaves this is the problem that's asked by bloomberg and Facebook right now so the problem scription says find the sum of all F leaves in a given binary tree so pretty simple problems description an example here is this tree and it says that there are two left leaves in the binary tree with values 9 and 15 respectively so we return 24 okay so if this question isn't clear all we're really doing is we're adding this value 9 because it's a chart it's a leaf node meaning that it has no left child or right child right the left child would be here it's now the right child would be here it's no insane for 15 the left child is now and the right child is no and they're both left leaves meaning that they've right we traversed from the right so we came from the right and now we went left and so this is a left child of some other subtree in the tree so we have two things to figure out right one is the node that we're on a leaf meaning it has no left child or right child and - did we come from the right so did we - did we come from the right so did we - did we come from the right so did we move left to get to this node that we're on if those two things are true we want to increment account so whenever we have a problem with the tree it's generally probably going to be like a recursive solution a lot of things in trees are done using recursion so that's a good hint the other thing too is that it's not crazy the amount of code that you typically have to write with recursive solution so that's kind of like another hint so like if you're your problem solution is getting really long probably a good sign that you've kind of like fallen off the path and maybe you should consider going down a different path cool so let's try and get right into the solution so what we want to do is we want to traverse this tree so we're given the route to start and every step in our tree or every recursive call that we have we want to basically check those two conditions so I think the easiest way personally to check this is from checking above so if we're on three we can ask one does 3 have a left it does okay cool so it has a left child now we have to ask is its left child a leaf so we're really asking is its left child no and is it's right child no and if that's true which it is in this case we're gonna add to account and then we know we don't need to recurse to this subtree because we've already taken care of its value there's no other nodes in the left subtree we know that so all we have to do is take whatever its value is which is not in this case and add it to a recursive call when we traverse the right subtree so I propose we write a cursive recursive solution where our base case could be if our root is null right so somehow we've gotten to one of these null children we just return zero right because it's not going to add any value there's no note there otherwise if the thing is a left child or sorry if our current node so three in this case again has a left child and it's a leaf node at its value which we just said we would and then recursively traverse that nodes right subtree so we done go to 20 and ask the same kind of thing or if the node run doesn't have a left child that is a leaf that we have to take care of we can simply recursively move through both sub trees so we would just return the result of our left recursive call in the results of our right recursive call so hopefully that made sense if it didn't we're gonna jump into the code and we can kind of go over at then so we set our base case and typically a lot of times your base case in a recursive solution with a tree will be if your roots know so if our root is no we have no value to add right so if we have no value to add we're just gonna return zero so we don't actually affect our sum of the left leaves otherwise we said if our current node has a left child so let's check that so else if root dot left is not equal to no and now the second thing that we said we want to check is if it's a leaf node so how do we do that we check if it's left child and it's right child are both no so if root dot left does not know and root left equals no and root left right is equal No then we know that the thing to the right sorry the thing to the left of us currently is a left leaf note so we should add it to our sum so we'll say root left Val and now the only thing left to do right so this is the case for right here so we added nine and now we need to actually still account for this subtree to the right side so we're gonna add the root dot left on Val plus sum of left leaves and now we're just going to curse on the right subtree so we'll say root whoops root that right in otherwise if neither of these things are true meaning the current node Ron is not known and the thing to the left of us is not a leaf node a left leaf node all we have to do is recursively traverse both subtree so we can simply return oh we should have returned Stephen here as well sorry we want to return the result of whatever those two sub trees give us back so we'll say return sum of left leaves root dot Left plus sum of left leaves root dot right let's make sure this works Oh 14 no whoops forgot now sorry awesome and it's accepted so that's how to solve some of left leaves if this was helpful guys be sure to let me know leave a thumbs up and subscribe to release the video every single day so you guys can try a new tech interview every day yeah if you guys I mean need any help on your interviews or anything feel free to reach out to me a couple people have and I really appreciate it I'm happy to help you guys however I can good luck on your interviews and I'll see you guys next time
Sum of Left Leaves
sum-of-left-leaves
Given the `root` of a binary tree, return _the sum of all left leaves._ A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 24 **Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively. **Example 2:** **Input:** root = \[1\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,606
hey everybody this is larry this is me going over q4 of the recent bi-weekly contest 36. uh of the recent bi-weekly contest 36. uh of the recent bi-weekly contest 36. uh hit the like button to subscribe and join me on discord and let's go find servers that handle the most number of requests so this one i took a long time and you could watch myself to con during solve this problem during the contest afterwards um for me it's just going for a lot of cases and to be honest i don't know how to go about my how to talk about my thought process and if you're new to the channel i usually talk about my thought process instead of jumping right into the solution uh because there are a lot of places to get that but basically the way that i thought about it uh eventually because it took a while i ended up solving this in about 24 minutes uh a lot of the time was just doing nothing uh you could say uh i did not handle that request download i don't know it's a bad pun on the problem name i'm sorry but uh but so what i did so basically you for this problem there are a couple of observations to be made one is that you're keeping track of the states of each of the servers right so that's what i mean i think that one is a user observation because they tell you i don't know maybe that's an observation but anyway one thing you have to note though is that you have to keep track of the servers the other thing is that you cannot do a straight simulation because k is big uh arrival and load are also big so like and the number uh n is also big right so there are a couple of things that are big so you have to do it in linear-ish time so you have to do it in linear-ish time so you have to do it in linear-ish time or like n log n time or better right so that's what i was thinking going from my mind um i think similar problems are uh exponential slash np ish so that's why my mind automatically render and i would normally think about a dynamic programming solution but that's why i didn't really uh pursue that well i was and some of this would come from experience how what i'm describing how i attack this problem and some of it is me just fearing it out because when i stopped when i was looking at this problem uh and a lot of it is going to be rephrase it rephrasing um questions or queries in a way that you can solve right and for me it um the texture of the farm or how i call it how i feel about the problem is just thinking about you know for because i think one thing that i also uh have to note is that i uh is always going to be i and not the next eye from the previous eye so it's a little bit weird as well and i had some silly typo that i just didn't catch so that took a while as well but basically in a way the second question the observation is that for each request you're trying to get um the next non-busy server with an i the next non-busy server with an i the next non-busy server with an i that's over that number right and for me i was put playing around with the idea of thinking of okay what if we don't wrap around then you could do a binary search right like instead of uh like against in this case instead of you know uh server one two three one two uh maybe we just do server one two three four five and then we maybe implementation detail wise uh hack something together where we map four to one and so forth so that's the kind of idea that i was thinking of um but then there's another observation is that you have all these states where you have to trip on and off and get like these defense basically you have to have a rival which flips a state from on to offer that right random how you want to implement it and the load which is another event that takes it off right so that's kind of um these things that i played around in my mind uh and try to figure out how to balance them together uh so how did i end up doing that is that well um i use the heap because that's well heap is only part of the solution right for to deal with the events he is basically saying okay i have handles the part of okay um so for me it's important to kind of separating out the different problems that you have which is what makes this hard is that you have two separate components that you're trying to put together what you know they're all both n log n um and one of them is the heap which means that um because i needed a data structure that tells me okay um you know uh we have to process you know we want to process uh something that's you know here's the event we want to process another event in the future that um that you know it's just another defend in the future at a certain time and we always want to get the minimum of those uh defense so that leads itself to a priority queue or heap right because uh and that's basically what i do here basically he for me has two apis one is adding an event and then one is removing the event as we talked about which is when a load when a request arrives and then when a request leaves which is when you know the load is done right um so basically that's the idea behind the heap and i'm going to separate that out we're going to ignore the second part of it for now so that um because i want to explain the deep understanding of the heap part first uh but basically when a request comes in it comes in that a we that's the time so we look at the top of the heap and if the beginning of the heap is um is before the arrival time or equal to the arrival time in this case then we pop it off the heap because we're like okay um you know that event is done that means that we can use the index asso the processor of the index uh associated with that request then it's done right and we keep on doing this because in the heap there's this invariant in that everything inside the heap has a later um processing completion time right so that's basically what this does here and then another one and you know let's say we found the processor that we're trying to um occupy we uh we then put it back into the heap we increment the count i guess uh but we put it back into the heap with the leaving time which is a plus l the arrival time plus the load time and then we just keep track of the index and that's basically all we use the heap for uh keep in mind that in python uh in hip q it's a min queue a mean min priority queue right where in other languages it is a max queue so or max priority queue uh or max heap sorry i keep um so when you look at other like solutions in c plus or java or something like that keep that in mind because they might write things a little bit differently as a result uh okay so let's say we have understand understood the heap part um now we need a second thing which is you know we need a data structure that keeps track of two things for us one is uh for every processor all the numbers in the uh oh sorry for all the processes give us all the indexes of processors that are uh available or taken depending on how you wanna do it doesn't really matter right then worse um and two is we need this data structure because otherwise it's just a hash table lookup right we need this data structure to also be able to answer the query of give me um give me the processor index that is uh greater than or equal to a certain index so those are the two attributes that we need and in different and you know this should uh be already and depending on your language there's said uh like c plus you could just use set straight up because there's binary search in set uh and i think it's same in java it could be wrong so let me know but in python uh the set doesn't do that uh so i have to use a sorted list um it's a algo is a data structure or a library of a data structure that i'm to be honest not as familiar with which is also why you see me uh during the contest uh struggle a little bit or not struggle but like i'm basically looking up the api a lot of the time just to make sure even though this is actually pretty straightforward the way that i did it um but basically a sorted list is just you know a list that's always sorted so that you could binary search on it um and then the second question is okay how can you binary search if it wraps around so that part also is an observation that took me a little bit of time to make and my what i end up doing is i binary search for imod k when a request first comes in for the smallest number that's bigger than i mod k right if there's no request then i binary search the smallest number um or just get the smallest number in general i guess so that it handles that wraparound effect um and that's basically it to be honest uh because for us and as we said once we um so in the beginning we so s is the list of um processors that are available so in the beginning i put all the processors in it uh everything in k um so i do this binary search thing that i talked about i did a binary search from i mod greater than i mod k or equal to uh if is greater than the length meaning that's um you know that means that it doesn't exist then we will uh wrap around to do k we do it by if i never hit you on zero though i think we could just take the minimum element but i wasn't thinking about it during the contest to be honest um and then if this is good meaning if there's a um a processor available and i actually could have rewritten this as uh if the length of s is greater than zero um because that means that if any processor is readable you should just take it right so in any case you take the um and k is the index of the sorted list of the available so we just map that to that so s sub k is the index of the processor that we're taking so we increment that by one uh we set the next time that'll be a red over by putting it in a heap putting the keeping track of an index and then i remove that processor from the sorted list and that's pretty much it um because we you know uh and when we process that the processor is done which is what we do with the heap we put it back into the sort of this index uh and then the way and this is trivial is just for uh you look at you try to find the max the most number of requests that you got and then you just kind of look at each element that is equal to that um yeah so what is the complexity of this um sorted list is a little bit of black box let's say it's n log n i think it's maybe n squared would have n but let's just say n log n uh because in if you if this is like a tree set or something like that in different languages uh this would that would be have the same complexity and it'll be uh log in right in that case each element gets pushed in the heap at most once uh and leaves the heap at most once so that's going to be and again for the heap side and put assorted this side um again each processor or sorry for each request we only at most uh insert into the sorted list one processor and remove it at most one processor so that's also going to be n log n uh and then this bisect is just two bisections for each request so also going to be n log n so that means that um if you look at this for each request everything is gonna be at most log n roughly because i know that this is a while loop but this is um amortized log n so this process is going to be um yeah n log n uh yeah and not getting the number of requests but to be more precise because all of these operations are actually on k not n so it actually is n log k um so yeah so time it goes to n log k where k is the number of processors and n is the number of requests um so the space of course is just linear assuming that heap is linear count is linear and sort of this is linear which i'm actually to be honest not super sure about i don't know if they use certain things to make things a little bit better but let's say linear for the most part because in tree set or something like that it's gonna be linear right so you can substitute three set that's how i do it in my head and yeah and you return the results again so and locate time linear space um that's all i have for this problem it's a long explanation because there are multiple parts let me know what you think let me know what you have trouble with as usual i try to think about the thought process more than just the solution so you know let me know what you think about that uh hit the like button and also you can watch it watch me solve it this problem live now you so you yes so um next you okay hmm so fun to i'm getting in some sleep i got it i hope it slowed down and you i need to be more friendly with this to be honest play sometimes foreign so okay um index hmm um now this is this belt this is wrong okay oh okay that's and this is not my pivot display this is annoying to debug uh but why oh it's going to be not ready for a while mess that up oh that's the third request okay four functions this should go to zero but zero is not ready yet one is that way and three is not really yet wait one is ready okay what is this just one thing oh it's not zero two three four right am i having enough by one so it should be busy until six which is true oh maybe this should be there should be two now but it's not good so why not i miss this i think right now i'm just not understanding the problem well so there's 012 which is fine two down to 13. oh this should be one huh hmm that was silly i remember i wanted needed to do that but then i just forgot about it come on that was a silly mistake all right hey everybody uh yeah thanks for watching this is larry uh this is me out uh hit the like button hit the subscribe button join me on discord i hope you had a great contest i hope you had a great prom uh let me know what you think let me know if you have any questions and i will see y'all next contest bye-bye
Find Servers That Handled Most Number of Requests
find-servers-that-handled-most-number-of-requests
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) request arrives. * If all servers are busy, the request is dropped (not handled at all). * If the `(i % k)th` server is available, assign the request to that server. * Otherwise, assign the request to the next available server (wrapping around the list of servers and starting from 0 if necessary). For example, if the `ith` server is busy, try to assign the request to the `(i+1)th` server, then the `(i+2)th` server, and so on. You are given a **strictly increasing** array `arrival` of positive integers, where `arrival[i]` represents the arrival time of the `ith` request, and another array `load`, where `load[i]` represents the load of the `ith` request (the time it takes to complete). Your goal is to find the **busiest server(s)**. A server is considered **busiest** if it handled the most number of requests successfully among all the servers. Return _a list containing the IDs (0-indexed) of the **busiest server(s)**_. You may return the IDs in any order. **Example 1:** **Input:** k = 3, arrival = \[1,2,3,4,5\], load = \[5,2,3,3,3\] **Output:** \[1\] **Explanation:** All of the servers start out available. The first 3 requests are handled by the first 3 servers in order. Request 3 comes in. Server 0 is busy, so it's assigned to the next available server, which is 1. Request 4 comes in. It cannot be handled since all servers are busy, so it is dropped. Servers 0 and 2 handled one request each, while server 1 handled two requests. Hence server 1 is the busiest server. **Example 2:** **Input:** k = 3, arrival = \[1,2,3,4\], load = \[1,2,1,2\] **Output:** \[0\] **Explanation:** The first 3 requests are handled by first 3 servers. Request 3 comes in. It is handled by server 0 since the server is available. Server 0 handled two requests, while servers 1 and 2 handled one request each. Hence server 0 is the busiest server. **Example 3:** **Input:** k = 3, arrival = \[1,2,3\], load = \[10,12,11\] **Output:** \[0,1,2\] **Explanation:** Each server handles a single request, so they are all considered the busiest. **Constraints:** * `1 <= k <= 105` * `1 <= arrival.length, load.length <= 105` * `arrival.length == load.length` * `1 <= arrival[i], load[i] <= 109` * `arrival` is **strictly increasing**.
null
null
Hard
null
724
hello welcome to problem solving and today's problem will be 724 find pivot index the problem statement is given an array of integer nums calculate the pivot index of this array and the pivot statements definition is the pivot string pivot index is the index where the sum of all the numbers strictly to the left and let me give emphasis on this word strictly and i'll explain what that means to the left of the index is equal to the sum of all the numbers strictly to the index right with the index on the left edge of an array left sum is zero because there are no elements to the left and the if we do not get such index we will return minus one let's check the example for better understanding so here's a given array one seven three six five six so we will be going let me just show you what this words strictly to the left of the index means strictly to the left means let's say our pivot index is 3 then strictly to the left will mean 1 and 7 and strictly to the right will mean this to this we were taking this as an example that's not actually an answer so let's undo this okay that should be so let's check the example test case so here one seven three six five six so first we will be on the first index that is zero let me show you the algorithm for this so we'll be taking a integer value l which will be storing our left indexes sum and we'll be initializing it to zero okay this is zero right and another value called sum which will be storing the total summation of the array so we will take in for loop and we'll just add all the elements and store it in sum for this case the sum will be equals to 28 so the sum is equals to 28 for this problem let's just move on to the problem so first we are on index zero so to the left there are no elements and this is our pivot index for right now and to the right we have these elements and to the left we do not have any elements so the pivot sum to the right will be this excluding this from our total sum so we will keep our total sum 28 minus 1 which is 27 so these are current some value and what is a next index the next index is 7 when we move to the next index we will add our prefix sum that is the previous value sum so the previous value here was 1 so our current prefix sum or l sum here is one and we are on index one so we will add these elements or these will be our right sum of our array so we have to subtract this from our total sum right now the total sum right now was 27 so we'll decrease the array not the added the sums value and the sums value will be zero 20 so the current value on index 1 will be for right sum 20 and for left sum it will be 1 so now we move on to next element that is three so the prefix sum for the index zero one two will be seven plus one eight that is eight so the prefix sum will be eight right now and prefix some of the right elements will be 6 12 plus 5 that will be 17 and we will subtract this to get our subtract 3 from here so we will get our right index sum that is 17 this is 17 now we move on to the next part that is the element 6 or the index 0 1 2 3 are index 3 at index 3 our sum is 7 plus 3 10 and 11 so our left some value is 11 right now this is the l sum and so as we are in the index 0 1 2 3 and we need to find out the right elements sum so we will subtract this from our sum value so this will 17 minus 6 will give me 11. so as we can see the l sum value and the are some values are same these two are same so we will return the index that is i and in this case our index will be 0 1 2 3 so we will be returning 3 as you can see the output is 3 here so let's get to the code i'll just zoom on to it better okay so what i have done here is i have taken two variables into the variables l sum and sum l sum was to store the prefix sum of the array and the sum is to store the total sum of the array so l sum and r sum and i have calculated the total sum of the added this will give me total sum off and we are iterating over the array our problem array which was this one seven three six five six and after that i have done sum is equals to some minus numbers of five i have done this i'll just explain this again since for the first element i'll just write one here since when i'm on the first index this is my first index 0 and i'm standing here or my when my pointer is on the first index to the left i don't have a real elements so my l value is 0 that is fine i don't have to make any changes for that but on the right side on the right to my right all these elements have a particular some value all these number will be adding to a particular sum but i do not have to include the number one or the index zeros value in my sum so i have to decrease the value of the position where i'm starting so 28 minus 1 will give me 27 so this is my right value or the right sum for the index 0 so this will be just checking for the value if alpha equals to sum that is and my left sum and right sum is equal then i'll be just returning the value or the returning the index i or else i'll be just adding the l sum plus numbers of i also l sum plus numbers of i does the prefix sum of the values so when i'm at index uh 2 let me just say when i'm at index 2 my l sum will be 7 plus 1 8 the prefix sum of the consecutive two elements will be eight for my index two and if not we'll be just returning minus one as per the given problem and because run this code sorry for that i'll just run this code if that's getting accepted let me use the example test cases the example is 82.56 so yes thank you for watching
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
1,630
hey everybody this is larry this is me going over arithmetic subways q2 of the recently code contest uh hit the like button hit the subscribe button join me on discord uh and you're gonna you get to watch me solve this live afterwards but the short answer for this question to be honest is just brute force um basically this is the definition of arithmetic right so what i did was not really uh not very are working the great but basically what i did is just before us for each query we literally take to see if it's good or not our good function is just we take all the numbers in that range we sort it we put in a list if it's one element it's good if it's not we literally just take the definition here where we take the difference between the first element and the second element that's the delta and then we check that every num if you sort it or the um that's the only way to kind of do the arithmetic with that entire subway um so basically yeah we sorted we do this delta check and that's pretty much it so each query is going to take adverse and not again so this is n squared log n um at the worst case and since this is 500 so i guess that's okay in terms of space depending on how you want to define it we kind of uh to make it sure that we don't use it in place we because in this case i would count it because we really don't want it in place and we allocate memory every time so every chord to this function will take and like uh or of and space so this is maybe n square space um in the worst case and yeah so n squared space n square log n time and that's how i did it during the contest you could watch me start this live next um hmm so oops i'm just putting nothing okay what is going on misunderstanding something oh my this is what happens when you use single variable names you do stupid stuff okay i am dumb it's the rightful slider plus one here right um let's see really slow today hey everybody uh yeah thanks for watching the explanations if you're here uh definitely appreciate it hit the like button hit the subscribe button join me on discord and yeah i didn't do that well just contest but i did learn a bit from the q4 i liked it i digged it uh dug it so it is what it is anyway i will see y'all next explanation bye
Arithmetic Subarrays
count-odd-numbers-in-an-interval-range
A sequence of numbers is called **arithmetic** if it consists of at least two elements, and the difference between every two consecutive elements is the same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] - s[i] == s[1] - s[0]` for all valid `i`. For example, these are **arithmetic** sequences: 1, 3, 5, 7, 9 7, 7, 7, 7 3, -1, -5, -9 The following sequence is not **arithmetic**: 1, 1, 2, 5, 7 You are given an array of `n` integers, `nums`, and two arrays of `m` integers each, `l` and `r`, representing the `m` range queries, where the `ith` query is the range `[l[i], r[i]]`. All the arrays are **0-indexed**. Return _a list of_ `boolean` _elements_ `answer`_, where_ `answer[i]` _is_ `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._ **Example 1:** **Input:** nums = `[4,6,5,9,3,7]`, l = `[0,0,2]`, r = `[2,3,5]` **Output:** `[true,false,true]` **Explanation:** In the 0th query, the subarray is \[4,6,5\]. This can be rearranged as \[6,5,4\], which is an arithmetic sequence. In the 1st query, the subarray is \[4,6,5,9\]. This cannot be rearranged as an arithmetic sequence. In the 2nd query, the subarray is `[5,9,3,7]. This` can be rearranged as `[3,5,7,9]`, which is an arithmetic sequence. **Example 2:** **Input:** nums = \[-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10\], l = \[0,1,6,4,8,7\], r = \[4,4,9,7,9,10\] **Output:** \[false,true,false,false,true,true\] **Constraints:** * `n == nums.length` * `m == l.length` * `m == r.length` * `2 <= n <= 500` * `1 <= m <= 500` * `0 <= l[i] < r[i] < n` * `-105 <= nums[i] <= 105`
If the range (high - low + 1) is even, the number of even and odd numbers in this range will be the same. If the range (high - low + 1) is odd, the solution will depend on the parity of high and low.
Math
Easy
null
138
hey what's up guys this is john here so today uh let's take a look at today's daily challenge problem number 138 copy list with random pointer so basically you just it just asks you to make like a deep copy of a linked list but the only difference is that you know for this linked list other than the value and next pointers there's also like this kind of random pointers which means that you know any node can point to a random node right for example this is the example right so and so there's like a next pointers as i like the uh the normal length list but there's also like some random pointers it could be uh pointing to a different random point uh note and our goal is just to make a deep copy and there are some like edge cases right if there's nothing we just simply return nothing yeah so i mean everyone knows how to make a deep pointer uh how to make a deep copy right basically we just make a copy of a new node and then we just uh populate the next with the with a new one but for this one you know since we have a random pointer right so let's say when we uh when we're making like the a node a copy of seven right so we're trying to copy the node of 7 assuming this random pointer is pointing to the last one to this one and so once we have populated the uh basically let's see we populate seven basically we make a new node of seven and then we have a next of course we'll make a new node of 13 right so this is the new node this is also a new node and then with just populate the next the new nodes next to the third to the to another like the copy of the node 13 right and then we also need to make the uh basically another pointer another new node to point for a node one because the current nodes random pointing to one right which means at the first step we have deep copied three notes this one and this one right so it means that you know when we process when we are at process this 10 here okay and when we are trying to make a deep copy out of 10 here right so the 10 next should be pointing to one okay but so here at this moment we don't have to make a deep copy of one again because we have already make a copy right deep copy of one note when we are trying to make a deep copy of seven right so here uh when we add 10 here so when we populate the new node of 10 then the new the newton we should not create another deep copy out of one instead we should just uh find this deep copy of one somehow right but how can we find it right so at a 10 here we know the uh the next node is one right so from the one what is the original node we should be we should we need to find the deep copied version of one and then we need to return that right and then it leads to like a basically what a hash table or a dictionary right which is the key is the old note right and the value is in the copied node right it's a copy node so which means that we're going to have like hyper functions every time we're trying to make like a deep cup a deep copy of a note right uh we always check this dictionary if this dictionary have already has like a copied version of the current node we simply return that otherwise we make a deep copy and then we save it into the dictionary yep i think that's the only thing we need to do here cool so and other than that you know you can either use like the dfs a recursive or a or iterative way to look through the uh the note so since this one is just like a simple uh a length list we can you use the uh the e30 way which means that you know so first you know let's do this if not had return none right that's the uh that the edge case and we have a new uh current so the current going to be the node of the hat of the value none this is the starting point of the deep copied linked list okay and then similar for the current equals to hat right and then we have a scene i'm going to use this scene as a dictionary to store those kind of knows that we which we have already copied at the beginning right so the mapping is we have a current equals to the current start to the new current okay so while current now we can just do this right uh now we have a new current right the new current dot next equals to what so i'm going to have a get copied node right so current dot next and then the new current dot random equals the get copy node current start random okay and then we move forward we move the both the current and the new current forward right new current dot next and in the end we just return the scene dot hat all right so yeah basically you know we every time when we have like the a new uh a current right we just uh um we just try to make a copy of the current.next and the current.next and the current.next and the current dot random and so which means that uh when we um implement this get copied node here we have a node right and if not node right simply return none else right so if note not in scene okay we make a copy basically the scene dot node equals the node of node.value and then none of node.value and then none of node.value and then none a none right and then in the end we simply return the scene dot node that's how we make a copy right of the current node if there is already a one if there's the node it already exists in the scene here we simply skip this part we just return this the node that we have already copied before right so yep i think let's run the code accept it yeah so that's it right i mean the so the only tricky part for this problem is that we have to maintain this kind of mappings between the old node to the new node so that uh when we try to get a copy note for the um for the next and for under for the random so it could be i mean the current next we already have a copy where current random already have a copy so in that case we don't want to create a new one because if we create a new one uh basically it's two instances of the same node and we'll be losing the pointers right so here we only create when the current node when this node doesn't have a copied version of it right and then if it doesn't we make a copy and then we store it into the dictionary and then after that with the return node here we'll basically populate the current the new current dot next and new current.random current.random current.random so that we can finish populating the current node with the new current node and then after that right we're just moving the we move the pointer forward for both the current and new current so by doing this right you know the we have the pointer pointing to the same location for the current and the new current right this is obvious right to be able to move to the new uh to the next node further for the new current we have to create that node first right that's what this get copy note uh is doing here so if this one doesn't if this random node or this if this next node doesn't exist right we will create that we'll create that node and then we'll then so that we can move to the next one yeah i don't think i have anything else i want to talk about for this problem i believe for this problem there's also like a way that um i mean you can skip you i mean you can avoid using this dictionary and but i find it's a little bit tricky to do it i mean so that's why i'm not going to uh cover that solution here yeah i guess i'll just stop here and yeah thank you for watching this video guys stay tuned see you guys soon bye
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
785
okay so lead code practice time in this video there are two goals the first one is to find the solution for this specific problem and also do some coding and the second one is to see how to solve this problem properly by following the interview process so let's get started so remember the first step is always to try to understand what the problem is what it is asking us to do if there is anything unclear please bring up the clarification questions and at the same time think about some ash cases which we need to pay special attention to so let's see this one is graph bipartite so given an undirected graph return to if and only if it is departed so it recall that a graph is bipartite if we can split its set of nodes into two independent subsets a and b such that every edge in the graph has one node in a and another node in b all right so the graph is given in the following form graph i is a list of the index j for which the edge between node and j exists okay so each node is an integer between zero to graph the lens minus one and there are no self edges or parallel edges all right okay so graphite doesn't contain i and it doesn't contain elements twice alright so i think it has helped us clarify the ash cases like self redirecting and also duplicate edges okay let's see the constraints that okay so no self directing and also graph i j will be between zero to the number of the nodes okay and all the values are unique in graph i graph is guaranteed to be undirected okay so i is equal smaller equal to okay so they're between 1 to 100 nodes this means between 1 to 100 nodes and each node has uh 0 or has 0 to 99 uh edges um okay yeah i think we are pretty clear about this there's there isn't too much things we need to clarify at this moment because based on the constraints it says all the other the graph first of all the graph is valid and also there's no uh self-directing uh edges uh self-directing uh edges uh self-directing uh edges something like that and also uh there's no duplicate edges so let's say so for example one um so zero two one three one two zero two and two one three and uh this one means uh three two zero two okay so it is true because we can separate into two things which is zero and two in the group and one three in the group yeah so um i think um what we could do is we could use a dfs on top of this problem so first of all we start with uh some nodes and we let's say we mark it at uh red and black so first of all let's say we start at node zero we mark it as red and the other adjacent nodes for uh for zero should be black so we mark one three as black and then um we further extend the two so we mark the two as a red so after we mark everything and we don't see any conflict then it means we can uh we can say that it's a bipartite graph so that's pretty much the solution is uh dfs and uh let's see how much time it's gonna take so it's gonna take i would say uh i would say we need to visit all so for each node we need to visit all of its adjacent nose and uh if it is like a sparse graph like there is there isn't too much edges then we but we still definitely need to visit all of its notes so i would say uh the worst case would be oh let's say there are a number of the nodes and they are e number of edges so it will be o and plus e for the worst case so for the worst case regarding the runtime um so after we find the solution the next part is to do some coding so the coding part we care about the correctness the readability and of course the speed so let's get started so um okay so first of all we are going to let's say we define um the color array as new in graph.less so the color array will as at the very beginning it will be initialized as all zero and we are try to we are going to try to color the different notes into either one or two so either working none of the note is colored so we are going to say okay uh iterates through every node um graph dots less plus i let's say we define um a function let's say is israeli color let's say we define something put a placeholder here so if it is a valid color if it is not valley color then we are going to return false otherwise we are going to return true finally so um i would say we could do some filter thing here so if color is not equal color i is not equal to zero it means we have already visited this node and the node before so we don't need to visit it again so we just need to continue here otherwise we will visit it with this node by calling the valid color function which is a helpful function we are going to define later on so let's say we are going to define a helper function is valid so we are first of all we are we need to say which node we are trying to visit so it is a node and uh and the second thing is uh what color it is going to be given uh so let's say current color or maybe just node color and we are going to pass the color array here and also we are going to have pass the graph here so you're going to say okay this one is i and this is we can give it either one or two so i so one is just fine and then we pass the color array and we pass the graph here okay so let's see um so um if so if uh the current node somehow if the car node is colored if node color sorry if uh the color node is not equal to zero and uh the current node color is not equal to the node color we are going to give the node is not equal to the current color it has then we are going to return a false for it otherwise um if it means it is either not colored or it is like the current note card we are trying to given has already matched the color of it before so let's say if node color already matches uh color node then we just need to return true for this one because this is a valid node for uh when we try to color it otherwise it means this the node hasn't been colored so we are going to set the node the color of the node okay and then we will try to visit all of its uh neighbors so let's say neighbor uh by going through graph um node okay so it's obvious neighbors so if not is valid so this is a neighbor and this is a note color let's say it is three minus the node color because we are going to try to color it as either one or two and then um it is a node color oh what is that so color uh yeah this is just color array and the graph so if it's not well let me return the fonts for it otherwise we just return true okay so since then we have finished most of the code let's see the next part is about testing we will go through this piece of code um by manually and explain uh how this code is going to work to the interviewer and then we will try to come up with different task cases to try to increase the test coverage so let's say it's bad parted so first of all we are going to have a color array and then you go through every node if the current color of the node is if the node has been colored then you just continue otherwise we call this dfs function on top of it so let's say at the very beginning we call violet color so we call valid color uh zero one and uh the color graph and the graph the color and the graph so currently color of the color is zero and then is we see that the note hasn't been ever uh colored so we are going to uh color it as color 0 as so we're going to give you the one as a color for node 0 and then we are going to visit all of his children sorry all of his adjacent notes which are 1 and 3 so we are going to say assign 1 and 3 both as 2 when we call the violet color on top of it on top of 1 sorry 1 and three given two and two so one three will be two color two and then for number one it is going to cause zero and it is going to uh the adjacent notes are zero and two so zero has a valid color two hasn't been colored so it is we are going to call the uh to give it a one so currently it is one here yeah so and after everything returns um i think it should be a true thing true case yeah so let's give it a try is sorry oh is valid it's valid okay so it's accepted okay so now i think we should be good about this question and uh regarding the tasking setup definitely set up one task is that it can be bad part it's bipartite graph and another one that's it's not maybe just give example one two is enough so that's it for this uh coding question if you have any question about it please give leave some comments below and uh if you feel it helpful please give me a thumb up and uh i'll see you next time thanks for watching
Is Graph Bipartite?
basic-calculator-iii
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties: * There are no self-edges (`graph[u]` does not contain `u`). * There are no parallel edges (`graph[u]` does not contain duplicate values). * If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected). * The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them. A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`. Return `true` _if and only if it is **bipartite**_. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\] **Output:** false **Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other. **Example 2:** **Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\] **Output:** true **Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}. **Constraints:** * `graph.length == n` * `1 <= n <= 100` * `0 <= graph[u].length < n` * `0 <= graph[u][i] <= n - 1` * `graph[u]` does not contain `u`. * All the values of `graph[u]` are **unique**. * If `graph[u]` contains `v`, then `graph[v]` contains `u`.
null
Math,String,Stack,Recursion
Hard
224,227,781,1736
3
in the previous video we learned about sliding window a problem-solving sliding window a problem-solving sliding window a problem-solving technique that works by maintaining a window that represents a contiguous part of the data in this video we will use it to solve a popular coding problem longest substring without repeating characters the title says it all we have a string s and we want to find the length of the longest substring with no repeating characters for example here the output should be 6 because the longest one is e a f c b h to solve this problem we can think of just traversing all the existing substrings while keeping track of the greatest length thus the brute force solution we traverse all indexes as the end of the substring for each one of them which hovers all indexes before it as the beginning of the substring and for each couple start end we extract the substring from start to end and if it has no repeating characters we check if its length replaces the maximum length we found so far and to check if a string has no repeating characters we'll just convert it to a set and compare the lengths converting to a set removes duplicates so if the length is still equal to the length of the original string then we have no duplicates hence no repeating characters after traversing all the substrings we just return max length the result we're searching for this solution is quite easy to implement but it's very slow we have nested loops plus the cost of extracting and analyzing the substring at each iteration it gives us a time complexity of n cubed where n is the length of the string how can we improve this solution let's suppose that we have this string and we're at this stage of the process the end index is nine in this situation we want to find the longest substring that ends at index nine so we start traversing start indexes with index zero we have no repeating characters from 0 to 9 we get a substring without repeating characters of length 10 then index 1 no repeating characters then index 2 same thing and so on we want the longest one it's when we start at index zero so here we deduce that when we have no repeating characters we just put start at zero to maximize the length now we move n to index ten here things are different because the character at index 10 is repeated before let's start traversing start indexes index 0 the substring from 0 to 10 has repeating characters index 1 same thing 2 same thing 3 also has repeating characters 4 same thing and 5 here we have no repeating characters we found a valid substring of length 6. then index 6 no repeating we found the valid substring of length five then seven we found with a length of four and so on among all these substrings which one is the longest valid one that ends at index ten it's this one and you can notice that it's the one that starts just after the repeated character we deduce that if s of n is repeated to get the longest valid substring we start just after the repeated character okay now we know that together longest valid substring that ends at index end if there is no repeating characters we just start at zero else if s of n is repeated before we start just after the repeated character now you may tell me what if we had multiple repeated characters well we can make sure to not have more than one repeated character the idea is that every time we found a new repeated character we eliminate it let me show you how at index 10 we found the second instance of the letter c it means that in remaining iterations all substrings that will include both instances of c won't be considered as valid it's useless to traverse them this is why from now on we will directly start just after c we drop all previous characters because starting in one of them gives an invalid substring let's combine these two ideas the first idea says that the longest valid substring that ends at a given index and is the one that starts as soon as we have no repeating characters and the second one says that to remove a repeated character we put the initial start index just after it we drop all previous characters let's apply them on this example our first substring is the one that starts and ends at index 0. it has no repeating characters so we found the substring without repeating characters of length 1. it's better than nothing we increment n to move to the next iteration we still have no repeating characters and our actual substring has a length of 2 better than 1 it becomes our new longest valid substring next iteration n is at index 2. we still have no repeating characters so we found the valid one of length 3 it replaces you can see that here we're not moving start because doing so would just shorten our substring while we want it as long as possible next iteration a b c e still no repeating characters we have a valid substring of length four it replaces three now when we move to the next iteration notice that b is repeated its first instance in our substring is at index one what to do in this case we said that to remove a repeated character we put start index just after it we put started index 2. we did that because now that we found a repeated character starting from the actual iteration all substrings that start from index 0 or 1 will be invalid because they would have 2 instances of b so we decided to darkly start at index 2. by putting start at 2 our substring between start and end now has no repeating characters it became valid again we did use that the longest valid substring that ends up index 4 is the one that starts at index 2 c e b we don't need to check other ones because if we move start to the left we'd introduce the repeated character again and if we move start to the right we'd get the shorter substring ceb has a length of 3 is not better than 4. next iteration is true that a exists before in the string but we don't care because it's before where our substring starts our substring has no repeating characters substring of length 4 it doesn't replace next iteration we've seen e before on our substring at index 3 so we put star just after it at index 4 to avoid having duplicates in our substring length 3 it doesn't replace by the way the technique we're using here is sliding window because we're maintaining a window that represents a substring without repeating characters remember that in the last video we saw that the window must respect constraints in this problem the constraint is to have no repeating characters this is why when adding a new character to our window we were instantly checking if we didn't see it before and if it was the case we were shrinking the window enough to get rid of that character to keep respecting the constraint okay let's continue next iteration is repeated before in our substring at index 5 so we put start at index 6. substring of length 2 it doesn't replace next iteration no repeating characters length 3 it doesn't replace next iteration no repeating characters length 4 it doesn't replace next iteration no repeating characters length 5 it replaces next iteration no repeating characters length 6 it replaces next iteration f is seen before index 8 so we put start at index 9. length 4 it doesn't replace next iteration no repeating characters length 5 it doesn't replace last iteration b is already in our substring at index 10 so we would start at index 11. length 4 it doesn't replace we finished traversing all the string s we found out that the length of the longest valid substring is 6. it's e a f c b h what we were doing here is that each iteration we were finding the longest valid substring that ends up that index the longest local valid substring and by keeping track of the longest one among them we've been able to find the longest global valid substring the one we're searching for all that while using sliding window technique to reduce the number of substrings we traverse let's try to write the pseudo code of this process maxlen starts at 0 because we didn't traverse any substring yet stat also started at 0. now we traverse all indexes each one of them represents where our substring is ending at each iteration we started by immediately checking if the new character as of and have been seen before in our substring the one between start and end so we search for the last index where we've seen it and to know if it's in our substring we'll check if it's between starting classif and end exclusive if it was the case we were putting start just after the position of where we've seen it after it whether the character was repeated or not we were checking if the actual substring replaces the longest one we found so far the actual substring is the one between starting and enclosive its length is n minus start plus one so max len becomes max between its actual value and end minus start plus one after the loop the length of the longest global value substring is in maxlan we return it the ambiguous part in this pseudocode is this one s and lastpose is the last index where we've seen as of end to implement this pseudocode we can think of the brute force way which traverse the path between start and end to search for s of and here we're using find method it returns -1 if it doesn't found the searched -1 if it doesn't found the searched -1 if it doesn't found the searched character but traversing a lot of characters at each iteration would result in an oath and square thumb complexity better than the first solution but still slow we have a better way to implement it to avoid always traversing the whole substring again to search for s of and the idea is to keep track of the last index where we've seen each character in hash table a hash table where the key is a character and the values the index where it was last seen -1 by default -1 means it was last seen -1 by default -1 means it was last seen -1 by default -1 means we didn't see it yet and at the end of each iteration we update we set end as the last index where we've seen s of and to get the last position where we've seen as of end we'll just read its value in the hash table in code we create last scene which is a hash table where -1 is the default value hash table where -1 is the default value hash table where -1 is the default value then a teach iteration s and last pause is just last seen of s of and at the end of the iteration we assign end to last then of s of and because end became the most recent position where we've seen as of and because searching and updating in hash table cost of one in average will get an off and time complexity better than solutions we've seen before and this is how we solve the longest substring without repeating character's problem by using sliding window and hash table techniques we've reached the end of this video if you want to support the channel like and subscribe or you can buy one of my algorithms and data structures related courses links are in the description see you in the next video
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string `s`, find the length of the **longest** **substring** without repeating characters. **Example 1:** **Input:** s = "abcabcbb " **Output:** 3 **Explanation:** The answer is "abc ", with the length of 3. **Example 2:** **Input:** s = "bbbbb " **Output:** 1 **Explanation:** The answer is "b ", with the length of 1. **Example 3:** **Input:** s = "pwwkew " **Output:** 3 **Explanation:** The answer is "wke ", with the length of 3. Notice that the answer must be a substring, "pwke " is a subsequence and not a substring. **Constraints:** * `0 <= s.length <= 5 * 104` * `s` consists of English letters, digits, symbols and spaces.
null
Hash Table,String,Sliding Window
Medium
159,340,1034,1813,2209
228
now let's go over question number 228 summary ranges you are given sorted unique integer array numbers you're going to be given an array that is composed of numbers they're all going to be sorted they're going to be unique and they're going to be all integers so whole numbers return the smallest sorted list of ranges that cover all the numbers in the array exactly so you want to return an array that has lists of ranges that cover all the numbers in our nums array that is each element of nums is covered by exactly one of the ranges and there is no integer x such that x is in one of the ranges but not in nums each range a b and the list should be output as so if the numbers are equal to each other we're going to just output one number and if they're not equal to each other we're going to give a range of numbers so a through with an arrow b now i think this is easier to see with an example so let's look at example one we are given our array which is again sorted unique and they're all integers in order for us to have a range of number so this one over here we need to have a consecutive number so what are consecutive numbers are like 1 2 3 and 4. and this is not a consecutive number so something like 1 3 and 4 because we don't have a 2 here so numbers that increment by 1 are consecutive numbers and obviously these two numbers will be consecutive whereas this whole thing is consecutive so let's try to see how our example works out well if we were to look at two adjacent numbers zero and one we can see that those are consecutive numbers we can see that one and two is also a consecutive number and is two and four a consecutive number well no it's not right because two increased by one is three and right now we have four over here so that's not a consecutive number so we want to have our ranges zero from two so we're going to add to our output zero with an arrow two and then it's going to be four and five well four and five is a consecutive number is seven also a consecutive number well it's not right because we're missing six so we're going to add four with an arrow five and we look at our last one and last one is just standing alone just one number so we just add that number and this is our output so if it's consecutive number we add it to the range of numbers if it's not a consecutive number we just have a standalone number now let's look at example two just to get a better understanding now we have our numbers and we have two well are these two consecutive numbers well it's not right so in our output we're going to have just zero and we'll get three and four are they consecutive yes now we look at two and three are they consecutive yes and now we look at three and four are they consecutive yes and we look at four and six well are they consecutive no so we add these ranges so that's going to be 2 to 4. now we look at 6 well a 6 and a consecutive number no right so we just add 6 and that is going to be 8 and 9 are they consecutive yes so we add 8 to 9 and we get our result so in order to solve this problem you have to figure out whether the numbers are consecutive if it is you have to store the lower bound which is 2 over here and then the upper bound which is four and then you want to add the arrow in the middle so lower bound with an arrow with an upper bound otherwise if it's not a consecutive number you're just going to add that single number whatever that is if you guys find this helpful make sure you guys like and subscribe thanks now let's implement our first solution and our first solution is going to have a time and space complexity of oven so as we talked about before what we're going to do for this problem is we're going to check if two adjacent numbers are consecutive if it's not we're going to just add that number in if it is you want to keep our lower bound and somehow check of our upper bound and add the range of numbers to our output so let's try to do that so first thing i want to do is i want to create a variable named output and this is where we are going to store our result and let's just return that over here now and next i want to create two variables one for storing lower bound and one for storing upper bound so let's do let lower is equal to the cell to null because we can't set it to zero because our lower bound might be something else so let's do no and let's do upper so that'll be our upper bound so here we're going to store our lower and upper bound now we want to be able to redo our range of numbers so let's create a for loop okay that's good so we're iterating through our range of numbers and we want to look at two adjacent numbers right so each time we're going to look at 0 and 1 and 2 so on and so forth now we have to figure out if our numbers are consecutive or not right so let's first handle our case when it's not a consecutive number if it's not a consecutive number we can just simply add the number to our output so how do we check if our numbers are consecutive or not well if the difference between the two adjacent numbers are not one it's not a consecutive no so let's handle that so if nums at index i plus one minus nums at index i if this does not equal to 1 it means that it's not a consecutive number so what we'll do is we will add that single number to our output so that's going to be output dot push and we're going to push in our current number and you want to convert this to a string so let's just add an empty string and let's try running this and you can see that it returned some numbers and i made a mistake here they shouldn't be minus one it should be just numbs because we want to iterate through the whole thing you can see that we are able to handle well the last three cases let me just have only one number or have an empty array and here we are somewhat okay we're somewhat done or you can see that five there's two five and seven well seven is correct but two and five is currently wrong because well it should have a range of zero to two and it should have a range of four to five and for our second example well zero seems good or four isn't because we want to have a range of two to four well six seems good and eight and nine should be eight to nine so this nine should be 8 to 9 with an arrow so let's just comment these out because we know that those are working so let's try to fix these two cases well in order to fix that we have to consider the other case when the numbers are consecutive so what we'll do is we'll use a else statement so this is the case when the numbers are consecutive now we have to check something we have to check if we have a lower bound if our lower bound is equal to null we want to save the current number to our lower bound so let's create an if statement so if lower is equal to null so if we don't have a value for a lower bound you want to set our current number to lower okay that looks good and there are a few more things and next we have to check well are the two pairs of numbers consecutive if it is if they are consecutive we want to keep looping right so let's create a check for that so if nums at i plus 2 minus nums at index i plus 1. if the difference is equal to 1 you just want to continue and what we're doing here is we're actually trying to find our upper bound so currently we are checking our current number with the next number which is 0 and 1. if this is consecutive it's going to obviously fail the first if statement and go to our else statement or does it have a lower bound if it doesn't we're gonna store that lower bound to our variable so it's storing this zero and then we check again is number at index i plus two well that's this number two over here right and then nums at index i plus 1 is this one well are the difference between these two numbers one well if it is it means that they're consecutive right so we haven't actually found our upper bound yet so right now we're just simply looking for our upper bound if the statement returns false that means that we found our upper bound so let's save our upper bound so upper is going to be equal to nums at i plus one and after we find our upper bound we want to add our result to our output so that's going to be output dot push and push in lower plus you have to give an arrow and we add our upper bound so that's going to be upper after we add it we want to do two things we want to reset our lower to null because later if we keep the value of our lower bound it's going to keep using the first number that we saved so we want to reset it and let's look at our example well you can see that it's somewhat looking good we have our range of numbers so zero to two we have four to five and we have seven but you notice that we have two here and the five here and well that's because after we add or save our upper bound that's at number at index i plus one right so we are starting again from this number and comparing these two numbers well that's not what we want right so what we have to do is we have to actually increment our number by one or our index by one and right now you can see that all the examples are looking good so we were able to get rid of these single numbers so it was two and five and again that's because well we added number at index i plus one so after we add it and after we add our range of numbers we don't want to start again at two we want to start at the next number in line so we want to start at four so we want to increment our index by one now let's go over our code one by one line by line to get a better understanding and for this example let's use example two for our code review so we want to have this is our array now first thing we do is we create a variable named output we create two variables lower and upper and this is where we are going to store our lower and upper bound now we create our loop to read through all the elements in our array and next we check well are the numbers consecutive so we look at two adjacent numbers so right now i is equal to zero so we look at nums at index i which is zero and i plus one which is two well are the difference between them not equal to one well they're not right so what we do is we just simply add our current number to our output and let's bring our output here so we add our zero so we're not gonna run our out statement because our if statement evaluates to true and we go on to now our next iteration and our i is one now so we're at over here so we look at two adjacent numbers again two and three well is two and three not equal to 1 well it's not right because they are consecutive numbers so this is sigma is going to fail so we look at our else statement and we look at our first statement and is lower equal to null well it is right so what we do is we store the current number to our lower and our current number right now is two and we hit our next statement which is this if statement and we check our numsat index i plus one and num z index i plus 2. well that's 3 and 4 right well are the difference between those two numbers 1 if it is it means that they're consecutive numbers so we continue we stop and we don't run this whole code and now our i is at three well we look at two adjacent numbers three and four well obviously this if statement is going to fail we look at our else statement well do we have a value for lower well lower is not equal to null that's equal to two so this is statement fails and we look at our next if statement and our next if statement is going to look at four and six are the difference between two numbers one well it's not right so this statement is going to fail and that means that our two numbers are not consecutive so we run this whole line now we save our num za index i to upper and what's our number at index i well it's four right so we say four and we add our range of numbers so that's going to be two with an arrow four and we have to reset our lower to null because if we were to have a value that's not null for lower it's going to keep using this two and we don't want that right we want a new fresh range of numbers so this is going to be null now this is the important part you have to increment i by one and if you remember when we didn't we had the number i think it was two here and a five here and obviously we don't want that duplicate values right so that's why we have to add one so after we increment it by i our pointer or i is going to be over here so we compare these two numbers and we know that these are not consecutive numbers so we just add in r6 and then finally we just compare eight and nine and we just add that range and get our final result now let's go over another solution and for this one the logic is going to be kind the same but it's going to keep not the number itself but the pointers for the numbers so for example if you were to look at our example two when we have a range of numbers or actually let's look at example one when we have a range of numbers well it's zero one and two rights because they are consecutive numbers well we want to have a pointer to this zero and we're going to have a pointer to this too so that we just get the element at that respective pointer and then just add the range so let's try to implement that first thing is our output this is where we store our result next is going to be let's just return our output here first all right that looks good and i want to create a variable named i and this is going to keep the track of the lower bound so that's the index of the lower bound and let's create our for loop to iterate through all the elements in our nums array all right now i want to check if my numbers are consecutive if you remember from before what we did was we checked if they're not consecutive first right but here we're going to check if it's consecutive what we do is we just keep going so if and i just made a mistake here this should be j because we have duplicate indexes so that's not going to work let's change it to j all right that looks good if our next number and if it's equal to our current number plus one it means that they're consecutive numbers right so if it's consecutive what do you do we just stop our loop and just continue and now it's going to be our else cause well if they're not consecutive so this should be nums right that looks good you want to check for a few things so if i is equal to j so if the elements are pointing to the same thing it means that it's just one number it's not a range of number so if it's not an original number we want to just push in that number only we just have to convert it to a string so output that push we get our number index i and let's just add an empty string to make it into a string and it should be nums and then now we have to check our other case when it's a range of values so else we want to just add in the range of number so i'll put that push and well the lower bound i said that is going to be our number at index i so let's do num index i and we want to add in our arrow and that's going to be nums index j all right that looks good but you do see a problem with the solution right it's keeping our lower bound for all the instances and that's not what we want and when we did our first implementation what we did was we reset our lower bound null but here we have to reset our index so how do we do that well our index is going to be the upper bound plus one so the element after the upper bound and if you remember from our previous solution after we reset our lower bound to know we incremented our index by one so we need to do the same thing so that's going to be index lower bound is going to be equal to j plus one because remember j is our upper bound and we add one so that we avoid the duplicate numbers and now we can see that we have our correct result so let's just go over this code really quick all the logic overall itself is the same it just we tweaked it a little we create a variable named i and this is our lower bound and you can rename this to lower bound or lower if you want and we iterate through all the elements in our array and j represents our upper bound and if our current number some nums at index i plus 1 is equal to the next number well that means that they're consecutive numbers right and if you remember from before if it's consecutive you want to just keep looping on to get the upper bound if this evaluates to false it means that we found our upper bound and we check we either found our upper bound or it's a single number that we have to add and if the indexes are equal to each other that means that it's pointing to the same thing right and if it's pointing the same thing it's just one number that you have to add so we convert it into a string and add the number otherwise what we do is we get the lower bound so numbers at index i we add our arrow and we get our upper bound and add that range of number into our output and finally we have to reset our lower bound so that it points the correct place and it's going to be upper bound plus one so it's the number that comes after our upper bound so for this one our open bound was 2 and we want next number in line to start our range so that's our 4 over here and finally we return our output and get our result if you guys find this helpful make sure you guys like and subscribe thanks
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
1,010
hey guys it's iran with another coding interview tutorial this one has been requested by subscribers so thanks for the suggestion i think it's a really good one so i hope you enjoy it now this question is called pairs of songs with total duration divisible by 60 and the description goes like this you are given a list of songs where the iris song has a duration of time and i seconds we want to return the number of pairs of songs for which their total duration in seconds is divisible by 60. so formally we want the number of indices i and j such that i is less than j with time at i plus time of j mod 60 equals zero so if you're not familiar with this mod operation this percent sign here um all it does is return the remainder of a division so if it returns zero it means that the division of this sum by 60 leaves 0 remainder which means this sum is a multiple of 60. now if you look at the first example we get this array of integers the output for this array should be 3 because there are three pairs of numbers that add up to a multiple of 60. this one adds up to 180 this one adds up to 120 and this one to 60. so that's three pairs now in the second example uh the output should also be three because all three possible pairs add up to 120 which is of course a multiple of 60. okay so let's first solve this as naively as possible and go from there so in this example we would start with the first element and check it some with all the others right and then we'll move on to the second element and check it some with all the others as well and then the third and we're done so the first pair is going to be 20 plus 40 which is 60 mod 60 is 0 which satisfies this condition so we increment the counter and move on the second pair is 20 plus 150 which is 170 mod 60 is 50 not zero so we move on without incrementing any counter 20 plus 100 is 120 mod 60 is zero so we increment the counter 120 mod 60 is 10 140 mode 60 is 20 and lastly 250 mod 60 is 10. so in total we counted two pairs that satisfy the condition so our return value should be two which is the correct answer now this algorithm translates very easily into code um we will just iterate over the pairs like this just a couple for loops now this uh j should actually start from i plus 1 because if we already counted this pair we don't want to also count this pair right so this is why we need to start from i plus 1 so we don't count duplicate pairs now if the sum of the pair mod 60 is equal to zero we want to increment some kind of counter right we also of course want to initialize this counter and of course we turn it okay so this will do the job but the problem is that the time complexity is going to be of n squared because of these nested loops here right so uh of course we're going to want to optimize it but before we do i want to make our lives a bit simpler uh so notice that this 60 here seems like a pretty arbitrary choice from the author of this question i mean i can't really think of anything special about the number 60 right so i bet if we solve it for a smaller number like 4 the solution will still apply to the original 60. it's just so much easier to think of examples and visualize operations on smaller numbers so let's just replace it with fours for the time being and the second change that i want to make is just um give these guys names because i don't want to have to say time and i in time and j all the time okay so let me just call this guy x and i'll call this one y okay so what exactly is this code doing we look over each element x and then in this inner loop we search for good matches for x right so if x plus y mod 4 is 0 we say that y is a good match for x and we increment the counter now we're not going to be able to get rid of this uh outer loop because we are always going to have to look at each element at least once right but we would like to replace this in a loop with something more efficient now this loop is performing a search on an array and we know that searching a hash table instead of an array is going to be much faster right so what if we kept a hash table that had all the values we've seen already and then search that table instead of the array so in this example at the point where x is 7 we've seen these values already so they'll be in the table with their count now searching this table will take average constant time which is awesome but what exactly are we searching for if x is seven do we search for one or four uh five or any of the other infinite possibilities that would make a good match for seven it's clear that we need to reduce the number of possibilities for each number x we wanna search for one number only so let's look more closely at this line now in general this mod 4 operation has only four possible output values 0 1 2 and 3 because these are the only possible remainders when dividing a number by 4. we can think of this operation as a cycle for example to compute three plus two mod four which is five mod four we can take five steps one two three four five and we landed on one because after one full cycle we had one more step left and this is exactly the definition of a remainder right how many steps we have left that do not add up to a full cycle in this case we had one so wherever we land on this cycle would be the remainder if we want to satisfy this condition we would want to land on zero now let's think about the individual components x and y let's say that after x steps we landed on 1. in this case x could have been 1 or 5 or whichever number x such that x mod 4 is 1. now if we want to get back to 0 at this point we would need y to complete the cycle for us so y could be 3 right after three more steps we're back at zero but now that we're here we can also take another four steps and any multiple four steps so basically we don't care how many full cycles y makes we only care about this number the remainder so if x mod 4 is 1 we would have to pair it with y such that y mod 4 is 3 plus 1 is 4 which is a full cycle and it ensures we do not have any extra remaining steps meaning 0 remainder in the same way if x mod 4 is 2 y mod 4 would have to be 2 and if x mod 4 is 3 margin 4 would have to be 1. so the more general rule would be that the sum of remainders has to be 4. one special case is when x mod 4 is 0. it's a bit different because we're already on zero and we don't need y to compensate we want to stay exactly where we are so why mod four should be zero as well so now that we have these two rules we can think of the algorithm we know now that we make matches based on remainders only the numbers themselves do not matter so instead of keeping a hash table that keeps track of the count of the numbers themselves we can track the count of remainders that we've seen so far so at this point where x is seven we will have these key value pairs in the table because we've seen one number with remainder zero and two numbers with remainder one the remainder of x is three so based on this first row we know that good matches for x would have remainder one so we look for this key in the table and find that so far we have seen two numbers with remainder one it means that we found two good pairs so we add them to the counter now we also add the remainder of x to the table before moving on to the next element so our x is now four the remainder of four is zero based on the second rule good matches would have a remainder zero as well so we checked the table to find how many numbers would we made the zero we've seen so far we've seen one so we add one to the counter and of course we increment the count of the current remainder in the table our last element is one its remainder is one so good matches would have remained a three we search three in the table and see that we have seen one number with remainder three so we add one to the counter and we know more elements to go we are done and our output is four which is the correct answer now notice that we can easily swap these fours back to the original 60 and the solution will still hold we didn't rely on anything specific to the number 4 so any other integer will work just fine now i think we're ready to write the code so let's do that in the algorithm we had a hash table called rem to count that would map remainders to their count but because there are only 60 possible remainders 60 possible keys to this table we can actually just use an array so this could be a vector of ins of size 60 and then i want to initialize it to zero because these are the counts right now let's get rid of this inner loop because that's the part that we replaced with the hash table lookup and what we want to do is for each element x we want to compute its remainder now based on the rules if x has a remainder of 0 good matches for x would have remainder zero as well so we look at the table at uh index zero and that is what we want to add to our count and then for all the other cases good matches for x would have remained that adds up to 60. so for all the other cases we want to add to the count everything that we have in ram to count 60 minus ram and then of course either way we want to increment the counter of the current remainder okay so that should work the time complexity of the solution is going to be o of n because for each of the n elements we perform a constant amount of operations and then the space complexity is going to be o of one because the only extra space that we're allocating is this uh vector and its size is 60 which is a small constant so we can say that the space complexity is constant okay so let's try to submit this okay so that's a success and we are done with this one if you have any questions or requests please post them in the comment section and if you enjoyed this video don't forget to like and subscribe thank you for watching and i will see you next time
Pairs of Songs With Total Durations Divisible by 60
powerful-integers
You are given a list of songs where the `ith` song has a duration of `time[i]` seconds. Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`. **Example 1:** **Input:** time = \[30,20,150,100,40\] **Output:** 3 **Explanation:** Three pairs have a total duration divisible by 60: (time\[0\] = 30, time\[2\] = 150): total duration 180 (time\[1\] = 20, time\[3\] = 100): total duration 120 (time\[1\] = 20, time\[4\] = 40): total duration 60 **Example 2:** **Input:** time = \[60,60,60\] **Output:** 3 **Explanation:** All three pairs have a total duration of 120, which is divisible by 60. **Constraints:** * `1 <= time.length <= 6 * 104` * `1 <= time[i] <= 500`
null
Hash Table,Math
Medium
null
212
hello everyone welcome to day ninth of october liquor challenge and today's question is word search two in this question we are given a grid of size m cross n where each cell has some characters associated with it we need to identify the number of words that are also given to us that lie within this grid and in what all directions can you move you can move in four directions top left bottom and right this is an extension of word search one that we solved two days back there in that question only a single word was present however in this question there are multiple words that we need to search and once we have the list of those words that lie in this matrix we need to output them so seems like a typical extension of that question and i'll talk about how are we going to solve this approach in the presentation section so without much to do let's look at the ppt word search 2 lead code 212 it's a hard question on lead code but if you solved yesterday's two questions one the basic implementation of tries and other one word search one then i would say it's a medium level question because we are going to use the same concepts here it's a time to implement those concepts so let's try and look at the first possible solution word search one which is an extension of this question that we saw two days back so the naive approach that comes to everyone's mind when they read this question is to search for all the given words in this matrix one by one and once you identify whether that word is present into in your matrix then you add it to your answer data set this is a typical approach that will cause that may cause tla issues but i'll provide the solution that won't cause dle issues so i won't recommend the solution because the time complexity of the solution is way higher let's assume there are n words that we need to search for and size of the matrix is l cross p then the total complexity would become n into l into p so this is of order 3 and we are not very happy with this complexity how can we improvise this we can improvise this using this question that we solved yesterday implement rise let's see how even before starting the details of the algorithm i am just making one difference to the try node from the one that i specified yesterday i used a boolean flag is word to identify whether the current node is a leaf node or not whether it's a terminal state or for a word or not instead of this what i'm going to keep i'll cut this up i'll keep a string and it will store the terminal word at that particular index where the termination is actually happening for example let's assume the word is e a t so how would the trine would be formed will have e pointing to a pointing to t and at t we will store the complete word e a t instead of is leaf or is word boolean flag so that we know that this is the termination of the word and we also have the word in place this is the advantage that storing the string at the terminal position will give us that we don't need to keep track of what was the word that we hydrated over now let's look at the solution i'll be using the same approach that i used yesterday to implement tries so the first thing that i'm going to do is to build the tri data structure using all these four words that i need to search in the matrix so let's start building the try data structure we'll create a root and the first character in oath is o so this is the new node and it will at o a new node will originate and it will point to a something like this and from a will go to t something like this and from t will go to h and attach we will also create a new node and at this particular node if we will store the complete word which is oath let's continue the process for the for next word we have p so this is our root node a new node will originate from p and it will go up till e from e will have a and from a will have another node where we will store p let's move ahead we have eat and from eat e we will create a new node and it will have a it will have t and rt will create another node that will store eat next is rain so we'll start with r will store a will store i will store n and from then we'll have another node that will store rain so pretty good so far we have built in the complete try data structure using all the input words that were given to us now comes the interesting case how are we going to use this data to actually search for all the words present in the matrix so let me just change the color of pen for better clarity and let's start the iteration uh the first character that we see is o and uh what we are going to do we will jump on to the other character in our root node what do you see there exists a node ato awesome that means we found a word so we will update it to visit it somehow we are going to keep track that we have visited this node and we are not going to use this what we will do we will search for the next character in all the four directions so we'll go up we'll go right we'll go towards left we'll go towards bottom obviously we'll keep track of the corner cases and towards its right we have an a character so what we are going to do we will search this a character in the try node do we have a link from or to a yes it does exist pretty awesome so we'll mark it as visited again we'll go in four directions uh right bottom left and up is the boundary conditions ignored left is already visited ignored there are two possible ways a towards a and towards t so let's move towards a first uh do we have an a originating from this a no it's null so we are pretty safe we'll abort the process we'll go in the bottom direction we see t so do we have a t node starting from a yes we have so we'll jump onto two again pretty good and uh we will mark this as visited that we have visited this node now we'll repeat the process we'll go in all the four directions first towards a then towards bottom then towards left and then towards top so uh let's see towards a from d do we have any link at a there is no link at a so we will skip this so we this control will return next we have its h so we'll go to h and uh what do you see we'll mark it as visited and that age we saw that the word is also complete there is an entry oath present at h that means this is a terminal state of a word what we are going to do will mark this word in our answer data set so oauth gets added in our answer data set uh also you can move in the eth direction this particular direction towards the left e doesn't exist from t so we'll avoid that process and uh once you are done iterating in one particular direction you will also you need to backtrack it as to mark it so as to mark it as unvisited for the next iterations to happen so we are slightly using the back tracking concepts here as well but if you are not able to get that don't worry i'll explain it in the coding section just remember that by light rating through the dfs approach once we have marked a node as visited we need to unmark it as unvisited for the next iterations to happen properly because there could be cases that we have and we have a word of getting formed as e another word getting formed in this direction so this character will be present and considered in both these words in the hypothetical scenario let's assume there's the word stretched in this span there is another word stretched in this span this e character can be treated in both the words that's why we need to mark it as unvisited for the next iterations to happen and in this way we'll start the try search uh starting from each and every node in our matrix each from each and every cell in our matrix and we'll try to build or search for solutions that exist in the try node you can draw the same thing on pen and paper and walk through the rest of the iterations it's pretty simple and straight forward nothing much to worry about just start the iteration starting from each character in your matrix and try to look out for words now it's time to look at the solution part i'll be explaining the both the approaches this tribe plus dfs approach and extension of word search in the coding section so stay tuned do watch it up in the first approach i'll be using the extension of word search problem i'll exactly do the same thing as i did two days back it's just that we'll be searching for each and every word that is given in the input data set i have created a set of string hashtag that will store the answer nnm variables are storing the grid length and column length uh and in case my n happens to be zero or m happens to be zero i return an empty arraylist otherwise i go and start the iteration i loop over all the input words i check uh if uh my of starting word character happens to be equal to the board at i comma j length i start the dfs operation and if my ds operation says that this word is present in the board i add it to my result i do it for all the given words possible and in the end i return an arrow list using the hashtag that i created above hashtag is used here so as to remove unnecessary duplications getting added into my answer next uh let's look at the helper method the dfs helper method it's exactly the same that we discussed two days back we have the input word we have the length we have i comma j we have visited array and we have the chest we have the board if my length happens to be equal to the word length i simply return true from it otherwise i'll go and check for the boundary conditions if my current character in the board at i comma j index is not equal to the word a character at the given index i simply return it back up to false or if i visited the current node in the past i simply return false from it otherwise i mark it as visited i store the result for by moving in all the four directions performing across in all the four directions if my result happens to be true it will return a true from here and once i'm done with the iteration starting on a particular node i mark it as unvisited so that it doesn't corrupt for future cases let's write this up accept it as i told before starting the question the time complexity is not that great can we improvise it the answer is yes how let me just show that to you guys let me just comment this up i just copy pasted the solution that i solved an year back in february 2020 and this is a solution and let's just walk through it so uh as i talked about that we are gonna replace the boolean is lee for is word variable with the word itself so as to identify that it marks the completion of the complete word and we also know what word was it's the rest of it is exactly same to what we discussed yesterday it will have children of size 26 that represents 26 english characters and let's walk through the core method we go and uh write find words method it has two parameters board and words given to us we create an error list of result we build the trinode using words and we store m and m that are the number of rows or number of columns in the input board we start the iteration and we perform dfs operation dsl operation will be responsible for storing all the words found in the tri root in our resolved data set and in the end we simply return the result data set let's walk through the two helper methods build try and dfs so the first one is build try because it's easier to understand it's exactly same what we did yesterday so i would highly recommend you guys to watch the two solutions word search and implement try it will be really helpful to actually see the practical implementation of both these both those questions so as we have created a new node root and we start the iteration one by one for each word we check this p variable is for i trading over all the characters that are present in the try so we start the iteration for car c word dot 2 car array i search for the index if my p dot children index is happens to be null i initialize a new tri node i update p to p dot children at i for the next iteration to happen and once i have completed a particular word or i traded a particular word i assign p dot word to w my current word into consideration in the end i simply return the root of the try that i have built so it's exactly same i hope you guys are able to follow this and now let's look at the dfs operation because it is something that is very interesting so this dfs method is responsible for finding out all the words of the tribe that are present in the matrix and it will store them in the result list so let's understand the parameters that we accept in this matter the first one is the board itself the second one in the i comma j index the third one is the root of the trinode and the fifth one is the data set that will store the result so the first and the foremost condition is to check if i have visited this particular entry in my board in the past or not and how are we going to do that we can use an extra a boolean variable or data set of m cross n to actually store this otherwise we can exploit the board itself and if the character on the board happens to be a semicolon that signifies that the character has been visited in the past because i am setting it in the lower in it in the lower part of the code so i'll come to it in the later section let's say assume that if you see a semicolon character on the board it means that you have visited the current node or if my p dot children happen at c dot minus a index at this particular index happens to be equal to null if any of these two conditions are met that means uh we have to abort the process and return back uh our building stack otherwise if my node is found that means p dot children at this particular index c minus a is not equal to null i proceed for the next iteration i update p to p dot children c minus a at this week i could have stored this index at a particle in a particular variable but never mind and while iterating to the next node i check if p dot word happens to be equal to not null that signifies we found a particular word in my try and we'll add it to our result and simply update p dot word to null so that we don't add it multiple times while iterating through any other word just to de-duplicate stuff in our rl list you de-duplicate stuff in our rl list you de-duplicate stuff in our rl list you can use hashtag as well but either ways you can do any of these otherwise now i go and update my current node to visit it i update the board comma i comma j to a semicolon and i start the iteration in all the four directions we also stored what character was present on the board and once i am done with the iteration in all the four directions i update my board to unvisited and update the same character that was initially present on the board this is part of the backtracking approach this is part of the dfs approach and this is part of the basic try approach so this question is an allegation of all these three concepts i hope you enjoyed the solution and let's just try and submit it up accepted it is it has reduced to 71 milliseconds which is 85 faster and memory space is also pretty good this brings me to the end of today's session i hope you enjoyed it if you did please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded i'll see you tomorrow with another fresh question but till then good bye
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
171
hello guys we are back with another lead code problem and today is day 22 of february let's see that today's problem and the problem is excellency column number it's a fall into the category of easy and it's a highly like ratio so let's directly dive into the question what actually question ask so you have a given and string column titles that represent the column title as appear in the excel sheet what's your duty you have to return its corresponding column number so that's pretty much forward and it's a daily basis use thing if you use the axle seats you know very well so let's understand uh how to map in the column title in the excel sheet so call a denoting the column one be denoting column two such that z denoting column 26 and after a e actually denoted 27 did you get it after z what's actually come after that a z is come after is that eb is come and as that thing is repeated so on so if you notice one thing here it's a similar to the binary digi binary decimals number after 1 2 g 9 but it's actually repeat it again come 10 or if i am right here 0 it make more sense for so on nine after nine what happens uh one zeros come two zeros come three zeros come for zero come i'm sorry one zero come one come until one nine after the one night what's come after the one night two zero come and two one come and so on and here i write double zero it make more sense and if i write zero one so it make more sense zero to zero nine so that thing happens so how can we know but in that case binaries form uh we needed 10 after 10 it enhanced the digit in that part so that's a similar approach but in this case after 26 step my character is gonna change so how can we it's a it's pretty much straightforward let's write the code then you understand what i'm actually on to try to explain you so let's make a some variable call num variable in which initially initializes 0 and i'll make a auto let's uh see and let's change this name for our sake of this let's write it as not make any sense so but i'm here actually do and actually take this i'll just take this initially let's say i'm talking about this so i'll take the same and after taking the same what i'm going to do and multiply it my sum i'll let it with some sorry i added with 76 initially my if that's the case if my sum is initially zero so 0 into 26 is gonna zero plus and i'm going to add this value how can i add this value for adding this value c containing the character of this and after i what i do i just minus this element from the e and add it so it's going to add into the same let's see if i talk about the same in my c is a minus a is 0 plus 1 so 26 into sum is 0 plus 2 1 is 1 my sum containing 1 and in that case my output is 1. let's talk about the another case too for talking about another case this a b let's talk about that so my it's first and foremost go to the e and that's a similar approach i do if i traverse if my current traversal is on e my sum will be one in that case you know about that because i have already done here and after knowing my a is 1 when i come to b after reaching to b what's my duty i'm multiplying my 1 into sum into 26 my sum is currently 1 so 1 into 26 it goes to 26 plus and my b have the value of 2 because b minus a is 1 plus 1 is 2 so 2 my total summation is going to be 28 in that case so that's a pretty much straightforward but here what here i am only changes i'll change this multiply into 26 times if it's uh by is similar as the binary decimal form sorry decimal form decimal number so let's submit this code guys okay ahead sorry for that it's not a column let's make it some for our second piece i have to change with call number so that's acceptable so if you have any doubt let me know in the comment section i resolve your doubt as soon as possible until then keep grinding guys
Excel Sheet Column Number
excel-sheet-column-number
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnTitle = "A " **Output:** 1 **Example 2:** **Input:** columnTitle = "AB " **Output:** 28 **Example 3:** **Input:** columnTitle = "ZY " **Output:** 701 **Constraints:** * `1 <= columnTitle.length <= 7` * `columnTitle` consists only of uppercase English letters. * `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
null
Math,String
Easy
168,2304
51
Ki A Hello Everyone Welcome T20 Second Aap Nahin Daal Introduce Question And Begin From 10pm Problems Very Fierce Interview Fail Subscribe Problem in the Video then subscribe to Ki Ki Ki Ki Patient Se Start Aircraft Place In This Alone In The Chest Size 30 Channel Blurry Si Ki Also Chew Young Vansh Replace Mirchi Problem Subscribe My Channel Subscribe Must Subscribe To That Slacks Understand Do Vaikunth Anil Subscribe And Subscribe To My Channel Ki Yudh Subscribe Subscriptions E Want Can Kill That All Everyone At This Place Across The Mrs Idli Directions In Which Till Or Its Channel Subscribe A Fold In The Napkin Approach For Its True Will Place Between More Subscribe Subscribe Now Subscribe Video Don't Forget To Subscribe And Subscribe Meet Sat For This YouTube Channel Subscribe Button Middle Age 9th Tight Oxidant Previous Light Soil For The Meeting That You Know It Or Not Continue By Pressing Subscribe Button The Video Then Subscribe To 116 Talk About How To Check Weather Or Current Sizzling Position Or Not That Selectors Umda Vihar Player One Place In This Particular And Listen To the Tunes and Subscribe Post Subscribe to a Column Which Makes Satisfactory The Next Been Crossed The Way in Which Puberty More Subscribe to Andhra Situation Andhra Situation Andhra Situation Snow Queen is Place Akrosh Disposition and This Position Was Not Doing in the Opposite Direction Hair and Roots Rotting Hormone Thursday Must Subscribe The Channel subscribe our YouTube Channel and subscirbe Note Hai Next Drown in the River Avoiding This Cyclone Cycle and a Good Will Start from All Over India and Will Immediately Following Countries Telecom Department - One Following Countries Telecom Department - One Following Countries Telecom Department - One Plus One Tell the Time You Want To Deal With This Talk About The Question More Leaders Like Share Subscribe And Subscribe To Ardhya Left Boundary So Difficult To December 04 - Awal Jo Hair Record Clear - To See - Sudhir And Home Subscribe To Report Singh Dacoit Dare To Create I Answer Site Which Nothing But List of Classification and Agree Vid Subscribe subscribe and subscribe the Channel Please subscribe and subscribe the A Slack Talk About Replace Pin Third Share A Model To Talk About This Written Statement Bill Talk About This Point Airplane Singh I Am Now And Trying To Listen All the columns for that particular settings Rohit ko long tilak robes and difficult for the current position more subscribe The Channel subscribe kare the black pepper time zone distic were killed in the same manner for the next to five eight subscribe The Video then that and What is my ringtone condition for this record video intense penance and update set with now school well current scenario in the stock subscribe to e will not metered returns forget midnight subscribe enrollment and subscribe Video subscribe now subscription will start from - Unmukt S Ki start from - Unmukt S Ki start from - Unmukt S Ki Ek Baar With Every Hydration Column Plus Mouni Cost Of Badri Das Porn Tube Porn In The Land Of The Question President Mirwaiz Similarly Aaj Bhi Agar Lagna Uday Ko 180 Degree Performance Will Start From Minus One Column From Padhaan Withdrawal Subscribe To E Will se desperation to render cute hai the soul will return prominent muslim acid servi knowledge subscribe ki slammed the summit hai akshar trade come who want david to like share and subscribe 200 chunnat under good night prayer meet kar do
N-Queens
n-queens
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**. Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively. **Example 1:** **Input:** n = 4 **Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\] **Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above **Example 2:** **Input:** n = 1 **Output:** \[\[ "Q "\]\] **Constraints:** * `1 <= n <= 9`
null
Array,Backtracking
Hard
52,1043
53
hello guys welcome to study algorithms and today we would be looking at finding the maximum sum contiguous sub array first we would understand the problem statement and define a contiguous sub array then if you try to solve it in a naive way and see what problems could occur next we would optimize the solution and discuss cadine algorithm followed by a dry run of the code so let us dive into the problem to be extracted with this problem we first need to understand what a sub array is any array that can be formed by using the elements of the array itself so given this array you can form various sub arrays one of the sub areas could be formed using -5 + 6 one of the sub areas formed using -5 + 6 one of the sub areas formed using -5 + 6 one of the sub areas could be form using - 3 5 and -6 but could be form using - 3 5 and -6 but could be form using - 3 5 and -6 but this problem talks about a contiguous sub array with a continuous sub array it's special property is that all the elements are next to each other so minus 5 comma 6 would be considered as a contiguous of array where as minus 3 comma 5 comma minus 6 is not a contiguous sub array as per the problem statement you need to find out the maximum sum possible that can be formed using all the possible contiguous sub arrays let us have a look at some of the possible contiguous of errors that you can form with this example you can have arrays like note that all of these are contiguous sub arrays and each of these contiguous Cerveris has some so the sum of the first sub array is minus 7 the sum of the second sub array is minus 1 and the sum of the third sub area is 3 so you need to find out a sub array that exists in this example that is contiguous and has a maximum sum I've already worked out this example for you and in this case the maximum so very possible is this and it has a sum of 7 so upon running your program your code should output the answer 7 let us see how you can go about following it as a good practice we would first try to solve the problem and then we would try to optimize it so a knife approach to solve this problem would be just find out all the possible contiguous web areas find out this sum and see which contiguous sub-array have and see which contiguous sub-array have and see which contiguous sub-array have the maximum sum let us try to see what could happen if we try to go with this approach so let us take up each of these contiguous sub areas one by one we start off with our array minus six and then we form all the contiguous sub areas possible starting with the first element now we evaluate the sum up till now the maximum sum possible is zero let us try to start our array from one now evaluating the sums so we got a new sub maximum sub array and that looks like 1 comma 5 but wait we need to keep looking forward starting off with 5 and then evaluating its sums and last but not the least we have the element minus 2 and it some would be 2 so out of all of these possible sub areas we can see that the maximum sum is formed by this sub array so our answer should be 6 but can you see the problem we would be having by this method in just an array of size 4 you already have 4 7 9 and 10 you have 10 different sub areas possible think about the case when you have array of filled size 100 or you have an array of size 1,000 then the number of contiguous sub 1,000 then the number of contiguous sub 1,000 then the number of contiguous sub arrays would just explode and you would realize that this solution is not efficient in fact the complexity of this solution is order of n square can they optimize this let us try to think about it to optimize this problem we need to think a little differently instead of going forward what if we go backwards and try to come up with the solution so I would have tried to look at element number 3 and then try to form all the possible contiguous some areas in the backward direction so let me just try to create all of these arrays and now evaluating their thumbs if you see the maximum possible contiguous sum of sub arrays is 4 over here but this problem does not end over here let me just try to form all the possible sub arrays that are ending at element number 4 so all the some errors would look something like and their sums would be so for all the sub arrays that end at element number 4 the maximum contiguous sum is 1 but do you really think we need to calculate the sum of all of these sub arrays if you look closely we have already evaluated the sums of all of these some errors and they can be found over here so why not just use these to evaluate the maximum sum possible for the contiguous um sub arrays that are ending at element number 4 so let me just try to use these sums and then evaluate my maximum possible contiguous um I am just using element force for now and I would be using my already evaluated sums to find the new result now calculating their thumbs and hence you see the maximum possible contiguous um ending at element number 4 again comes out to be 1 so what does this tell you if you start from the beginning and go all the way up to the end and apply this technique at every element and if you keep a track of all the maximum possible sums that you find out then at the very end you would know what is the maximum possible contiguous um let us just try to take this example one step further I will be populating element number five and using the result I already obtained now calculating the thumbs in this case the maximum possible contiguous sum is 2 the approach we are using over here is called memoization it means that we are already using our derived Revolt to evaluate our further problem this is a very common example of dynamic programming and as some of you may have guessed this is also called as the contains algorithm let us try to do a dry run and see how this exactly works in our code to start off we initialize two variables the value max so far would be storing the maximum possible sum of the contiguous survey race and the value current max would store the sum of the contiguous sub array at a particular position next we run a loop from I equals to 1 up till the length of the array to update the values of current Max and Max so far so for the first iteration I equals to 1 the values would be updated something like for I equals to 2 for I equals to 3 going forward with I equals to 4 going next with I equals to 5 going forward with I equals to 6 and lastly going forward with I equals to 7 so after all these iterations are complete we can see that we have our Val maximum value as 7 and this is an answer please note that this algorithm runs in order of endtime and occupies order of 1 extra space we saw how we can use memoization to reuse the result we have already professed and find a solution in order of endtime this is a classic example of a sub optimal structure you can find the link with the problem in the description below and please feel free to comment below in case of any doubts thank you
Maximum Subarray
maximum-subarray
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_. **Example 1:** **Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\] **Output:** 6 **Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6. **Example 2:** **Input:** nums = \[1\] **Output:** 1 **Explanation:** The subarray \[1\] has the largest sum 1. **Example 3:** **Input:** nums = \[5,4,-1,7,8\] **Output:** 23 **Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
null
Array,Divide and Conquer,Dynamic Programming
Easy
121,152,697,1020,1849,1893
108
welcome to mazelico challenge today's problem is convert sorted list to binary search tree given the head of a singly linked list where the elements are sorted in ascending order convert it to a height balanced bst for this problem a height balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ more than one so we could technically take this linked list and make this the head and just say okay write tree negative three write tree zero and have this like big line here uh that technically would be a binary or a tree a binary tree but it's not balanced right so that wouldn't count we want it to be completely balanced uh and not different more than one so the key thing here if we were to build this binary tree with this linked list we need to find the midpoint because that's always going to be the head uh the root node like what we would do is write some sort of recursion and say find the midpoint make that the head and then create subtrees finding the midpoint here that's going to be left and find the midpoint here to make the right node and make subtrees down the line right but this is a linked list uh we're not gonna be able to like just jump around um but we do know it's sorted right so um what we could do and what we will do is instead of building this into an array we will get the length if we have the length we could do a binary recursive call or we can figure out where we need to end our recursion by doing a binary search so i'll show you what i mean what we'll do is first create uh we need to first generate the length of our linked list and to do that we'll just get curve head and we'll say while cur curve equals codon next and increase our n next thing we need to do is write some sort of recursion so to do this what i'll do is use the start and end uh to recursively call and the base case would be if the start is greater than n then we know this is a single node and we can return a none or this node doesn't exist so we can return none here now basically what we'll do is build our substring here starting with the left side then define the root and then go to the right side what we'll do is say okay left is going to equal recursion well first we need to figure out what the middle is just going to be start plus end divided by 2. and the left will be let's see start to mid minus one right now we need to define our root node and this would be tree node but we don't know what the value is here right so we'll leave that for now and we'll say okay root dot left is equal to left and root dot right is equal to recursion mid plus that's right okay so what we'll have to do then is we return our recursion zero n minus one and uh this would be something like this but the tricky part is to figure out well what do we generate here with this tree node so if you think about it if we would do this recursion it would continue left and would go all the way to the left most side right so what we can do is just have some sort of global variable we'll say okay self.head is equal to head and okay self.head is equal to head and okay self.head is equal to head and we'll make that equal to the root note here we'll say self.head dot value and create a tree node right there and we'll also need to move ahead then our self dive head next and this way when we um go to the right side it makes sure that it's going to be the next one and this tree that we're generating like this order should generate a balanced binary tree so we got to return our root here so at the very end this should return the head of the root should be the mid so let's see if this works okay so it's different but if we just look it's like 0 negative 10 5 and then negative 10 negative 3 and then 5 9. so it is a binary search tree and it's bounced it's just kind of in a different order so let's submit that and there we go accept it so this is all of n time and i believe it's one space although if you count the binary tree itself i guess it's solvent space as well now this was not easy um i knew it had something to do with finding the midpoint and doing a recursion but i think the trickiest part here was figuring out like how do we actually get the values um and to be honest i'm still not completely sure how this worked um you know but i guess we just got to continue and maybe look more into it like how the path works to figure out why this algorithm actually works okay thanks for watching my channel remember do not trust me i know nothing
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
1,095
hey everyone welcome back and let's write some more neat code today so today let's solve the problem find in Mountain array once again we have a hard problem this one though is not super crazy I think at least conceptually you should be able to figure out how to solve this problem in a reasonable amount of time hopefully so we're given an array and of course as is typical with hard problems it takes a while to even understand what they're asking but basically they're saying we're given an array that has at least three values that's important because we have an array that's kind of going to be shaped like this that's why this is called a mountain array and this is find in Mountain what this means is that we have some values that are in strictly increasing order suppose one 2 3 4 five until this is the peak let's say five is the peak and then we have values in strictly decreasing order 3 1 and I'm just using the same values from this example over here and the reason it's important that this array is of length at least three is because this guarantees that we will have this kind of strictly increasing and then strictly decreasing uh portion so in other words we have like a sorted array here and then we have a sorted array here except this one is sorted in descending order this is sorted in ascending order now the tricky part is we're not told where this peak element is and we're given some Target value in this case it happens to be three and we want to search where does the three exist and in this case we actually have it existing in two positions so they tell us that we want to return the index of the first occurrence of that Target value so this is index zero this is index one this is index two we return two that's the output for this example so now knowing all of this how do you think we should solve the problem now there's a couple other tidbits here that were given this mountain array and instead of it just being a regular array it's a different interface like to read values we have to call the get method on it and we have to call Dot length on it I don't really understand the purpose of this to be honest cuz if you're doing Java you're probably using this anyway but I guess they wanted to level the playing field for people who are using python so now we'll have to use this but I guess the other purpose behind this is that we can only call doget a 100 times and with this interface leak code is probably able to enforce that the main thing that I think they're trying to prevent here is the linear scan solution because usually linear scan for relatively small inputs and I think the max size of the input is going to be a th000 a linear scan is usually pretty efficient so I think that's what they're trying to prevent what I'm getting at is the easiest way to solve this problem in Big O of end time is just to read values from left to right the first time we see the target value we return the index and if we never see the target value in the entire input we return NE -1 okay but entire input we return NE -1 okay but entire input we return NE -1 okay but can we do better than o of n yeah when we can it's usually a single algorithm and that algorithm is called binary search so is there any way we can use binary search probably given that there are sorted portions of this array now as I mentioned it'd be pretty nice for us to know where the peak is because if we knew where the peak is how do you think you would solve the problem using binary search probably we could run binary search on this portion and this portion we'd probably want to run it on this portion first because if we find the target here then we will return this one first rather than returning this one and the good thing is that we don't have duplicates in like this portion of the array and in this portion of the array because remember it's in strictly increasing order or strictly decreasing order now the only thing left for us to know is how do we find that Peak element well that again is going to be binary search but how let's think about it we have our left and right pointers here we know that the peak is definitely not going to be one of these positions but that doesn't really matter too much because we definitely know a peak exists like we know that with 100% certainty like we know that with 100% certainty like we know that with 100% certainty it's pretty much guaranteed now we know if we're in the left sorted portion like basically with binary search as you may remember we're going to take these two calculate the Midway point which I think is going to be here in this case but basically regardless of where the midpoint is we want to know are we currently in the left sorted portion or are we currently in the right sorted portion or are we at the peak element what do you think is the easiest way for us to determine that well remember that if we're in the left sorted portion basically this is going to be true the number at index middle is going to be less than the number at index middle + 1 less than the number at index middle + 1 less than the number at index middle + 1 and the middle is going to be greater than the value at index mid minus one this is really messy I'll rewrite it yeah so this is going to be true if we're in the left sorted portion because remember it's in strictly increasing order now to know if we're in the right sorted portion we basically just take these inequalities and reverse them like the comparisons and reverse them and if this were true then we know we're in the right sorted portion what if we're in like the peak how do we know we've already gotten to the peak well then our equalities I think would look something like this the middle is greater than the left and the middle is greater than the right so that's how we're going to be able to find the middle element not super crazy there is another way to actually find the middle element with the few less comparisons but we only need like one extra get read with the way I'm going to be doing it so I think that's sufficient it does pass all the test cases and in my opinion it's a little bit easier to understand but you can check out leak codes editorial if you want to see the slightly more concise solution but that's for finding the middle element okay once we find the middle element it's pretty easy to solve the rest of the problem just run binary search on this left side where this time we'll initialize our pointers like this our right pointer will be at the mid and we'll run binary search on this subarray and if we find the solution we return the index if we don't then we run binary search over here where our left pointer is going to be at the peak and our right pointer is going to be all the way here so that's pretty much the whole solution and even though we're having to run literally three binary searches we know three times log n is still going to be overall log n so the time complexity is definitely going to be overall better than Big O of n so knowing that let's code this up okay so the first thing I'm going to do is just get the length of the array and we can't just do it like the traditional python way we have to actually take the mountain array interface and call do length on it and I'm going to do that so we don't have to keep writing this out because we're going to need that length a few times because we're going to be running binary search like three times so the first phase is going to be where we want to find the peak element and I'm going to initialize the left and right pointers like this at 1 and length minus 2 because normally we would do 0er and length minus one those would be the edges of the array but we know that the peak is definitely not going to be at the edges so we can make like a slight optimization and just do this instead and other than that it's going to be a mostly straightforward binary search at least the way I like to write it I like to do left is less than or equal to right because if they're equal then that's probably where the solution is and typically we calculate the Midway Point like this left plus right is going to be divided by two and now I'm actually going to just save the three values left mid and right I know I'm kind of reusing the same variable names even though like these L and R stand for the pointers these are the actual values so this is what I'm going to do mountain array. getet mid minus one that's the left value and I'm going to call the same thing except for Mid that's going to be the middle value and then I'm going to do mid + one that's going to be going to do mid + one that's going to be going to do mid + one that's going to be the value to the right of the middle value and the reason I'm saving all three of these is we kind of want to minimize the number of times we call doget and we're going to need to do a couple comparisons so I don't want to have to repeat the same call so I'm going to do what I said earlier I'm going to check is all three values are all three values in increasing order or are they in decreasing order like this and else we already found the solution therefore we break because if neither of these are true we know for sure we don't even have to check we know that this equality would be true we don't even have to check that so that's how I'm going to do this and then once the binary search is finished we're going to assign Peak equal to whatever the middle pointer was we can do this in Python because this variable will still be in scope but you could have always declared this outside of here if you were using like not python but in this case since we're in the left sorted portion we want to search towards the right so we take our left pointer and set it to Mid + one here we're in the right sorted + one here we're in the right sorted + one here we're in the right sorted portion we want to search towards the left we take our right pointer and set it to Mid minus one so this is just finding the peak now we're going to do the second phase search left portion and this is going to be pretty similar but this time our range left and right is going to be from the beginning up until the peak index and once again we're going to continue while left is less than or equal to right and we're going to once again calculate the Midway point so this is pretty repetitive code here but this time we're going to need not three values we're actually only going to need the value at the middle index because now we're not searching for the peak we're actually searching for this target value that was passed in as a parameter so first I'm going to get whatever value is at index a mid and then I'm going to compare it if value is less than the target that's a possibility else if value is greater than the Target and else is the last condition where we found the Target and if we find it we might as well return the index of it so that's the easy part now for these other cases if the value is too small we should probably search to the right because this portion of the array is sorted in ascending order so here we're going to set left equal to Mid + 1 in the other case we set right Mid + 1 in the other case we set right Mid + 1 in the other case we set right equal to Mid mid -1 like I said a pretty equal to Mid mid -1 like I said a pretty equal to Mid mid -1 like I said a pretty straightforward binary search at this point and lastly I'm just going to take this actually and copy and paste it now because it's going to be pretty similar when we search the right portion just a few modifications we're going to have to make here the initialization definitely needs to change here we're going to search from the peak element up until the end of the array which is going to be length minus one remember we computed the length all the way at the beginning of the solution now we calculate the Midway point the same way we get the value the same way the difference here though is that this array is actually this portion of the array is sorted in descending order so if the value is less than the target we actually want to search towards the right and if the value is greater than the target we want to search towards the left you could update these like I could set left equal to Mid minus one and right equal to Mid + one or I could just swap the in + one or I could just swap the in + one or I could just swap the in qualities either one works so I'm just going to make that change so now we have our solution we have the three binary searches but if we never end up returning from any of these at the end of the solution we should just go ahead and return NE -1 so this is quite a lot and return NE -1 so this is quite a lot and return NE -1 so this is quite a lot of code but I think it's about 40 lines mainly because we're running binary search three times I have a few comments in there as well and you know this takes up a decent chunk of the solution so I'm going to go ahead and run this to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Find in Mountain Array
two-city-scheduling
_(This problem is an **interactive problem**.)_ You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`. **You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface: * `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed). * `MountainArray.length()` returns the length of the array. Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification. **Example 1:** **Input:** array = \[1,2,3,4,5,3,1\], target = 3 **Output:** 2 **Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2. **Example 2:** **Input:** array = \[0,1,2,4,2,1\], target = 3 **Output:** -1 **Explanation:** 3 does not exist in `the array,` so we return -1. **Constraints:** * `3 <= mountain_arr.length() <= 104` * `0 <= target <= 109` * `0 <= mountain_arr.get(index) <= 109`
null
Array,Greedy,Sorting
Medium
null
1,269
hey everybody this is Larry this is me doing day 15 and I'll also do the premium problem later uh of the deco day challenge oh they going give us a hard one right before contest hit the like button hit the Subscribe button join me on Discord let me know what you think about today's SP 1269 number of ways to stay in the same place after some steps I'm still in tight P you can see the background or just W up so uh but I didn't sleep that well so I don't know what to make of it uh chat lag Maybe but yeah that's I saw the mod so I'm going to do the mod T and mod that's mod this thing all right so you have point at zero each step you can make left to the right or stand the same price given two steps uh we number way such that the pointer is still at index zero after exactly steps okay so then after that just constraints and constraints are 500 so this is actually pretty um you know easy to Define right uh wait what's all link again oh in know oh actually I think I misread this a little bit um well I'm trying to think like oh yeah the outside way so you start at zero and you okay I mean but it's still yeah it's not that bad I think the uh I think one of the things about this particular problem sorry I'm a littleit shaky cuz I'm literally using the laptop on my lap um but maybe just not you look maybe you're not looking at my face anyway and that's fine but uh but I think for this particular one I think the key thing to realize is that you know this constrain is like oh we're doing steps by away length that's going to take forever and it's true but I thing to notice is that you can only move one step at a time how many how far away can you be after end steps and the answer is n end steps away right so that means that even though this already length is 10 to the six you can only really go only 500 steps away and of course um and that's just in general if you want to talk about um yeah that's just in general and then if you want to talk about um the actual problem which is you have to get back to the first Index right the Ser index well yeah stay in the same place but yeah the first index uh or index zero then you can you have to kind of budget the time to go back and forth which means you even then you only go up to um n/ two steps then you only go up to um n/ two steps then you only go up to um n/ two steps away or steps over two uh distance away right so in that case yeah I mean obviously it's still going to be n square but where n is the number of steps but you know uh that should be good enough for us to start so let's do it right so then now here we have uh you can do it in a number of ways I'm going to do it top down just because it's easier to explain uh yeah let's just say um I'm going count steps or something or uh yeah just do count uh and then uh how many so you have like Steps left and then the current Index right uh and then here now we want to return C uh step with steps all the steps left and we start at zero index and yeah so if steps left is um you go to zero that means we have more steps left if index is equal to zero then we return one otherwise we return zero the base case is just that you know if we are able to go back to at the end of all the steps if we're in the first uh space then we return one otherwise return zero uh okay and then after that you know you can only go left right or stay in the same place so yeah so then uh number of ways we can go left we can go right and we're going to stay in the same place uh I'm doing this in the weird order but of course the thing is then now um we have to make sure they stay in bounds right so if index minus one is greater thanal z um if index + 1 one is greater thanal z um if index + 1 one is greater thanal z um if index + 1 is less than and already length and that's pretty much it that looks good uh and of course here you can trally put in like 500 and 2,000 and it'll time out is what I meant 2,000 and it'll time out is what I meant 2,000 and it'll time out is what I meant to say but I don't know I forgot to say it uh but yeah so it should time out because this is brening three times or close to three times on every uh iteration uh so the thing to do is just memorize and um the couple things you can kind of um hack around as well like I said um index has to be um I guess in this case if you have steps left and then you have index it takes all the steps to go to index so you can actually even add something like if steps left uh actually I'll end optimization no I think this is fine if steps left is less than Index right is it less than you go to Frank and then we return zero because we don't have time to get back right don't have enough steps to get back two Z right uh I'm trying to think so we have if index is one and this is one then you do have enough so I think this is fine and then of course the other I mean this is a very Min optimization but the other thing is of course memorization right uh so how do we Analyze This steps left can go from Zer to steps index can go also from Z to steps though a little bit tighter than that this optimization but we'll just kind of ignore that for now uh but yeah has cash right and that's pretty much it after you cash it up uh actually use the cash up uh I would also say if you're using another language you should be more careful about the mods um in Pyon I don't have to be that careful per se but also I did actually do a background over math it's just that you know l about it but basically if this number is less than mod then all this will be just at most three times mod right and three times mod isn't going to overflow for by that L uh long by that much by that long so that's why I'm not worried about it uh let's actually give a submit obviously because sometimes I forget apparently uh yeah and you can see that even case 4 kind of once fast enough I don't know how fast it went but uh let me double check any weird edge cases I don't think so let's give a submit uh and there we go uh like I said this is going to be step square and step square space uh you can actually optimize the space part if you do it Bottoms Up U I'm not going to go over that today uh I try to go back to sleep to be honest uh and even though my body doesn't want to I think like it's just going to burn me out if I don't at least try a little bit um but yeah that's all I have for today at least with this problem uh let me know what you think going do the premium prom next so stay good stay healthy to mental health I'll see yall later and take care bye-bye
Number of Ways to Stay in the Same Place After Some Steps
market-analysis-ii
You have a pointer at index `0` in an array of size `arrLen`. At each step, you can move 1 position to the left, 1 position to the right in the array, or stay in the same place (The pointer should not be placed outside the array at any time). Given two integers `steps` and `arrLen`, return the number of ways such that your pointer is still at index `0` after **exactly** `steps` steps. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** steps = 3, arrLen = 2 **Output:** 4 **Explanation:** There are 4 differents ways to stay at index 0 after 3 steps. Right, Left, Stay Stay, Right, Left Right, Stay, Left Stay, Stay, Stay **Example 2:** **Input:** steps = 2, arrLen = 4 **Output:** 2 **Explanation:** There are 2 differents ways to stay at index 0 after 2 steps Right, Left Stay, Stay **Example 3:** **Input:** steps = 4, arrLen = 2 **Output:** 8 **Constraints:** * `1 <= steps <= 500` * `1 <= arrLen <= 106`
null
Database
Hard
null
143
hey what's going on everyone I'm back in the leeco grind so let's get to it in this video I'll show you how to solve question 143 reorder a linked list using a two-pointer method but the way I solve a two-pointer method but the way I solve a two-pointer method but the way I solve it here is a little different than the fast and slow two pointer method that you may have seen in some other tutorials about this problem I think this weighs a little less error prone during an interview when you're under pressure but maybe that's just my opinion anyways let's Dive In let's start out with example one for the problem or given the linked list with values 1 2 3 and 4 and we want to rearrange the values so that our linked list is one four two three the array representation of the linked list will look something like this I've just used the table here so it looks neater so the top contains the actual nodes and the bottom row shows the just the indices of the array just keep in mind that the actual linked list is still connected the nodes have just been added one by one onto an array that's the same length as the linked list on this picture of the given linked list I'm just going to draw out what we're supposed to get after all the pointers have been reordered so we're supposed to get one four two three and then three points to none all right so that's what we're supposed to get so uh with that in mind let's go back to the array do you perform the reordering we can use a two pointer method since the array allows us to keep track of how many nodes from the beginning and end the two pointers are respectively let's call it a pointer from the first node a and the pointer from the last node B and what we're trying to do is bring the two pointers closer to each other while reordering the next pointers of the notes to increment A and decrement B we can use a for Loop that only needs to iterate up to the middle index of the array but the middle of the ray is calculated differently based on whether the array contains an even or odd number of nodes as you'll see later we can get this limit by doing the integer division of the length of the array by 2 for the even case I'm just gonna write Len for short right so we have four by two and that's two we're supposed to stop at one but this two is all right because if we're using a for Loop uh this two will be the exclusive limit I'm just going to call it exclusive limb for short which means our inclusive limit is one so we're good here so the for Loop that we have is for I in range so first we assign the pointers right I'm just going to call this a rate r a r short and then B is array all right so that's B and the next we reorder the pointers of the nodes we can point B dot next to a DOT next and then we can set a DOT next to be if we reassign a DOT next to point to B first we want to be able to point B dot next to a DOT next because a DOT next has been disconnected from two so that was the case for I equals zero but what about our last iteration where I equals one so I'm gonna just make the smaller a little bit so we have more space so the case where I equals one we still have a and then B just like before but does this does eight on x equals a b dot x equals a DOT next still work and does a DOT next set to B still work let's try it so now we're not here anymore we are a B so B dot next equals a DOT next and then a DOT next is B which is already in place here so right off the bat you can see there's a problem this is a cyclical Loop here we need to add some additional logic to be able to break out of this Loop so let's see what we can do since a is already next to B and we are already at our stopping index all we need to do here is move this down a little bit check if the minus one all right if I is equals to one which it is and if a DOT next is already equal to B now if that's the case what we need to do here is to just set B dot next to none and then break otherwise you have the same logic does here and so this is your new logic here but it's important to note this is for the even case but the odd case you'll as you'll see is very similar so for the out case what we're supposed to see is right and then we can use the same way a B so I equals zero I equals one so now a B same thing and then a DOT next is B so now what about I equals two all right this is actually where we want to end and at this point A and B are actually both pointed to the same number so for the odd case your limit is actually the length of the array integer divide by two Plus one and five divided by two that's two then plus one that's three remember what we did here and then go back up here for our even case we can see that what we do inside the if statements are the same the only difference is these two so our overall logic is four I okay so this is the combined logic of both the even case odd case so now that we have the combined logic I think we have enough information to start coding so now we kind of understand the idea behind the reordering operations we can start coding first I'm just going to put all the nodes in an array so I'm going to call it r set a pointer n to point to head right and then we increment the pointer effort pendings and then that'll put everything on the list so next is to calculate the exclusive limit like we calculated back on the drawing board and that remember that's dependent on the array having an even or odd number of elements right so this is the even case else we have the odd case so then we have the for Loop and these are the two conditions for uh even and odd well I think it's uneven uh B dot next equals none break right otherwise we fall through reordering the point the next pointers of the nodes and then just return head because we've just modified the whole uh list in place so both of our preliminary test cases pass let's submit foreign the time complexity of this is determined by the number of nodes in the list so if you look at here in this while loop we're going through all the nodes once so that's o of n where n is the number of items in the list in this for Loop I'll just write this down thank you so in this for Loop we're going up to O of n over 2. about or plus one but that's really insignificant so and that's still oh then and the space complexity here is oven because we're using an auxiliary array to keep track of the pointers so that's it for this question I hope you've enjoyed the video or found it useful and I'll see you in the next one
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
1,614
resting depth of the parenthesis so string is a married parenting string where they have denoted as VPS if it meets one of the following criterias so first one is it is an empty string or a single character not equal to either open or close okay other critical is it can be written as EB like a is concatenated with B where V A and B are valid paretary strip or another will be it can be written as string so basically valid parenthesis means if a parent is open then again opens so it should be closed so this will be done and again you chip because so in this case we can tell it as valid planted so how can we check this so let's start with the account here so if it is opening parenthesis will increment the account if disclosing path is for local implantation since this is for closer path is increment account one initially it will be zero okay then this is opening again counter two then this is closed so count minus one again zero so at last you have zero so you can see it's a valid by this string so you can similarly Define the resting depth of any valid parenthesis string as follows so I'm testing left there will have an itself depth as zero so depth of C will be zero where C is a string with single character or not equal to so if you see in this the instant depth will be this given string is so listing that will be 1 plus depth of a wired up coffee so a can be a will be equal to this that's it then it will be nothing but a brackets example nothing but this so in this case so that is what they have to next yeah here it will be 1 for this nesting depth and depth of a plus inside whatever it is there width of a can be 0 1 to any number it can be for example if this string this is all a valid parenthesis strings with mistake that zero one two and if you look into this there are violent parentheses though you have open and closing parenthesis they are not file in parenthesis strings because if you see here this opens open but closing only one times either closer should be there here it was first closing then open it now that's not a valid parenthesis close then open as I said so it is commonly considered it doesn't indicates a life parenthesis but for this scenario you can do it because they have given the value parenthesis strings only so if you see here this bracket the first is closing so count minus that only minus one next open exocratic increment so it will be zero at the end quantity zero but this is now with a given example we have to tell what is a nesting dip of the parenthesis foreign foreign because for this opening we have this closing Okay so and then for this open we have this closing for this opening we have disclosing so they're all in the order so what is the misting it's a volume parenthesis the maximum of all the depths we have here that is three this is okay so you have to return this as a answer and logically if you see why is it the answer see because if you start from here SSN this is open that is the outermost path this first inside parenthesis which will cancel out so two and three are canceled out here so that's why these two are done and if we come here open if you check this it is open this work inside out okay so that will be less than that will be three for eight the most inside whatever I said that will be having highest investing depth then we will return that because all this nothing that will be 2 for this expression stand that will be two and four also assume that will be two that so what we can do is we will have a variable called Max step equals to zero another variable called current okay current is nothing but the county is nothing but representing so each time in the loop if you find an open plan this is you keep on intermitting them at the same time you find the max step for the next step foreign test now Next Step equal to zero texting to current that will also be neutralized to zero so next we have is for each character C string s so first of all show the C plus we celebrate explain the example code so each character understanding is what we need to check if C is equal to open parenthesis so you have to use a so if it is open parenthesis fine after that you have to check for the max depth so next step equal to Max of max depth comma current fine so next this is done else if also you should be your mind else if you give else all this character will become under the S else Parts LC what is the character equality but closing parenthesis foreign so that history will be converted to RF characters and you either to the array of characters no and he has instead of Max you should use the path of Max function then everything else Remains the C yes okay successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come up with Adam in the next session until then keep learning thank you
Maximum Nesting Depth of the Parentheses
maximum-nesting-depth-of-the-parentheses
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` is a **VPS**. We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`. * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s. * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**. For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s. Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`. **Example 1:** **Input:** s = "(1+(2\*3)+((8)/4))+1 " **Output:** 3 **Explanation:** Digit 8 is inside of 3 nested parentheses in the string. **Example 2:** **Input:** s = "(1)+((2))+(((3))) " **Output:** 3 **Constraints:** * `1 <= s.length <= 100` * `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`. * It is guaranteed that parentheses expression `s` is a **VPS**.
null
null
Easy
null
1,705
hey everybody this is me going over q2 of the weekly contest 221 uh maximum number of g in apples so this one i had a lot of struggle with during the contest um if you skip i actually just kind of i tried like three or four different things uh and they were just wrong um i mean i had the right idea but uh i want to go over a couple of things the first thing that i want to go over is that i was just really bad at gauging the max size um for some reason i couldn't get it in out of my head that i thought it would be um 2 times 10 to the fourth squared is the number of maximum apple but if you think about it correctly which took me a long time is that you could think about these segments right and the length of the line segment can only be two times ten to the fourth so then the longest um the last element is or the last days which is only going to be um you know the last element plus two times ten to the fourth meaning that the worst case is gonna be about four times ten to the fourth i actually i don't know why but it took me um way too long during the contest to really realize this and this is why the video is so long um and uh and yeah and then the other thing was that i just had an off by i think i was being a little uh incorrect i might up solve it later using the same strategy but um but i was trying to do some clever things with um with uh fast forwarding but in this case you actually don't need to because four but four times ten to the fourth if you do log n things uh that's still gonna be fast enough um but as i said so i had a lot of issues there um yeah and that this was the most troublesome uh because i think i knew what to do but i just for some reason i um i couldn't get it and also during the contest there was a hidden test case which i was just wrong about um so like i couldn't figure it out so i just keep on submitting it was keep being wrong but this is basically my code um and the way that i think about it is actually it's a or at least this code is um a sort of hybrid and what i mean by that is that uh i'm it takes advantage of the fact that um when we go by from their starting points are only one offset each so then we can do essentially a scanline algorithm uh with a scanline algorithm with a heap uh on top right where as you kind of move from day to day you know you eat one apple at a time every day and for each day each apple um you literally just implement okay you know today is day five these are the number of apples that are available to me that's greedily take an apple from the tree that watch the closest to you right um i think that makes sense in an intuitive sense because you know you if you swap the order where you take um an apple that can last longer well it can only give you a worse solution because um later on uh the apple that you haven't eaten yet could expire earlier right so that's basically the greedy solution and getting it day by day and yeah um so basically uh yeah so we put things in the heap only if there are apples and then here index is actually the day number um we get rid of the apples that are expired and then if we have any apples left then we look at the expiry we get the cow uh we pop it we eat one apple and if we still have any apples left we put it back into the heap to be you know keeping track and then once all this is done because we still have extra days um we do basically a copy and paste to be honest which is we do the same thing except that we just keep on going while they're still uh apple's in the tree and that they're not expired so this is that's basically it um i think i just have one of those mind fart moments where i just couldn't solve it during the contest because i had something very close to the working solution but i had just a lot of off by once in a couple of places and i couldn't just one of those days so uh you know i would also say that earlier today i finished first in the contest so um and this is not meant to be a brag because it's kind of embarrassing when you know you can finish a q2 afterwards but what i want to say is that you know you'll have good times you'll have tough times um just you know always try your best always grind it out and if you watch me during the video i worked the entire contest trying to solve this even though i didn't get it and the video actually even goes uh and you should fast forward for it but you could just see that um i worked even past the contest time to get it right before um you know before i stop working on it so definitely hopefully that's a lesson there um and there's some debugging tips and printout but i was just really bad on this one because i just had off by once and um i think the key thing that i wasn't taking advantage of was that um for here um the days and the events line up and i think i just didn't i think by able to visualize it correctly the first time i should be able to solve this but because i didn't visualize this correctly the first time i had some lingering visualization that was just wrong and then i was trying to modify my solution or my visualization to fit like off by once and stuff like that um which is always a disaster sometimes uh and for me i needed to reset and restart it over for this problem but i just couldn't let go because it was only a q2 right so i was just like oh this should be easy but um but yeah so that's basically my lessons there um yeah uh let me know what you think you could watch me solve it live during the contest but again like i said this portion is very long so hope you enjoy it uh like i said it's uh you know i consider myself good at this because i literally won a contest earlier today and i still struggle from time to time so you know so you find yourself struggling it's okay just keep working hard keep grinding and i will see you next problem but also the live portion is now i guess okay well here we go get that out of the way get the silly mistake out of the way hmm um hmm alright you oh that's not what welp oh step right this one so i want to play through this three of these now it's four man why am i so bad right now only three people got it so i don't think this is just me but i wish i didn't make a silly mistake on part one this is just prefix some i think wait well now it's something like this but i don't know prefix some this is too big so you do i okay so wow this is hot so how many apples can you eat right let's go i don't know how to do this one maybe i'm a little bit stuck only 46 feet have gotten it in 15 minutes which is really long let's find this okay so same code but different language and it worked right so that's a little bit sad uh okay thousand people solve this let's think about it again hopefully now i have refresher mine uh okay what is n oh did i miss an n no that's okay no because it still can have it can still have 4 times 10 to the 8th number of apples i'm still weird but how do you do this i mean this seems like i'm just having a um a blank so now per day keeps the doctor away but it's this problem has been keeping me away like the heat one looks more promising did i have my heat solution i thought i saved it somewhere but i guess not um so okay so then two so just uh t minus last click is this it was i just been dumb no i mean it could be both but then i have to keep track of the ones that would have wired it you yeah i mean it's just very wrong right i'm just blanking out on this is tragic oh i'm just being dumb whatever apples have left over so i can't do prefix some i am dumb this is not multiple oh man what oh okay so yes why did i multiply them i got confused about the thing okay my analysis was wrong that's why i got so confused okay and then okay so then now why is that only six am i driving off by one so just come on up well just having that kind of day well evening i guess expected one so one oh that is actually a good um thing but oh no that's to actually know it's that way well i just have no idea how to do this one maybe i really have no idea how well i mean a thousand people got it so maybe it's something simpler but i just okay i have 20 minutes that should be fast enough but i thought i saw a pattern but that was wrong actually so once we eat it that's not my oh well now the heap solution makes sense i am just being dumb again uh okay do i have it in somewhere no okay fine because now guys the reason why i didn't think it makes sense is because it took two okay poop um okay let's do it again uh index i'll just do a sword of this no this is to start and text just do that um tears is you don't have to this may be too slow actually to be honest but um so that's not even right at least this one's right why is this problem so for me i mean i just don't get it how am i doing so well okay so this is done this is also done up fourth day yeah why is this coming off by one somewhere i'm gonna explain this one though oh i think i made this i will be for the first time i did this and i made it again okay so this one's better but we're still having this issue oh because this is uh off by one so this should be this minus one okay wish me good luck i might just i don't know oh what that's sad i need to start maybe i don't need to start i mean you don't need to start because yeah because they're all consecutive another thing they have to try to maybe this expect this 102. just off by one doesn't really matter as long as we're consistent which we might not be the thing doesn't even make sense anymore actually okay what am i doing here maybe i do need to start this was a disaster and a lot of people got in this i don't i mean i'm just curious how they got it or like what's the solution rather um okay maybe i sorted a different way well that is just really well so maybe not that but i'm getting along with a hand case nope still nope i forgot which one i submitted that's why i was hoping that the g code sign is the thing but uh six minutes ah i don't know just one of those days i guess i mean i feel like this is right but like mostly could and i don't have any overflows or anything like that they're still on day one does that make it better no i don't think so yeah amount of ideas to be honest i think this is the right idea but i'm implementing it weird for sure if i don't think this matters but i'm gonna try anyway yep i mean i wish they'd just give me the case because then um and it's not like i'm cheating it's just that i don't no idea though maybe it's just a weird case i don't know why they made q2 so um like i feel like they should only have hand cases for only time limited situations because no one is hard-coding this one is hard-coding this one is hard-coding this right it's just that you know we're trying to learn and grow um don't like that's one of the things i liked about lead code right so uh see how long people gotten it i mean this is a disaster right um i mean i don't know even late chris well he just did it last maybe um i did q4 pretty quickly but i spent half an hour on it because i have twice because i have to rewrite it to c sharp um which is kind of silly how do you do this four minutes should be enough if i have an idea i mean yeah i didn't think that would change because that's shipping in variance i really don't know huh i don't know why they hide it um a little bit sad about that like i feel like if i had just one test case i could solve this problem but that shouldn't matter with it to be honest i don't get it what are you doing wrong larry i didn't get it please uh i don't get it uh i mean this is literally me the entire contest i don't know why i'm having so much struggle with this um i am going to go over the time to i kind of reveal um do some code reviews about this uh because i just don't know i mean it's probably something obvious that i'm missing some invariant that i'm really missing uh so it's kind of sad that this is like a best and worst day of like 370s like right yeah but now it's done so let's kind of go over it a little bit and then see uh well i mean it's probably like two well this is not two lines of code so i was like i was hoping that it like there's a simple one that i missed but um i was kind of doing it well okay i don't know how i mean maybe i can understand that one but let's see again i mean i kind of this is basically what i do but i mean maybe i was trying to be too clever with to i mean he's doing it basically uh one edit um as you go from left to right as well so maybe that makes sense i don't know um okay so kind of a sliding window thing but i see what's going on i think i'm just having issues with kind of an off by one somewhere um let's see if i can take a look at my submissions real quick and i might just live i mean this was painful um does it tell me my wrong answer i mean this is way off so actually i don't know oh great i mean i don't know why they didn't maybe this is a big case and it's just that my com my fingers smaller because i was saying that they should only do that for trd cases which maybe this is a tlu case but uh just that i'm wrong on it but i'm actually not sure why though that um so two is what two apples from here to um ten thousand why am i so weird on this case you uh i mean i've now that i looked at other solutions i think i know how to do it's just that i don't know why my code is like conceptually i'm doing the same thing um but i mean definitely taking um advantage what people do is that they take advantage of this but uh yeah like i have this code pretty much maybe not that one let's see i'm going to try some okay maybe just look straight for it okay this is actually a smaller bookkeeping maybe but man this was a disaster i'm trying to still find one that i can kind of really um and again of course i'm just sad because it i had to solve q4 twice so oh it's just a hip yeah i guess if we do it um i don't know i guess i don't really understand why this my code is so bad um let's just print it out real quick so this may time out a little bit um i don't think we need all of this um and i think this is this should be the same answer or the same wrong answer maybe oops and this one i just had another two because for me i'm just trying to understand and yeah so clearly my answer is wrong which is fine which is what i expected to be honest uh or with obviously i didn't expect it during the contest because if i did then i wouldn't have done it but now i'm trying to figure out what is going on with the state um so hopefully this debugging helps and maybe i should have just you know end the year strong and not have done today's forum after finishing first but okay do i not print a heap okay so first we i mean this is not in sorted order so okay so start let me put this in oh i see kind of which is that um i let the later expiration stuff uh time out when i should i mean that's kind of what i was thinking but i didn't i couldn't find an uh in examples but i also wasn't able to think about the cleaner way to implement it which is to scan the index from left to right because if i did then this would have been naturally taken care of which is how some people did it as well um because okay so this goes from zero to nine inclusive so this will always have the priority but what you want is actually you delayed it once as they become available something like that um because i got two or maybe at four yeah at four at time stamp four well actually even at time stamp three we should definitely eat these two but then otherwise it gets expired which is why we don't need enough apples wow that's a very subtle invariant that i feel like i mean i did try to sort of by the end um endpoints but i think i didn't what i didn't do is um what i didn't do was kind of doing it together right um we're like okay so kind of like a sliding window heap type thing where um it's not a sliding window but it's like a sweep line which is actually another thing that i tried during the contest um but i just didn't put them you need to do both which is really tricky for q2 um but yeah so basically the idea here would be then let's see um okay so basically what i want to do is okay this is gradient uh this is equal to zero let's just continue um no wait that's not true because we might eat from an apple okay eat an apple okay so first of all in the beginning we want to push to the heap uh the expiry time and we want the earliest expiry and then x oops so that's the invariant and then now if the length of heap is greater than zero um we want to eat one apple from the top and well let we have to clean out the top from xp first so if uh this is greater than index i just thinking about off by once uh he q dot hip hop heap and then otherwise that's e to the top one if length of c is greater than zero oh yeah and we also push to the heap let's only push this if x is greater than zero obviously maybe it's obvious uh then otherwise if there are more than zero elements then uh then we eat the top of the apple so okay x3 count is equal to heap sub zero um q dot hit pop i guess it always gonna be yeah do we hit pop and then push again no i don't think we need to i think we just go straight um now that maybe that missing things up actually so okay let's do that uh pop heap and then we eat an apple and then we push it back okay and then now while length of heap is greater than zero i guess we just keep on going with index um index plus one at the weigh-in and then we do basically this string again actually and then return total something like that well that's not right at all if heaps up soon oh no whoops if this is the other way around meaning that the current time it's after the x3 maybe enough by one huh okay nope and he's not that uh let's put toto in the middle man i'm really struggling with this problem today but uh okay so five is in the middle that means that this is not done so um also we have to kind of count is greater than so i think that's why because we don't get rid of stuff so it was probably just doing i would imagine it to be more but okay let's just run it real quick uh so let's put heap in here so we can take a look at the heap is still empty uh so heap is not empty so that means this part of the code is wrong so while leap is great oh just because this part is this um okay and then now let's give it a good luck submit oh wrong answer again i didn't want the test cases today that's those that is literally the test case so i'm a little bit sad um i'm having it off by one apparently uh why is that so we ate four apples at the end and then we have these left a1 and this is so hard to visualize i think that's one of my problems but okay so i have three apples zero i think i just have an off by one somewhere possibly well possibly again so index should be n at the end this is right but this as well up on a third day four day five days so after five days we ate five of them is that right i guess so and we have these left on the expiry so this is six seven so index is equal to five create this uh index is equal to six we ate this and that should be it right that's one of my environments well i just have an off by one on this uh okay so this is four and then on the fifth day what did i change is this one no this is yeah on the zero one two three four five man i'm really struggling not gonna lie i'm also trying to wash it a little bit but still this is just sad i'm a little bit sad um okay so wait five apples before which is true but then four so yeah so this expires to the fifth so you ate that one here we it expires on the six right so maybe it should be this but i don't know that makes sense i feel like i'm missing something curly so this should be inclusive right so i don't know let's make it exclusive so then here then we get rid of it but then that we have to eight five issue why tell me why i just really don't even know anything anymore is this state right i feel like that's right that after five days do i really have to draw it out i mean i know the answer and i still cannot finish this in 20 minutes so this has uh been a very hard one for me um first day second day yes two days so we eat two apples in two days that's fine day three okay yeah five six seven right so why is that well v85 at first and then day six day seven oh this is four when it should be oh huh oh i'm just being dumb because i for some reason i thought this was in full range and in other languages the for loop would have to last while you but in python it might not okay i'm a little bit lazy so that's why oh my gosh okay uh hey yeah thanks for watching the video uh let me know what you think hit the like button to subscribe and have a happy new year and i will see you next time bye
Maximum Number of Eaten Apples
count-unhappy-friends
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._ **Example 1:** **Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\] **Output:** 7 **Explanation:** You can eat 7 apples: - On the first day, you eat an apple that grew on the first day. - On the second day, you eat an apple that grew on the second day. - On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot. - On the fourth to the seventh days, you eat apples that grew on the fourth day. **Example 2:** **Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\] **Output:** 5 **Explanation:** You can eat 5 apples: - On the first to the third day you eat apples that grew on the first day. - Do nothing on the fouth and fifth days. - On the sixth and seventh days you eat apples that grew on the sixth day. **Constraints:** * `n == apples.length == days.length` * `1 <= n <= 2 * 104` * `0 <= apples[i], days[i] <= 2 * 104` * `days[i] = 0` if and only if `apples[i] = 0`.
Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people
Array,Simulation
Medium
null
412
hey guys welcome back to my series of videos of solving lead code problems right now looking at 412 Fizz Buzz so given an integer n return the string array answer which is from index one until the integer end inclusively and each of the indexes it shows the positions of the answer array and it will be first bus if I is divisible by three and five phase it is divisible by three buzz if it's divisible by five answer or I as a string if none of the above so this is a simple pretty straightforward thing so we start with answer and we iterate for I in range one and N plus one so let's check it's divisible by three equals um and rest of the division by three equals zero divisible by five equals n division by five equals zero and we can we now just need to do some of this analysis if both if divided by three and divs divided by five then answers your plans Fizz Buzz and now you do a bunch of elopes so I'll have LF and then this is the else if it's divisor divided divisible by three it's fizz and if it's divisible by five it's bus we append the string version of hi and then at the end last but not least you just return answer we submit this we're gonna go wrong uh for Iron Range so it should be one two-fifths why is this happening because I'm doing and should be doing I yeah here it is hope you guys enjoyed it
Fizz Buzz
fizz-buzz
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: * `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`. * `answer[i] == "Fizz "` if `i` is divisible by `3`. * `answer[i] == "Buzz "` if `i` is divisible by `5`. * `answer[i] == i` (as a string) if none of the above conditions are true. **Example 1:** **Input:** n = 3 **Output:** \["1","2","Fizz"\] **Example 2:** **Input:** n = 5 **Output:** \["1","2","Fizz","4","Buzz"\] **Example 3:** **Input:** n = 15 **Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\] **Constraints:** * `1 <= n <= 104`
null
Math,String,Simulation
Easy
1316
496
hey everyone in this video let's take a look at question 496 next greater element 1 only code part of our blind 75 list of questions so let's begin in this question I'm actually going to go ahead and just copy the examples here I find that they're easier to understand yeah than the actual question phrasing is a little weird so in this question we are given two arrays we're given a nums one and a nums two you can think of nums two as the entire array and nums one is basically telling me which of the elements in nums 2 I want to perform this next query element operation on what is the next greater element is the element of which for example if I ask for an x squared element of 3 it is the element to the right hand side of three that is greater than 3 and it is the first of that element so in this case it's going to be four it's possible there's like six and seven here but we only take the first one into consideration which is 4 here now this basically tells us like for which element we want to look this up so you can see here for four there's actually no next element so that's why we return a minus one for one the next element here is a three so we return a three and again for two there's nothing so we return a minus one what about the next example in this example we have two and four that we're looking for the next element of two next greater is a three or four again we don't have anything so that's why we return Three N minus 1 here Okay so the question is like phrased a little bit differently so hopefully the examples Illustrated what the question is really about but if I just gave you like this array here right if I just give you this array here how about you go about finding the next greater element of all of these like what if I just want to find the next greater element of one three four and two and then maybe I can next store that somewhere and then in from nums one I can just look that up right so here I can see that for one next greater element is three or three it's four or it's minus one or two it's minus one right and then once I have this information here then I can basically just Loop through my nums one and then I figure out okay so for four I want to add in minus 1 to the array for one I want to add in three to the array number two I want to add in -1 to the array two I want to add in -1 to the array two I want to add in -1 to the array maybe let's start with that type of approach so we have nums two and basically we will find the next created element for all of the items in numbers two and then in the very end we can just perform like a hash map lookup to map the indices or map the like the items here to the appropriate like answer here so let's take a look at how we can do that well if you think about this question how would you go about like finding the next greater element right so let's say I'm on number one here what I would need to do and maybe this is kind of more obvious if I have like a larger array maybe like four to seven eight something like this if I'm on number one what I need to do is I need to look on my right hand side and for the first element that is greater than number one I will store that as my answer so in this case it's three when I'm here what I would do is I would look on the right hand side here and I will store the answer such that it is the element that is the next greater one from three which is four in this case then I start off F4 and then I can see the answer is six you can see this is actually a slow algorithm because we're doing the O of N squared time look up here because We're looping basically N squared times here but maybe we can start off with that and see where we can arrive at so let's maybe go ahead and start off with that so what I can do here is I can go through the items in nums two so I will do for Iron Range zero to length of nums two and then I'll do for J in range start from I and then it'll go to end of nums two right so maybe like we start off I over here I will start off here Jay will start off here and J Will basically look here okay so what I want to check now is I can check if nums 2 at J is greater than comes to an I but then I found my element right so I can basically just record this so first of all go ahead and break because I don't want to look further in the loop I only want to return the first one so we have that information here so now we store the element right so next greater initially we can see it's -1 assuming initially we can see it's -1 assuming initially we can see it's -1 assuming like we find none of these but now we will store it we will say next greater is equal to nums 2 at J and then once this J Loop is completed then now I know that for one the next greater element is three so then I can actually create this in a map I can record this information in a hash map so then I can just do like uh let's just call it D for dictionary right and then what I would do here is I will store D of what of nums two I is equal to what is equal to this location this next greater element here that's basically what we have so let's maybe go ahead and try to see if this works so here I will just return an empty string um but let's just maybe see that it works with the first example is this one okay so let's just see that it works we can figure out at least like what is the next mirror element so we can see that for when we get three for three we get four for four we get minus one and for two we also get minus one perfect so now that we have this information all we need to do is when filling out a result array like our final array we will go through nums one so for Num in nums one comes one we will figure out what is the answer based on numbers two so I can do rest dot append e at num and then in the end I can just return rest let's take a look at this go ahead and run this test case and you can see give me the right answer I'll go ahead and submit it and also we get the right answer now this is actually faster than 94 but it really shouldn't be because this is an O of N squared approach it's not necessarily the best one here the best one is something which we call a monotonic stack and it's maybe something you haven't learned before so let's spend some time discussing what a monotonic stack is and so then we can figure out how we can actually just not Loop N squared times here but figure out the answer in just one go in O of n time so let's take a look at how we can do that open up my paint here and I've already have something set up so here's my monotonic stack what is a monotonic stack it is essentially a stack that is either strictly increasing or strictly decreasing that's what monotonic means it means strictly increasing strictly decreasing in the types of questions in which you're asked to find the next grader then you want to use a decrease in monodynamic stack which basically means the items in the stack will all be decreasing maybe like five four three one Etc in the questions that you're asked to find the next smaller element you will find or you will use an increase in a monotonic step okay basically that's the idea of like how you want to use this or how you want to understand to use it here I have a set of numbers 514236 and here I've written down the next greater element so next great element five is six one is four is six two is three is six and six is not half one right and here are basically just printed out all of the elements here what do we do in a monotonic stack we're in a monotonic stack first thing you do is you actually go through and you want to add the elements to the stack but you want to add them such that you're preserving the decreasing stack property what do we do here well first thing we do is we add in the number five because there's no problems around the five what about next we add in the number one can we add this we can because it's still a decrease in monotonic stack because you can see five and then we decrease to one so good what about now four can we add in four we can't add in four because if we were to add in four then it would break the monotonic stack property it would be decreasing and then increasing what do we do then we go ahead and we pop one and then we can see can we add four now okay yes we can add four now so we'll go ahead and add four now notice what happened here when I popped one from here what does it necessary mean well if you think about this really carefully it means that the item that I'm popping the next Creator element must be the item that I'm inserting it has to be right because we're going to the array in order I'm popping this element it's greater than which means it defeats the purpose of a decreasing monotonic stack and so the next greater element of one has to be four and so you can actually see here that we have exactly that next grid element of one is four okay so let's continue so we've added in five one and four and we add in the two we can there's no problem there okay so we add in the two and what about a three can we add another three we can't because it's greater than two so we pop the two and because we're popping the two we learned or we know that the next greater element of two is equal to three and so we can see that right over here why is that the case well because we know that when we're popping the next element must be greater and because we're going in order then the next greater element must be the item that we're just about to insert which in this case is three insert the three now what a six okay in the case for six and we add it in we can't because three is less than so it'll break the structure what do we pop the three and then we understand that three is an x squared element must be six but notice how we can also pop this we can also pop four and we can also pop five so we pop four and four is an X greater animated six and we also pop five next grade element is also six so notice how by using a monotronic stack we're able to determine what the next greater element is specifically using a decreasing monotonic stack let's take a look at how we can do this in code so go ahead and I actually just remove this information that we have here so now let's take a look and there's like a general type of structure you want to follow with these types of questions but let's take a look at how we can do this first of all what we can do is we can Define our stack and what we need to do is we need to go through the numbers too right we need to go through the second array I will do for I and range zero to length of nums two right now what let's just assume that you know we're in the middle somewhere right like let's assume that we already have items on the stack like maybe we have five on the stack maybe we have one on the stack grid and now we're looking at number four here okay we're looking at number four so what do I want to check well I want to make sure that I am only strictly decreasing right so assume items on stack maintain decreasing stack so we want to maintain this decreasing order so what can I do here well I want to check the case in which I can pop elements off the stack here I can check if I can pop so can I pop well how can we check if you want to pop well in order for us to even determine if we can pop or not first of all the stock stack has to exist right so there has to be items left on the stack you can do wall stack and what well then I need to check that the last element on the stack if it is potentially less than the element I'm about to add then I know that I can pop it and I can do and nums to or actually I can just do stack at -1 or actually I can just do stack at -1 or actually I can just do stack at -1 right so this will be the last element if this is less than nums to an I if this is less than the number I'm actually adding on then I know that this is not a valid order so I have to pop This what I would do is I'll go ahead and pop like item and I can do stack.pop stack.pop stack.pop so this will remove this will effectively like remove the one here when we're about to add in the four so we'll remove the one and now so what do I know so I know that this item that I just removed it's an excreted element must be this so then I can basically store in my array so I can do T at item it's next Creator element must be sums 2 and I right so this is the case in which I want to pop let's say I don't want to pop and I just want to add to the stack I can very easily do that I'll just do stock.append and I will append the stock.append and I will append the stock.append and I will append the number I'll do nums 2 at I and that's basically all there is to it in the very end we might still have items left on the stack and so what we can actually do because in this case if you take a look at it in this case after we process all of this six was still left on the stack right so we can just take a look at that and what we can do is while still stack right while stack then e at stack.pop e at stack.pop e at stack.pop is equal to -1 right because there are is equal to -1 right because there are is equal to -1 right because there are no more elements to the right hand side of it so we can do that okay that's basically all we need here and then this remains as it always does let's try to go ahead and test this to see if we run to any problems and rest is not defined and I did not Define it here so as I would find here okay and let's go ahead and submit okay perfect it works so this is an O of end time algorithm and this we're using a monotonic decreasing stack in the next set of problems we might use an increase in one Etc but the concept is the same okay so it's overtime algorithm and also o of n times space because we have to add to the stack all right I hope this helped
Next Greater Element I
next-greater-element-i
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`. Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._ **Example 1:** **Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\] **Output:** \[-1,3,-1\] **Explanation:** The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3. - 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1. **Example 2:** **Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\] **Output:** \[3,-1\] **Explanation:** The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3. - 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1. **Constraints:** * `1 <= nums1.length <= nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 104` * All integers in `nums1` and `nums2` are **unique**. * All the integers of `nums1` also appear in `nums2`. **Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
null
Array,Hash Table,Stack,Monotonic Stack
Easy
503,556,739,2227
1,957
hey what's up guys so i saw this 1957 dvd character to make fancy string also offensive string the string with no three consecutive characters are equal so given string ask delete the minimum possible number of characters to make it fancy uh you can prove that this is unique uh this is i mean you can try to prove okay so but basically for example e you can make it e okay and uh for aaa you can give a one a give uh a okay so i think uh you guys know trick right the trick is that every time you see three consecutive guy or more consecutive guy you replace with two consecutive for example if this 3e you just replay 2e you see 4a you replace 2a okay uh once you know this then you retrieve your play you just consider every uh possible english character in the set s and you count how many of them right if v is greater than two then you may worry about it so you can ask whether three times i is in s using s then you replace any three of them to p two okay replace any three of n two okay so uh this is y okay so for example if you apply at least then they become a sorry a so you need to apply twice okay so this is very brutal for us but uh i can solve this right see you guys next video
Delete Characters to Make Fancy String
closest-room
A **fancy string** is a string where no **three** **consecutive** characters are equal. Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**. Return _the final string after the deletion_. It can be shown that the answer will always be **unique**. **Example 1:** **Input:** s = "leeetcode " **Output:** "leetcode " **Explanation:** Remove an 'e' from the first group of 'e's to create "leetcode ". No three consecutive characters are equal, so return "leetcode ". **Example 2:** **Input:** s = "aaabaaaa " **Output:** "aabaa " **Explanation:** Remove an 'a' from the first group of 'a's to create "aabaaaa ". Remove two 'a's from the second group of 'a's to create "aabaa ". No three consecutive characters are equal, so return "aabaa ". **Example 3:** **Input:** s = "aab " **Output:** "aab " **Explanation:** No three consecutive characters are equal, so return "aab ". **Constraints:** * `1 <= s.length <= 105` * `s` consists only of lowercase English letters.
Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time.
Array,Binary Search,Sorting
Hard
2179
1,727
hey everyone today we are going to solve the Ral question largest sub Matrix with rearrangements okay so we should return the largest Square in The Matrix so simply formula is height multiply width so let's think about this um since we can rearrange the matrix by entire columns we can consider entire columns as a height so for example we can move entire colum at index two this so to the left for example so now um so this entire column is at index one and on the other hand previous index one this is now index two so we can move uh like this but U we cannot move part of columns um to uh to like a left or right so for example um we want to move only this part to left so we swap like a one and zero so we cannot do this we need to um move like a entire column to left or right okay so let's calculate height at each column so we iterate through each row one by one like this and uh so obviously first row is zero Z One height right so at the low one height should be one and two so Y is two so look at the um this column so previous uh in the previous row at index two we have one height right and the current uh height is one so total two right here so that's why we put two here and on the other hand look at the index zero and one and the pre in the previous row we have zero height and zero height right so that's why this is a first height and this is a first height so that's why put one here and then um in the next row so height should be two because the current height is one and the previous height is one so total two and next current height is zero so we should put zero and then so next index two is one height and the previous row has two height so that's why total three right so um look at uh this column entire column so we have one so three height right so that's why we put three here okay next let's calculate the WID at each row so uh we know that if each number is greater than zero that means um there is at least one in each position so we can consider nonzero position as one length for each width so since we can rearange the matrix by entire colums so we can sort each row to move zero position to small index I mean left side so in solution code we sort each row one by one but the image of entire Matrix after sorting is like this so now we are like this and after sorting um so Matrix should be 0 1 and uh one 1 two and Z 2 three like this and then after sorting all zero in the each row I move to left side so our look at the here so we have two Z but now 02 and that means um we have some numbers on the right side so we can consider right side as part of WID I guess somebody wondering are you sure sorting works so let's make sure and focus on 0 to three so this means colum index one we have two heights right and at colum index two there are three Heights right and so we are sure that we can create this Matrix so 0 1 and uh we have one here so one and zero uh one so this entire um colum has two height and this entire col has three Heights right so um since we sort it um each row so we are sure that um so now um index one is two right so we sort this um R based on height so we are sure that after uh index one that means from index two or later at least we have two height or three height right so that's why uh we can calculate um this area so um this height is two and uh this width is two right so that's why 2x two so max area should be four in this case that's how sorting works so um let's see one by one so this is a all calculation so at0 so we have zero height and three wids right so one two three but Z multiply three is so zero right so a is a Max area so far and at 01 so Z multiply um length should be two right here so but 0 multiply two is zero and at 02 so one multiply one right so height is one width is only here so that's why Max area is one and uh look at one Z so height is one and width is uh three right so in this case Max area is three and look at the one so height is one WID is two so three versus two is three right so that's why Max area so far is three and look at one two so two multiply one is two B Max area so far is three so that's why we take three and I look at two Z so Z multiply three is zero so still three max area is three and look at the two one so as I explained earlier so we have two heights multiply two we so total four so now a Max area is four and I look at the three so three multiply which is one so I mean this I think this rectangle so in this case three multiply one is three and we have four Max area so that's why we take four and in the end in this case we should return four as a Max area yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's WR the code first of all calculate the length of row and column call equal length of Matrix and the length of Matrix zero and then so first of all calculate the heights for each column so for I in range and from one to row and for J in range and the rength of column and if Matrix so current position I and J equal one so in that case um update current position i j plus equal so add height from previous row so that means Matrix and I minus one and the same column number J and then uh initialize result variable with zero and then um so um calculate um Max area so for I in L and row so first of all sort Heights in like ascending order so Matrix and current row do sort then uh iterates through sorted height so for J in range and colum and the height should be metrix and Y and J right and the width should be our length of colum minus current index J and the result should be Max and the current ma current Max area versus height multiply with yeah actually that's it after that just return result variable yeah so let me submit it yeah looks good and the time complexity of this solution should be order of row multiply column low Chum so sort each row here and each row has rength of gum so that's why and the space complexity is order of log colum or order of colum so except metrix so the S operation on the height array utilize the temporary working space so which can be estimated as order of um colum in the worst case this is a step-by-step algorithm with my solution step-by-step algorithm with my solution step-by-step algorithm with my solution code I hope this will help you understand my solution code deeply yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
334
hello guys welcome to another interesting video in the series of coding it's called increasing triplet subsequence so let's get started with it given an integer array nums return true if there exists a triplet of indices i j k such that i is less than j is less than k and numbers of i is less than numbers of j and numbers of j is less than numbers of k if no such indices exists then return false so let's try to understand with the help of examples that they have given so here they have given num sorry to be one two three four five and there exists a triplet here that's why it's valid actually there exists a lot of triplets for example one two three four or even one three five two four five and so on so that's why it is true consider this array now 5 4 3 to 1 there is no triplet such that i is less than j is less than k and as well as the values are less than each other in the increasing order so we have to return false okay let's go to the next example two one five zero four six so in this example we can see that triplet three four five that is the indices three four five that is zero four and six is forming a triplet where the indices are in the order of i is less than j is less than k and nums of i is also less than numbers of j and numbers of j is also less than numbers of k so let's try to understand the logic of this code before moving on to actually coding it so let's take the same example which they have given 2 1 5 0 4 6 so 2 1 5 0 4 and 6 so basically we can perform a o of n cube solution but that will be very bad so o of n cube solution is very simple and it is the brute force approach right we can do this but it's going to be very bad because it's going to take a lot of time complexity so we can check for all the three elements and we can form three for loops and various methods but it's going to be very bad so we'll think of a simpler solution so let's think of a simpler solution so what i will do is i will initialize two variables called left and mid okay now i'm going to declare left as maximum of integer value okay just consider it infinity for example and i'm going to declare mid as infinity okay now if i'm going to find any left that is lesser than this throughout the array then i am going to change my left so lets start iterating over each element and if i am going to find any mid element such that it is greater than left but it is going to be lesser than the maximum value okay the highest element that is possible then we can find such a triplet so let's start hydrating then we will understand it better so for example i am going over to my first element okay now my first element is the smallest element so i will change my left and it will become 2 now i will go over to the next element is even smaller than this element so my left will become 1 now i will go over to the next element five so now phi is greater than left so it will occupy the position of mid now i'll go over to the next element zero is smaller than left so zero will become the new left going over to the next element 4 so 4 is between left and mid so 4 will become the new mid and going over to the last element now when i encountered such an element that is greater than mid okay then i am going to return true so 6 is greater than mid which is 4 so i have found the triplet and hence i can return the value true so let's start coding this and then the whole picture will become clearer i hope so we will declare int left to be the maximum of the integer value and then we will declare int mid to be again maximum of integer value and let's start iterating before this we can also give a simple condition that if the size of the array is less than 3 then in that case we can simply return false because a triplet is not possible if the size of that is less than three now let's start hydrating over the array so for int i equal to zero i is less than num start size i plus so let's give the first condition and that condition will be if we are able to find element that is greater than mid so if nums of i is greater than mid then we can just return true so in this case that we just looked at we were able to find 6 that was greater than our mid that means we have found a triplet okay if this condition is not true then we can check if nums of i is greater than left and nums of i is okay so we are going to search for the mid element so numbers of i should be greater than left and nums of i is less than mid then that will become our new mid so mid will become equal to nums of i else we can check for the condition that if nums of i is less than left then in that case left will become equal to numbers of i so that's it and we can give a return false in the end so that's it and it should work let's run and see if it's working so it's working for the first test case that is given let's see if it's working for all the test cases yes it's an accepted solution and thank you for being patient and listening to me
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
343
all right let's talk about integer break so you're given independent break it into the sum of k positive integers so for k greater than or equal to 2 and maximize the product of integer so return the maximum product so basically this is supposed to be easy but it's actually really difficult to code so imagine you have four right so you're gonna have what four equal to one plus three or two plus two right or three plus one right but three plus one and one plus three are the same so i'm gonna just get rid of this so the product of one plus one uh one plus three is well one times three right it's actually three and this is two times two right this is four right so the maximum for the integer four is actually about four right but two is actually what one plus one right this is one times one this is one okay so you cannot have two plus zero because every single value it has to be greater than uh greater than zero i mean it has to be positive sorry it has to be positive so zero doesn't work and again try out another one for the base case three equal to what is either one plus two or two plus one right and everything this is supposed to be the same right so this is gonna be a one times two right so one times two this is actually equal to what here right so for two and three uh they are base case so it's either one or two and for the four or above they are actually depends and this is going to be pretty much it right so uh i'm just talking about the base case so here's the idea again i'm going to draw again so if i have 6 so 6 can be what so i can break it into one six minus one is five six minus two is what is four three two one right so uh i minus one over here i minus two minus three minus four minus five right and then i would have to know like how many possible values i can have right this is what this is one comma uh one comma five right so you can say one plus five right well this is what and this one you can break it into what four three two one right this one you can break it into one three two one this one you can break into two one right and this one you can break it into one so again this is actually uh this looks like what four times a four plus two right and this was three plus three but in this three you can break it into two plus one and then this is what six plus four right but for the four you can break it into what uh four three plus one two plus two something at least one and again the one should be basically so i mean you don't have to worry about one right and again so this is a big problem so it looks like you have a difficult stuff but once you have a base case for every single value and then you'll just breathe up right you will just go bottom up and then you'll sew every single scenario so let me start putting and you'll be able to just follow along okay so uh in this case i can use what i can use without the map but you'll get t-o-e use without the map but you'll get t-o-e use without the map but you'll get t-o-e t-o-e represent time damage t-o-e represent time damage t-o-e represent time damage um if uh time they may exist right so something like this i don't know so i'm gonna just put it into the hex i'm going to map a map and i'm going to initialize to the new hash map right and then i need to know the base case so if i equal to 2 or equal to 3 this is what return a minus one right this is a base case right and i'm gonna just set the default value for the map is one comma one and i will have to return the helper function i'm gonna put dfs and this is what uh this is the type in function so dfs so here is the uh here's a recursion solution so if num is actually equal to zero you just have to return one for the base case and then if you already put into the map right then you can actually say if meta get it's not equal to known then you just return gate so don't try to use map.contents key because map.contents key because map.contents key because uh there should be a stack overflow scenario right and then i'm going to just create a vowel i'm going to just say minimum value for now and i'm going to traverse every single possible value so for example you have four right so this is going to be what one plus three or this is two plus two right and i'm going to just try verse one times three and this three is going to be a recursion solution this is going to be what one plus two so i have to find out the recursion answers for this one so i will just keep updating my current maximum value and based on uh just based on this label right so i'm going to find out the maximum value for this label but in this level i need to find out what is the maximum value in this label right so just uh just turn out the minus solution so i'm going to use some volume so you have to starting from i equal to one this is because the positive integer right zero is not a positive number and this is i listen i less than equal to num and i plus right so i'm going to use the 10 just create a temporary variable for local so i times ef s minus i right so i would just subtract by a value and then one and using the multiplication itself to find out the maximum so now i have a value with one math max 10 comma right and then i would find out what my current num for the maximum value for the product right and i will just return now and this is pretty much the idea and then let me submit so this is un square so why is n square right uh you do have to traverse by uh and unkind for yourself right and then uh hold on sorry so six so you have five four and then three something two and this one you guys have to traverse four three two and so on right so six and transverse untie and then five you traverse a minus one times so this is a square time for the time and for the space for space you're using hashmap all of right so this is memorization dfs now let's talk about a dp solution so again uh if you know the content like if you know the idea right here we can actually store the value for what for the value that we already know right so just for example um if i have a dp so which means i have a table and again right this is uh 0 1 2 and so on to uh to n right and again by default value 2 is actually 1 and others is actually 0. now using this idea the y value so two equal to one plus one right one plus one equal to one right so i'm using this one to actually generate the possible value for what for the rest of the integer so how do you actually do this um give me one more second so uh for the four right you can say one times uh one plus three right is it is equal to 1 times 3 for the return value and this is 2 plus 2 and this is going to become 2 times 2 right so you want to find out what you want to find out like i times what 4 minus i right and then i will go from where uh this is i and this is j right so the sum of i plus j is actually equal to four right one plus three two plus two right and then uh you just have to make sure like um when you do the multiplication if there is a sub uh stop maximum value when you go dfs right when you go dfs there should be a value imagine 10 right like two times eight and then four times six right and then eight is current value for eight but how about you break it down to seven six five four three 2 and there is a value which is greater than 8 so which means the possible maximum product is not 80. it's one of this wonderful value underneath it right so you have to say it's either 8 comma the dp value you store inside uh just at i minus j index right all right so let me restart it so again i'm going to create a sheet pp dp equal to new and the size is going to be m plus 1 this is because i want to just put the index 0 right and the default value for dp is db2 equal to one for ni since we already know since we're starting two right and then we don't need to traverse two again so we're starting three and then we have to say i less than equal to n and x plus first so we have to traverse until only for the two right so this is how it is so for in j equal to what starting from one is positive number right and j less than i minus one j and uh this is pretty much it right so i can update my dd update my b based on what based on my dpi and max.max.max.max j times what um okay i made a mistake so you can say mass on x j times r uh i minus j or comma j times dp i minus j right this is it right and if you notice they have j inside the method max you can pull this j out but i'm not doing this right now i'm just on my solution give me one more second so uh yes oh i made a typo and yes so let me submit first and then okay now i need to pull down my j since they have what they have a comments constant three times and then submit all right so this is pretty much it this is shorter but this is actually really difficult to notice because uh you probably cannot solve this question within i mean doing an interview unless you see this question before all right so for the and space this is going to be n squared for time right all the fun and it traverses to i minus one so it's still going to be n squared for the time this is definitely all the thing right and this is a solution and i know this is a little bit difficult and i can't solve it uh sorry in once like two weeks of freeway so i have to come back to check again the question and to practice about my dp and dfs and i will talk to you later so if you feel helpful subscribe like and i will see you later bye
Integer Break
integer-break
Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers. Return _the maximum product you can get_. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** 2 = 1 + 1, 1 \* 1 = 1. **Example 2:** **Input:** n = 10 **Output:** 36 **Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36. **Constraints:** * `2 <= n <= 58`
There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
Math,Dynamic Programming
Medium
1936
455
hello everyone in this video I'm going to explain you uh the sign cookies problem so the problem goes like this so let me take example and explain I think you have gone through the problem so you have understood what problem statement says so basically they'll be given us two arrays uh G so G implies the grid array and then yes the copies array so uh G there are three elements in the D which means we have three child and then first child has great factor is one second two and third children is three and then we have two cookies all tastes as uh one comma one sorry it is not the it is the size so basically uh cookie size like first cookie size is one second is also one and according to the problem they given like uh G of I has to be less than or equals to S of G which means uh the great factor of the particular child has to be less uh than equal to the size of the um cookie so in this case uh what we can solve is for the first uh children uh this cookie this particular cookie can be assigned so answer will be one and for this child we cannot assign this particular cookie because this cookie size is one but child creats at least of size two and also similarly for this child uh he needs cookie of size three but right now we have only one so in this case answer is one let me take one more example uh in this case we have two child and their grade factors are one and two and we have three cookies of size is 1 2 and three so one of the ways can be uh for one child one this cooking can be assigned because it satisfy this condition G of I inal of J also uh like second for the second child this cookie can be aside so answer equals to two and one more combination would be like for this child whose gr Factory is one we can assign uh cookie of size two because uh 1 is less than equal to two also for this child a child to we can assign cooki of size three so this can be also a possible answer so but thing is in this case both the Childs uh satisfies their cre conditions so in this case answer true let me do one more example uh in this example as you can see a child with a great Factor one can be assigned with this cookie and child with gr factor three can be assigned with this cookie and two child with two can be assigned with cookie two so in this case answer will be three so the idea of this problem was basically um like GD factor and cookies can be shuffled so the problem need not give in sorted way so our approach would be first we have to sort these arrays both arrays we have to sort dat so our algorithm will go like this we have to sort array sort G array and then sort s array which is basically size of the cookie and then uh what we will do be doing is we'll take a two variables i z which basically keep track of the uh G like grid factors and then we'll take one more variable g j will be also assigned with zero and this will keep track of the yes like the size of the cookie so in this case as you can see 1 2 3 is already sorted one after this line This will be sorted and then one this also will be sorted so our condition would be like we'll check if I is exhaust we'll check till if I is exhausted or till J is exhausted so this would be G do size and J would be S do size so in this case what I'll be checking is I'll be checking if uh great factor of I okay great factor of I if it is less than or equals to uh size of the cookie so in that case uh that particular cookie will be assigned to the um that particular child so and also I'll keep one variable as answer impul zero so this implies right now we don't have any child who is assigned with a cooki so if this is the condition so in this case what I'll do is I'll increase the answer also I'll increase I uh because let's say for this example uh G of I is less than equals to S of i s of G so 0 so it is equal so this child has fulfilled with the cookie so now we have to go to the next one so when we go to the next one G uh pointer has to be incremented also with the GP has to be incremented so that is the reason I'll be doing I ++ and reason I'll be doing I ++ and reason I'll be doing I ++ and g++ okay and if this is not the g++ okay and if this is not the g++ okay and if this is not the case then in that case so like what was the case G of I is less than equal to S of J so if this is not true which means s of J G of I which means great factor of that particular child is more than the size of the cookie so since array arrays are sorted so as we can increase J when we increase J so uh like s of J will be pointing to the greater like greater cookie size so again we will be checking the same condition so in L's case what I'll be doing is I'll be simply increasing j++ so this is a condition and at last j++ so this is a condition and at last j++ so this is a condition and at last I'll be retaining as answer so let us dry run for this particular case uh this whatever algorithm we have written let us tryn for that so first our algorithm says we have to sort this so our sorting will give one 2 and three and sorting of s will give 1 2 and 3 next we'll be pointing our I to this position and then J to this position next what I'll be doing is like we have answer variable and it is initialized to zero uh in this case answer I written one no it will be answer as three so answer I be initialized to zero and uh according to our condition G of I is less than equal to S Sub J so one is less than equal to one which is true so initialize answer to one and increment the J pointer also increment the J pointer I and J pointer we to basically now s of I again equals to S of J so increment answer increment I increment G in this now also both are you also increment this thing answer no I be pointing to the like null and J will also be pointing to the null so for loop I mean while loop gets executed and then we'll basically return three which is actually the answer so now let me code and show you how you can find this so according to our algorithm we'll go so we have to first sort G g. begin comma s do end sorry this is so G so basically we have sorted G and then we'll sort s and then as usual you have to take one answer variable and initialize to zero and we have to take I variable which is point which is basically the pointer to the G uh vector and then J which is basically pointed to the S vector and we have to check till I is less than or G do size and J is less than s. size so can not if great factor of the J is less than or equal to the size of the cookie so in that case uh that child will be fulfilled with the cookie so answer has to be increased and I increase I also I increase J and if great factor is not satisfied which means the size of the Cy was less uh so we have to increase the G pointer which is basically the uh size of the cookie pointer so it will point to the next uh greater size cookie as you can see from here uh like in if in both conditions J are there okay so one thing we can do is we can remove this lse condition and we'll put outside J like in all the cases J is increasing basically the cookie size uh cookie array is been increasing and it last we have to return our answer let me run this uhing take b g submit the code so the reason why uh wrong answer is I put here I it has to be in G it got accepted so let me analyze the time complexity uh like we're basically sorting both the arrays so a sorting will take in login plus like n of G I'll put it as here because it will it is basically the gr array and N of size of the cook AR n of s I'll Take N of log n of s so once we sort and we have to one by one we have to go to the uh one by one we have to check the condition if GOI is less than equal to S so as you can see from this uh loop every time G is increasing and J is less than SI and J has been initialized with zero so basically it is n of size of the cookies so this is our time complexity we go off and the space complexity is O of one so thank you for watching
Assign Cookies
assign-cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child `i` has a greed factor `g[i]`, which is the minimum size of a cookie that the child will be content with; and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, we can assign the cookie `j` to the child `i`, and the child `i` will be content. Your goal is to maximize the number of your content children and output the maximum number. **Example 1:** **Input:** g = \[1,2,3\], s = \[1,1\] **Output:** 1 **Explanation:** You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content. You need to output 1. **Example 2:** **Input:** g = \[1,2\], s = \[1,2,3\] **Output:** 2 **Explanation:** You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. You have 3 cookies and their sizes are big enough to gratify all of the children, You need to output 2. **Constraints:** * `1 <= g.length <= 3 * 104` * `0 <= s.length <= 3 * 104` * `1 <= g[i], s[j] <= 231 - 1`
null
Array,Greedy,Sorting
Easy
null
863
hey yo what's up guys babybear4812 coming at you one more time uh as i record this video it's super claudio uh but as the old adage goes when uh when rain brings you sorrow lean code brings you joy and so here we are i don't think there's an average that goes like that i just made that up um anyways 863 all nodes distance k in binary tree uh the companies that like this one are amazon and facebook more than anything and the problem goes as follows we're given a binary tree with the root node root that's passed in a target node as well as an integer value k we need to return a list of values of all the nodes that have a distance k from the target node the answer can be returned in any order so we're given a tree a target is five and k is two the output is seven four one if we take a look at the tree that represents five is the target node so from this node five we want to go k steps in this case ks2 two steps in any direction and return a result or return a result array of containing every node that's k steps away in this case getting to four is two steps so getting to fours two steps getting to seven is two steps and getting to one is also one step so notice we're going kind of up through the root and down and that's gonna be that's what makes this problem a bit tricky uh we're told to note that the inputs root and target are actually tree nodes the descriptions of the inputs are just above are just serializations of these objects and we're told that uh here as well so the root is a tree node and so is the target so i'm just gonna get rid of these just to make the code look a bit cleaner we're gonna return a list at the end of the day all right so let's think about how we would do this problem i don't think this one's too trivial it's one of the harder medium tree problems in my opinion so i don't know what your first approach was when you tried this but for me i started kind of scratching my head over maybe thinking about labeling each of these uh each of these notes so i thought to myself well maybe you know maybe we do a dfs and we do one full walk through the tree and we notice that each of these exists at a certain depth and so maybe the root is at that to zero and then these two are at depth one and then we've got you know depths of two for all these and i kind of labeled them as such and then i said okay well you know maybe we could just say let's keep all these in some sort of array and then let's loop through the array at the end and just pick out the ones that have whose depth is a difference of two from our target node so if our target node is five and its depth is one let's pick up anything with depth three okay that's fine so you realize that works here then you notice we missed this one right so we missed that one because it's the same depth so okay then maybe you think to yourself um maybe these could be negative you know and we try to pick it up this way and we can try that um again this is an approach that i kind of went with and in quite quickly you'll notice that there are circumstances where this will this is also going to fail um namely if all of the all the trees maybe are on one side for example all the nodes are on one side of the tree and we can try to get clever this way but i don't think there's a and like a super obvious approach to take in doing something like this or even labeling with coordinates in a similar way that we would with a vertical order traverse and you can find the video for that i'll leave it in the description down below because that's a really good question as well and so like many tree problems i think what makes this tricky is the fact that we don't have access to our parent node i have access to my child nodes for my children but not my parent if i could have access to my parent i could then just hop this way and hop the children and count my steps from when i actually get to the target node unfortunately that's not the case that's one observation to notice and actually i didn't maybe i'll just write this here k was two here and the target i'll try this t and then n and for node like nabi and then node five was our target this would have been again this is this would be trivial if we could have access to our parent that's one thing the other thing you might want to notice actually is that perhaps this question would be more trivial if this was a graph and i know that all trees are graphed but let's think about if we had this represented in a graph like structure like with an adjacency list for example if i had this as a graph like structure where you know it was directed and hypothetically i could actually since you know we five and one are at a distance of two what if i could jump this way and so what if we had a i guess this would be a connected bi-directional graph connected bi-directional graph connected bi-directional graph that essentially they're not essentially but that was just it was a standard graph and it was one that we can manipulate and work with like we would answer any other graph problem and i think that noticing this is the key to getting to one of the solutions this problem does have a few solutions i'm going to just focus on one and i believe there are a few that are equally efficient so i will show you guys kind of a top efficiency one and if you can notice and think about the fact that if this were a graph this becomes a bit easier because all i've really got to do is to say let me start from my target all right so i mean maybe the name target is a bit deceptive here uh but the target is going to be five over here okay and then if i'm looking to take k steps away well that sounds like a classic case for a breath first search because i could essentially cover this so one first step this is almost like my step number one all these nodes three two and six are one step away all the following notes so the children of three two and six maybe that's these two and uh and the one here maybe i could have drawn this a bit better these are two steps away and then these ones over here oops and then these ones over here are three steps away and so on and so forth and so if we actually had a graph like this and then we just did a standard breadth first search this problem becomes pretty trivial and so surprise what we're going to do the approach we're going to take is to actually take this tree to convert it or at least create an adjacency list to represent a connected and directed graph and then from there once we have a graph we can actually do a standard breadth first search grab all the notes that are k steps away return that result go land our dream job and make millions all right so the approach we're gonna take here is going to be that one i hope that makes sense i hope it's clear again i don't i'm not sure that's an obvious mental step to take and kind of that quantum leap of imagination to go from saying i've got a tree let me turn it into a graph this problem i think pretty naturally calls for it though and so i hope that at least when you see this one if this is something you haven't done before then maybe you've added one more tool to your repertoire into your toolkit and you know in your collection of methods and how to go about solving these problems all right so i actually think this is all the theory that we need to talk there won't be much more than this the rest of the details will be in the code will be more or less straightforward but it is a bit verbose this time uh there may be ways to shorten it down that i just i haven't figured it out but anyways let's dive into it and we'll take a look at how we're going to deal with it from there so maybe we'll start by doing this let's start off by doing error checking as usual and then we're going to do something like we're going to turn it into a graph and then after we turn it into graph we're going to do our qpfs on graph and finally i'm going to return my result and at some point i'll define a result variable and we'll run with it but for the actual error checking let's think about the variables we're given and how we can maybe take on some edge cases right off the bat so i'd argue if we're not given a root so if we're not given a root or we're not given a target then if we if so if both of those are missing then i would say let's just return an empty array because there we can't really make a path happen if we're not given a root there's no tree if we're not given a target there's nowhere to start from the other one that i would put here is with respect to k if k is zero right l if k is equal to zero what that means is that we want zero distance from our target and so all we would have to do is return a an empty list that i presume would keep our target and i haven't looked through the it's just k can be zero and so if k can be zero then the only item that's zero steps away is the target itself so that's why i'm including that my error checking then we're going to turn this so we said our next step after error checking is going to be to turn this into a graph and so maybe i'll do something like a json list is equal to self thought uh we'll call it treat the graph and in there i'm going to pass my root variable and what we can do and that's going to be for this step i'll obviously write out that function we'll go through that step by step but i'm gonna do that all in a modularized form the bfs we can do within this function itself so we'll go here and we'll define treat the graph uh self and we said we're gonna be passing in a root all right so if we pass in a root or sorry let's think about this we pass in a null root where we've already taken care of that error some i'm not too worried right we're not going to make this a recursive function per se so let's think about this um what i want to do is the following is i want to say let me create some sort of i'll create a result and that's going to be our adjacency list i'm going to return that result the reason i'm calling it result is not adjacency list i just don't want to well we're not going to actually have name collision so we'll call it adjacency list here now i want to be able to loop through um each one of these items so i'm going to start at the root and then add on all the children and grandchildren and all the kind of ancestors going downwards not your ancestors only upwards add everything into this adjacency list somehow so what i'm going to do for this i'm going to keep a queue of every item that i see and as we're walking through the queue we'll keep on adding that to our list so q is going to be equal to dec and i'm going to begin by appending to my queue the root and what we're going to do is we'll just jump into the loop that says while q so while it's not empty we're going to do the following we're going to say uh that the current node that we're looking at is going to be q dot pop left since this is a queue i want to pop off from the start so we're popping off the left side then i'm going to say the following uh if current is not in if that node is not already in the adjacency list then what i want to do is i want to say adjacency list of cur is equal to some an empty array and then we're going to do the following if we have a left and a right child so if kurd.left um i'll pass for now if kurd.left um i'll pass for now if kurd.left um i'll pass for now if kurd.right kurd.right kurd.right pass and if it's got either these two children or both we're going to want to do a couple things we're going to want to add the child so maybe we'll do this we'll add child to parent adjacency list we're going to want to add parent to child adjacency list so again we're going in two directions so i'm going to want to do both of these and finally i'm going to add child to q and i'm actually going to do both of these steps here in if both if we have a right and a left child once we're done and there's nothing left in the queue we're just going to jump out and return the adjacency list and that'll pass it down into here again i'm not really doing anything new here apart from literally just creating an adjacency list there's no funny tricks um yeah that's all i got to say for that so we want to add the child to the parent adjacency list so uh i want to say if um or i want to say adjacency list of cur dot append curve.left again we've dot append curve.left again we've dot append curve.left again we've already checked if it exists now we want to add the parent to the child adjacency list that list may not exist yet okay so the child may not be in the adjacency list so what i'll say is um if kerr dot left not in adjacency list similar to how we did up here then we're going to say adjacent to list of our left child is going to equal empty array and we're going to take that array and append to it our parent all right finally we want so that's the second step and finally we want to add the child to the cube so we're going to say q dot append root dot left and what i can do here this code is all going to be the same except for replace the lefts with the rights i say right and again those are the only three things i'm doing so i'm adding the parent i'm adding the child to the parents adjacency list i'm adding the parent to the child's adjacency list and then i'm adding the child to the queue so we can process that one next this block of code right here this function is now done it's completed unless i've made any really silly errors which i'm going to have to go back and correct but this module is done at this point we've done our error checking we've created an adjacency list so we can now actually treat this question like a graph question and the way to treat it like that is to now do a breath per search on the graph in order to find excuse me in order to find all the nodes that are k steps away from our target now we're going to have to do a couple of things i'm going to have to determine a result array i'm going to have to determine some sort of depth so i want to start from a depth of zero and say let me track how many steps i've taken along the way once i've taken my case steps whatever items are in the queue at k steps i'm going to add to my result and then i'm going to break up so i'm going to track the definition the depth is going to be zero um like with many breadth-first zero um like with many breadth-first zero um like with many breadth-first searches we're going to want to keep a visited i'll use a set because it's got instant look up so that we're not uh going from parent to child back to parent and jumping forward we only want to go outwards all right and finally beyond that we're obviously going to need a cube which i'll use the kind of the same syntax i used up here and now where we want to start with our breadth first search is going to be from the target node right so i'm going to say cueda append target so this is all we're you know what i'm going to make a lot more space and kind of move things down a bit where we're going to make we're going to be starting our depth first search from here and what i want to do is as follows that i want to say while q so while there is something in the cube and also what i'm interested in is that the depth is less than or equal to k reason being if i have a depth of two and you know let's say that uh so i'm at this five once i've taken two steps out i don't want to take three steps and four steps and search because i mean i've got my answer right so when i get to the case two i'm going to append those items as they are and then i'm going to break out of this and just return the result we don't want to go any further than we need to from here we'll see the following we're going to say that the current item we're working with cur is going to be equal to q dot pop left or actually uh i take that back i think that i'm going to have to do this in one second because what i want to do first is i want to start looping through the queue at whatever length it's at right now and pop off every item uh you know individually so i'm going to do this in a for loop and i'm going to say for some under so we're not going to need this variable so for underscore in the range of the length of the queue i'm going to say that oops i'm going to say that cur is equal to q dot pop left alright a little bit too much space so that's fine uh curve is equal to q dot pop left so now we're looking at our you know at our current that item that we just popped off we're looking sorry i'm tripping over my words we're looking at the current item and in this item that we're looking at we're going to want to search through um all of its children and take steps there so we're going to say for a child and adjacency list at kerr we're going to do the following we're going to say uh q dot append child okay we're going to do q dot append child and then we're going to say the following so it's going to be in the queue we're going to visit it but once we've appended all these children onto the queue what am i going to want to do i'm going to want to say if my depth is equal to k so if i'm actually my second step if my depth is equal to decay i'm going to want to take my result and append to it not just the current node that i'm at but i think in the return value we want to return the sorry in the return array we want to return the values not the actual nodes i believe um return a list of the values of all nodes so i'm going to append curve dot oops curve dot val and once i do that once i jump out of this for loop uh because i've gone through this entire first step first layer of depth i'm going to say that plus equals one and i think that this should actually be all the code that we need um let me i'm going to try to run this really quickly and then i'll go through and explain just to make sure that everything about this bfs makes sense so let me try to run this super quick um i forgot to do something and let's see what i forgot to do uh we're popping off the left here i'm getting stuck in an infinite loop ah i'm getting stuck in an infinite loop because uh well i haven't added to visit it so i think i'm jumping between the visited back and forth and i'm just i'm never adding an item into visited so i just forgot to use that entirely so i'm popping off this current value and maybe what we'll say is uh if occur not in visited oops visited then we want to do all these things right so if oops i only want to have these in you know maybe move myself a bit there we go a bit easier to look at um so if current is not invisited then we want to do all this um afterwards we're just we're going to want to see when we're done with this we're going to say uh or sorry visited all right and so this is gonna make sure that we're not jumping between the two steps uh over and over again let's see if that fixed it and i've done something wrong again let me see what i did here i'm really sorry about that i so i just fell in the air some of you might have caught it while i was going through the code um in the actual queue i am appending root dot left instead of kurdal left and andrew thought right instead of kurdot right that was frustrating i'm not even gonna i'm not gonna admit how long that took me to try to find um let me see if this will work now i do apologize for that mistake at least there was a small one conceptually everything else still holds water um or so it should and we've got another area i really don't feel like re-recording this re-recording this re-recording this um let me take a quick look because i found it so one final mistake here it is when we're returning uh in this edge case i want to return the target value not the target all right i want to return the target value i was returning the entire node as opposed to the node value this should now do the trick um man this is a headache to finally get it across the line but there we go as you can see the result is very favorable um i'm going to move this over and see if i can get the entire solution on the screen for you as a really quick recap we did our error checking we noticed that we could best solve this problem or one good way to solve it would have been by creating a graph out of this tree so we made an adjacency list using this function over here um again i didn't really do anything uh super clever smart here just took the nodes made an adjacency list and then finally did a standard breath first search where i simply said let's keep track of the depth that we're adding we'll break out when we've hit the depth we wanted and appended everything to our result so that's it guys i'll move myself back here ah like comment share subscribe the whole nine i hope you guys enjoyed this and i hope it was helpful i do mean it um any other questions any questions on this comment down below any other questions you want me to solve same thing and i'll see you guys next time peace
All Nodes Distance K in Binary Tree
sum-of-distances-in-tree
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **Output:** \[7,4,1\] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. **Example 2:** **Input:** root = \[1\], target = 1, k = 3 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 500]`. * `0 <= Node.val <= 500` * All the values `Node.val` are **unique**. * `target` is the value of one of the nodes in the tree. * `0 <= k <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
1021,2175
820
Hello guys welcome to another interesting video open a desi shop ideal for today the problem it is the goddess challenge of today only its caller shopping cooling off but so let's get started to the problem given there goals for stated in question are of course So 2014 Russia And Finally Tears Return The Length Of The Short Recent Is Possible To Any Valid In Cooling Tower Select Example To Understand What Is The Example Of The World's Richest Man In The World Of The Times From 16th Quote Solvency Attendees Printing This Particular So Let's Remove poverty from taking only possible rates like this quid time in the light of rs festival comment you use chapter festival rule in right side ki agila use this character according to experts to find the length of the return of the length of distance and time for The length of the world in the form of ok bed is a new set of words between Adheen Neetu those unique values ​​for example if you are unique values ​​for example if you are unique values ​​for example if you are unique values ​​and unique values ​​in repeating itself and subscribe to that your an edit suite control unit year then Words words are being passed this that in this function some words start with words but and solar universal book store in this site yet another set of casts rings to and similarly do the same thing but will give water nor will it go into different parts of the Water into his fast fall from set vansh ios guide overs ke saunth and toe parts of rs.10 on the bed the amazing for example is consider all of rs.10 on the bed the amazing for example is consider all of rs.10 on the bed the amazing for example is consider all the first time but i don't like or subscribe 100 index subscribe point to parts of the plus 100 We write the sub school parts dot subscription for finding most and subscribe our back side this I'll get I 'm the first time set two to 'm the first time set two to 'm the first time set two to WhatsApp chatting and siding we list I OK fennel just subscribed will be shift the sentence of to decide Example of a WordPress Comment You Dance and Finally I Will Have You Not Just a String of Villages Have Learned How to Write to Vote for You APhoto Which ID is Equal to a Student Beaten That It is Not Equal to X Dot in That ID Plus OK SO IT INSIDE IT BETTER OBJECTS 1234 THE FIRST WORLD OF S2 FORUM IS NOT DOING ITS PARTS OF WRITING ALL PARTS OF ITS IS WILL GIVE YOU TOO PARTS OF DECISION AND K ON SWITCH WORKING WITH FLUT SAMRDHI SOLUTION SITES FOR Watching A Sachin Accepted Solution Significantly
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
144
Everyone and welcome back again Tu Coding Ispat Delhi Challenge There can be only two maximum routes from one route or from one note There can be maximum two children Visit all of them He is the priority person As if I explain in this one, then can you do this route You will start from here, we will add it, after that we will add it to the left, whatever we get, we will keep adding it and along with it we will keep returning, then while going, you will be left most when you travel. What you have to do at the beginning is to go to the left side and keep adding whatever you find as you go, like in this case, if I see that I will start with the van, then first I will add the van. I made a list in my list and add the van. Done, okay, now I had to go to its left, there is no one in the list, I have not returned, I have to go to its right, I went to the right, I got you, I added you, I had to go to the left, because I went to the left, I got three, I added three to the left of three. I have gone, there is nothing on the left, there is nothing on the right, I went back and on the van, we are green and our whole tower is completed, so 1 2 3, this is our list, this is our answer, you have to return it, look, it is an easy question. Now I am doing this with the help of this tag. In the next video, I will tell you the solution. Now let's talk about the solution. If I have to make a list, I will reduce it by one. First, I will make a list at the top so that it We will fill the list and return it at the end. List of India Let's Quality. If this is created then we will directly return this list. At the beginning whenever we find null in the root, if nothing is found then if root is equal to n then we will return only Simply return the list. Return an empty list. There is no need to fill anything. So first add this route, then add the value of the route list.ed. Add the value of the route. root dot write jo You have got the value, add the root or whatever element you want and call it on the left. When the left is finished then put the right one. Our list will be complete, now we will return it. OK, it is accepted.
Binary Tree Preorder Traversal
binary-tree-preorder-traversal
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,2,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,255,775
1,008
hey everybody this is larry oh this is day 13 for 14 yeah 13 day 13 of the lead co daily october challenge uh hit the like button subscribe and join me on this card let me know what you think about today's firm and all the good stuff uh yeah i took a nap so i just woke up even though it is like 9 00 p.m in new york though it is like 9 00 p.m in new york though it is like 9 00 p.m in new york probably a dubious idea but anyway i don't know it is what it is let's get started on today's problem which is uh construct binary search tree from pre-order traversal okay pre-order traversal okay pre-order traversal okay this is pretty i don't know if this is easy or hard it is just that um it does come up a lot in when you learn about these things um so at least an algorithm and stuff like that they would tell you how to do it so i think i have some idea about this but let's actually read the problem i'm just reading it from the name sorry there's like a lot of random stuff on my desk for some reason anyway okay so give it a pre-order traversal so give it a pre-order traversal so give it a pre-order traversal okay construct the tree and return the root okay uh okay so let's think about what uh for these form i yeah think about the invariants and then let me look at what the thing is so n is a hundred so that's um that's interesting and that means that you could do something like an n square um you can even do something in n cubed but i don't think that is necessary but n squared is definitely fine so that's something that i would think about so that now in the invariant is that okay so the pre-order means what does priority mean pre-order means what does priority mean pre-order means what does priority mean right priority means that the first node that we see is going to be on the top right so then here um what's our output what's this output mean oh i guess that's just a tree and string representation okay so we return a tree node okay so yeah so we get an eight and that means that everything be um so then now we do um a period if you will by that eight right so everything uh everything that's smaller than it's going to be to the left and everything that's bigger than it is going to be to the right and in the pre-order that means that this is the pre-order that means that this is the pre-order that means that this is the next note and so forth okay i mean the way that i you should do this yeah okay um yeah and i think the way that i usually do this is i would say with a global wearable you can definitely do it in a little bit better but i'm just going to do the end square way and then we can play around with how i would maybe optimize it uh maybe i should take a longer nap i don't know i haven't been sleeping much the last week for some reason uh probably because i was staying up to watch dota or something like that i don't know maybe it's just the weather i don't know anyway so yeah so that let's from that though you can definitely do something in n squared very trivially um by like i said you look at the node and then you just divide left and right so okay so let's look into that um i would say i'm just trying to think whether you can do better in an easy way but let's actually just start with that and then we'll figure it out right so um how do we want to write this yeah let's just do root is equal to none maybe and then we turn root and construct we have a node and yeah maybe just left and right uh my left right is kind of weird but yeah it's fine and then here we do root is equal to construct uh maybe just left and um sorry friends i'm a little bit i don't know i'm just not feeling that well today maybe i don't know sorry about that um but yeah let's actually construct this from here if left is equal to right then we have one note left so let's just do return tree node of uh what is the pre-order of left because uh what is the pre-order of left because uh what is the pre-order of left because it's equal to right so it doesn't matter which one otherwise um you know current route is equal to uh tree node of pre-order of left pre-order of left pre-order of left and then now we kind of um basically what i'm doing is just constructing it from a segment of the pre-order traversal and then here now we pre-order traversal and then here now we pre-order traversal and then here now we have the first order so now we keep we're going to the right until um some middle is equal to left plus one maybe yeah are these numbers unique i think that's the okay they are unique okay um yeah so this is inclusive say if pre-order of middle is say if pre-order of middle is say if pre-order of middle is greater than current then if that's the case then we can well maybe even return but break first then uh current root that left is equal to construct left plus one middle uh no because this is middle if this is middle is greater so then this is middle minus one right also just in case if this is the case we turn none otherwise and then this is just middle and then right inclusive right yeah otherwise uh i guess in this case we can just return current otherwise then that means that middle is greater than right in meaning or um every suffix is every number in left plus one right is smaller than pre-order left so that means that pre-order left so that means that pre-order left so that means that everything's to the left right that's basically yeah going dot left as you go to construct left plus one uh right and then current route that right as you go to none and then return current route and i know that this is true but i just wanted to print it out for a little bit of symmetry maybe um and here of course you can just actually do this uh this is gonna be o of n squared but we can definitely do better but i just wanted to at least get it right first um and here if the first number is greater than that oh well this would be an infinite loop because i don't increment but yeah if the first term was greater than that already goes okay let's give it a run did i quickly move i think i could do multiple times but oh whoops uh it's kind of wood uh dot value uh that looks okay so i think we're mostly good here we can play around with some numbers i don't know that this is yeah whoops okay maybe not okay fine let's just give this a minute and then we'll see what happens and apparently i've solved this one two three different times this is the fourth time i didn't even remember this uh but yeah i think one thing about prematurely optimizes that given n is a hundred even n squared is going to be running really fast so i wouldn't really worry about it i've done even earlier before but yeah so this is going to be n squared because for each um because in the worst case um you have a linked list for example and this would go to the last element um so this would go to the last element before um yeah so you this would go to the last element and therefore it's going to be n squared because it just takes one element at a time and of course this end time so this is going to be n square um you can get this down for sure um i would practice that what sorry friends i'm struggling a little bit today just talking i mean i don't know why and you can see it so my apologies having an off day uh i don't know but you can kind of see what my code and i think i probably have older videos so maybe check out the older videos and let me know how that goes maybe today i'm doing a little bit bad but how did i do previously uh did i do it the same way at least i'm consistent actually it seems like i mostly did the same thing actually this is slightly cleaner but yeah uh okay i think that's all i have for today i don't know i my words are escaping me so maybe check out my older video um apologies anyway stay good stay healthy to get mental health i do have a good streak going so oh well uh i'll see you tomorrow and may hopefully tomorrow be slightly better my apologies anyway bye-bye stay good
Construct Binary Search Tree from Preorder Traversal
binary-tree-cameras
Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_. It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases. A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`. A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`. **Example 1:** **Input:** preorder = \[8,5,1,7,10,12\] **Output:** \[8,5,10,1,7,null,12\] **Example 2:** **Input:** preorder = \[1,3\] **Output:** \[1,null,3\] **Constraints:** * `1 <= preorder.length <= 100` * `1 <= preorder[i] <= 1000` * All the values of `preorder` are **unique**.
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
1021
1,980
Hello Welcome Back Friends Today We Are Going to Be Discussed Problem 1995 Unique Binary Spring The Governor of None in Unix Banner Spring Switch Off Planning and Return Winery String of Land in That Was Not Appeared in Effigy of Multiple Answers You May Return of the Day 102 Ago Have Been Given Minor Strings of Length in Three Years You Can Still Visit Cylinder to End Will Have to Return the String of the Same Land Which Does Not in the Least for Example 11:00 Took Another Example Which 11:00 Took Another Example Which 11:00 Took Another Example Which Example for Discussion 110 Have Given Another Three Lens Of Three Streams Auckland Three Layer Of Minor Springs Wave 0 And You Have To Find Out Any Remaining Binary String Of Links Regional Which Is Not In Never Give Your Inputs At Song How Were Going Dresses Loot Generate All The Language In English Language 10,000 Language In English Language 10,000 Language In English Language 10,000 Generated From - Generated From - Generated From - The Amazing Link And Can Return Of The King Is Not Given The Giver 10 Ki And In This Way There Oven 100 Grams That We Can Be Written In Of This Cream Actually An Answer Like Share And You Will Like Ajay Who Will Return Industry Length In Which Is Not In Every One Of Us Will Just Edit Interwar Result Second Year Result Date Air Force Which Give The Like This In A Day Strings Pending Link Will Were Passing Year Aaj Loot Se Investment Example Will First Year And Will Cost Springs Us thing2capture result do you want to give back from the receive method and share * pass the given number set so what you have done this guy took this here and there share * pass the given number set so what you have done this guy took this here and there retracting the head of the input - 30 retracting the head of the input - 30 retracting the head of the input - 30 forming even number set and where passing Even number st into this matter and in the beginning distic s and unity allegation both mt servi and where passing no0 languages ​​in and for example for others where languages ​​in and for example for others where languages ​​in and for example for others where discussing a free and all finally spring set isi sadhe better you know like oo want to see the Get Results 100 110 Tracking Setup Not Be Reminder Set Souvik News Date Final Year The * All Binary Saturn Will Just Be The Year The * All Binary Saturn Will Just Be The Year The * All Binary Saturn Will Just Be The First Element From This End Annual Return Readiness So As You Can See In The Beginning S&amp;T Readiness So As You Can See In The Beginning S&amp;T Readiness So As You Can See In The Beginning S&amp;T Will Be Empty And How Will Gradually Common Wedding Life One And Destroy You Can See You Will Fall Recursively And Will And One Here And Will At Zero Year To The Given String Gas And S Victims S Equal To Cash Plus Two You Will Two Actually Solid Will Generate All The Final Spelling Of Link And Share Where Twins The Condition Check When They Find The Time Link Per To You Are Looking For Late Se Guzar Looking For Link Free In The Example Dengue This Point Se Hu Is The Best Result Will Have Generated Reddy Already Darinda Input St Kitts Not Dare Interesting Fact Which Adds in to our results and well written update pimple implementation-defined implementation-defined implementation-defined unique - cream unique - cream unique - cream song height your life many examples for example of two and third example of two so let's do work is run in this joint secretary one is generator tweet seven is of Because it is not drink tea input and every year they have given 100 developed also not her in this important to have so they can return sugar of the following is not fair of that submit solution and mix and this work to pure solution is working find 200 Aa Ki Sudhir Special How Are You Have Defined In Unique Finally String Of Problems Yudh Just Quick Recap Hui Have Implemented Recessive Generating Spring And Gradually E Like Your Page To The Winner Of The Giver Subscribe Result And Will Return Gift Element From The Result Ho To Ise To Solution Play List The Like Button And Subscribe My Channel Thank You For Watching My Video
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
232
hey everyone welcome back and let's write some more neat code today so today let's solve the problem Implement Q using Stacks if you don't remember what a q is it's a first in first out data structure so for example we have a few operations that we can perform we can push elements into the queue and this case they're going to be integers we can pop elements from the queue and those are the main operations we'll quickly go over these two but just to keep things simple we're going to focus on these Peak is basically just going to return the element at the front and the other function is just to check if the Q is empty or not so just to quickly simulate suppose we do a push we push one suppose we push again two push three push four just to be clear this is the front of the Q This is the back of the Q we push to the back we pop from the front so now if we were to do a pop operation we'd want to remove one then we'd want to remove two etc so when we say we want to Peak an element we are just going to return the element from the front without popping it okay not super complicated but our job is to actually implement this data structure with two stacks and if you don't remember what a stack is it's kind of like this except basically we'll push one we push two we push three we push four and then when we remove from the same side so now we want to pop four pop three pop two we don't pop from the other side this is called a stack and it's pretty easy to implement because removing typically from the end of an array isn't very difficult we can kind of do a soft delete like if we were just maintaining an array and we had like okay the length of the array right now is four therefore this is where the last element is and we could delete this element without actually deleting it we can just take this pointer and shift it so Stacks are pretty easy to implement I go over this I think in my data structures beginners course a lot more in depth if you're interested but clearly the problem is in the queue we remove from the other side that we push from so removing from an array over here is not as efficient because if we want to remove this we kind of have to push everything over so that ends up being a bigo an operation and if you try to handle it with like the soft delete that I just talked about you're going to Real iiz that the pointer here like let's say we deleted all of these now our pointers all the way over here look at all that unused memory again I go over stuff like this in the algorithms courses but you don't need to know this super in- depth I need to know this super in- depth I need to know this super in- depth I think to solve this problem so back to the problem given this type of data structure two stacks how can we try to solve this problem and they actually mention in the problem description that it's possible for us to solve this in such a way that we use two stacks and the a average case time complexity of all of these ends up being constant and that's actually the hard part of this problem so first we're going to solve this problem without considering that requirement let's just solve this problem using two stacks in a naive way so let's say this is stack one and this is stack two we can only really push and pop from a stack so naively let's say we had this same sequence of values let's say first we want to push one next we push two next we push three and let's say we do four as well now we want to pop how do we do it well for us to remove an element here we have to kind of get rid of it and at least with a normal array we do that shift thing that I talked about we shift every element but they tell us with a stack we can only use the stack operations push and pop so can we accomplish the same thing without doing this basically without like indexing the stack cuz that's not usually allowed with a stack yeah we actually can how would we do it well it's probably not going to be by pushing an element you can guess that we probably want to pop until we have the last element remaining but we don't want to get rid of these then we lose what we had well that's kind of what the second stack is for isn't it so as we pop these elements we can push them to the other stack in the same order that we're popping them what happens when we do that let's just try it and then see what happens okay we get four then get three then get two looks like the order of these was actually reversed so when it comes to coding this up instead of hardcoding it such that we wait until the length of S1 becomes uh equal to one so that we have the last element and then we can pop it let's just take every single element here pop it such that it gets pushed to this other stack so now look at what we have done we've reversed the order why does that help us because now when we pop we're actually popping the correct element because remember this is the sequence this was the sequence this is what the real Q would look like 1 2 3 4 we push here to the back of the que we remove from the front of the queue so far so good we now are able to pop this element here but remember we kind of reversed the order of these so let's just take all of these add it back to the first stack in like the same order that we popped them well in the opposite order I guess so that we now get two three four so if we were to pop these this is what we would get and that's fine because now when we want to push to the stack we can push in constant time just to review the solution I have shown you pushing is constant time and popping since we're popping from the other side it's going to take Big O of n every time to take all these elements move them to the other array and then move them back that's going to be the bottleneck popping but they claim that somehow we can get a solution in constant average time so tell me theoretically how would that even be possible well with two stacks we know we really don't have a lot of options we can only push or pop and we already decided stack one is where we're going to push that's constant time somehow if we can make it so that stack two is the one that we're always going to pop from which we kind of already did that pop itself will be constant time but the bottleneck was when we had to move all of these elements there and move them back do you see something that we could do we don't know what the next operation is going to be we don't know whether it's going to be a push or a pop but if it were to be a pop wouldn't we want to leave the elements like this because we did that operation we did that Big O of n operation why do we want to have to do it again cuz looks like the numbers are already here if we want to pop again we could do that actually in constant time if we want to pop again we could do that in constant time okay but what if we wanted to push an element well I guess we could still push an element to the first stack like for example now if I wanted to add five to my Q so I'm going to put the five up here in the original q and then if I wanted to add five I'd probably push it here we've decided that's where the most efficient place to push is now if I want to pop again what am I going to do because originally we took all these elements and moved them there well right now it doesn't look like we need to do that again look at the input sequence we've removed one so far but the next element we'd want to remove is two and we can do that it's right here doesn't matter that we've added five because this second stack the one that we're going to pop from is nonempty so what we can decide is pop from here and pop from here if we want to pop again now well stack two is empty so let's go look at stack one maybe it's empty too and we just can't do another pop but it's not so now is the part where we would take all these elements and then push them here just like before and if it's one element we do that perhaps it would be multiple elements and we do the same thing they'd be added here in the opposite order that's the key cuz when we pop from here and then push here the stack gets inverted that is the key here because remember push here and hop from here we can do that because the order is good for what we want to do and it works now this isn't super complicated is it the hard part about this is the fact that we are trying to find a solution that is amortized or you could think of that as like the average case time complexity if we do several calls to this Q we want that to be constant for both pushes and Pops that is really the hard part about this problem so let me kind of give you the intuition of why that is kind of guaranteed let's go through a few examples here the trivial one is if we push then we pop we're going to end up popping this and moving it here and then popping it from here so pushing is obviously going to be constant and then popping is going to be constant because we're going to move it here and then remove it so if we just did push pop back and forth it would be fine what if we instead had a long sequence of push operations and then we had a pop after that well we kind of showed that earlier we'd have a 1 2 3 here then we'd invert the order 3 2 1 and then we'd start popping if you were to look at the total number of operations that happened here it looks like we have like about two operations or maybe three operations cuz for each element we're pushing it to the first stack we're popping it from the first stack pushing it to the second stack and then popping it from the second stack so I guess actually four operations for every single number but what does four * every single number but what does four * every single number but what does four * Big O of n or just n equal that's still Big O of n right that constant four doesn't do anything to us so it looks like having a long sequence of pushes and then a pop is not bad and I kind of just realized I already showed you if we had a long sequence of pushes and then a long sequence of Pops because again we'd push each element and then pop it and then push it here and then pop it and remember each of these operations is constant time so even though this would be constant time uh this would be constant the pop itself the first one would technically run in bigo of end time because we'd have to move all of these here then after that every pop would be constant time and again I just showed you we're only going to do it four times for every single number so it's not going to be super inefficient now you might be thinking what if we just had a single push and then a bunch of Pops came after that well that's not really possible we can't pop if we haven't pushed anything remember so that's the idea here again average case time complexity of push and pop is going to be constant I want to quickly go over empty how do you think we're going to resolve that because we are working with two stacks we would just check if both of them are empty we return true if that's not the case let's return false what about Peak well remember when we pop we're popping from stack two so when we're peing we should just take the element without necessarily removing it and then we can return that element what if though stack two is actually empty we haven't pushed anything to it yet what if we just have 1 2 3 4 in the first stack well let's have an if statement in our code to check for that if stack two is non-empty check for that if stack two is non-empty check for that if stack two is non-empty return the last element from stack two if stack 2 is empty return the first element from stack one and now that I think of it we're technically not allowed to index a stack so I guess probably the best way to handle this would be kind of the same way we handle the pop so I guess depending on the language you're using we can do that same operation so that's what I'll do I guess so instead of that whole if statement thing let's just handle it this way okay now let's code this up let's declare our two stacks I'll call them the same thing stack one and stack two technically these are arrays or dynamic arrays in Python but we'll just be using them as a stack so let's just keep in mind we can either push to it we can pop from it or we can look at the last element in the stack the top element uh by the way if you're wondering how I figured this out I'll keep it real with you I actually was able to solve this problem because I had solved it before in the past otherwise I don't know if I would be able to but in pushing let's take stack one and append X to it that's the easy part okay popping this is where things get tricky ultimately we want to return from stack two we want to take stack two pop the last element and return it and by the way they guarantee to us that pop is only going to be called if we actually have an element in the stack we don't have to worry about edge cases where the stack is empty or rather the Q is empty sorry about that same thing with Peak we can't return the front of the Q if the Q is empty so we don't even have to worry about that now it's possible like I said that stack two is actually empty so if not stack two then let's take everything from stack one and move it to stack two so while stack one is nonempty take to stack two we want to append the last element from stack one so pop that element that's perfectly valid in a stack so stack one. pop great we have completed pop like I said this is going to be pretty similar to Peak I guess there's going to be a bit of redundant code if you want to move it into a helper function you can I probably won't be doing that the only difference between Peak and pop is that instead of popping the element we just want to return it so think of it like this return self. stack 2 the last element in Python I don't know if top is a method so the way to get around that is just to return the last element which you can just get with the negative-1 index and just get with the negative-1 index and just get with the negative-1 index and we're allowed to do this because technically this is top it is pretty much a real stack operation now it's possible again that stack 2 might be empty if that's the case let's just take everything from stack one and move it to stack two before we execute this so instead of writing it out I'm just going to copy and paste it like that done with this and the only thing left for us is the easy part thankfully so let's Implement empty we just need to check that both of the stacks are empty so return let's say length of Stack one and we're going to need length of stack two and we could check that they're both equal to zero or I guess a slightly clever way to do it would be just to take the maximum of both of these and then check if that's equal to zero CU it's not like the lengths are going to be negative if even the maximum is equal to zero we can assume that the other one is also equal to zero so that's the entire code I will admit this is a bit hard for an easy problem at least to come up with the amortized approach that part is definitely not easy but you can see on the left that this works and it's pretty efficient if you found this helpful please like And subscribe check out n code. for more resources and I'll see you soon
Implement Queue using Stacks
implement-queue-using-stacks
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: * `void push(int x)` Pushes element x to the back of the queue. * `int pop()` Removes the element from the front of the queue and returns it. * `int peek()` Returns the element at the front of the queue. * `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. * Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. **Example 1:** **Input** \[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 1, 1, false\] **Explanation** MyQueue myQueue = new MyQueue(); myQueue.push(1); // queue is: \[1\] myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue) myQueue.peek(); // return 1 myQueue.pop(); // return 1, queue is \[2\] myQueue.empty(); // return false **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. * All the calls to `pop` and `peek` are valid. **Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
null
Stack,Design,Queue
Easy
225
64
let's talk about today's li coding challenge question minimum path saw we have a M by n grid matrix filled with non-negative numbers we want to find a non-negative numbers we want to find a non-negative numbers we want to find a path from top left towards bottom right which minimize the sum of all the numbers although its paths and we can only move towards right or going down at any given point of time so it's a pretty standard better make a programming question so let's just be a little bit more generic here about this problem let's say that we have a function called F IJ which is the minimum path some from location 0 the top left to any given location IJ then since that we can only go in right and we can go in only going we can only go in towards right or going down the way that we reach this location is going to be from the row above it or these the column that towards the left of it so there are only two ways we can get to location I J it's from I minus 1 J or I J minus 1 so if we can just get the minimum path sound for this 2 location then since all the numbers are non-negative the minimum numbers are non-negative the minimum numbers are non-negative the minimum path sum for this location is going to be choosing whichever is smaller fundis 2 and plus the integer at this particular location so that's the recursive relationship we have in this dynamic programming question and of course in the end we want to return f n minus 1 J minus 1 in the end yeah so that's pretty much the formula for DP here I'm a dynamical programming here so we're gonna code up a 2d version and then I minimize I'm trying to try to optimize it a little bit so before we do that let's just run for the sake of demonstration we run a quickie example about how to solve this how to actually calculate the table for F I J so we start with the top left to location because its first location it does not have any other ways any paths before that so the path some for the location 0 is just the number itself and then we look at location 0 1 the only way we can come here is coming from the left so we add one with the sale value of 3 and just keep doing that it's the same for the first two column that we can only go in going down keep going down and just adding the bottles then things become a little bit interesting when we're looking at the second row here second row second column here we choose the smaller value between the cell towards the left and the cell above it which is 2 and add the cell values 5 to it to get the F IJ for that location we just do the similar saying we get 6 here we choose with pick-6 which is a smaller we choose with pick-6 which is a smaller we choose with pick-6 which is a smaller between six and seven and add to tourism so we get 8 for the rare loss location would pick 6 because they're smaller than 8 and add 1 to it and get 7 so that's a so Indiana will return 7 that's a little animation about how to populate this i5j table and I guess one thing important is that you see that we're actually doing this row by row after we're populating this 2 boundary of this boundary here you know so there can potentially be a reduction of space requirement by you know when we are dealing with them when we are dealing with the loss 3 here all the information we need is the cell that's above towards the left or the cell value above it we don't need anything about the red first thorough so we can potentially reduce the space by only keeping track of the current two rows that we're working with so we can reduce the space requirement from the whole matrix 2d grid to towards 1d so that's a kind of possible optimization which will be coded up very easily actually not difficult at all so let's start how the 2d version first thing first they grab the N by n Fabio skier in them for the matrix and we have table and Willow and Collins and we're going to start to populate the top left value to be zero but it'll be the good value and we're gonna have four simple four loops to populate the first row and first column row equal one robust and so this is a the first column here we gonna do plus so that's the first row and first column that we do the first arrow here then we starting working at the second row second column I'm just starting doing this real barrel callin by : doing this real barrel callin by : doing this real barrel callin by : so we're gonna have a nested for-loops so we're gonna have a nested for-loops so we're gonna have a nested for-loops here yeah the time complexity for this is obvious it's a n by n so we since we populating a table of size M by N and for each cell we do a constant time operation so it's a time complexity is n by n for this 2d DP version the code is gonna take M by n in space I kind of actually copied so that's the then we just use this formula here dpi Rantala is equal to the value of that location plus the minimun of whichever direction that we can come in from so that's PI minus 1 C row minus 1 that Colin row and column minus 1 so that's pretty much the 2d version and in the end we just return n minus 1 so it's a it spiritual literally this cup of Lies gets it literally just do played this formulary into action code let me quickly check initialize empty table the left top left is the value itself and we do a first column first row then we start where to start working on the second the interesting part which we can or we need to do a decision which parts we take so looks okay so let's submit this okay so we're gonna try to reduce this a little bit so this is a 2d version MN in time and order MN in space so for the one dimensional one we just gonna store the single line here and so let's actually do a quick demo so remember the matrix let's see up here so we populate the first row 1 4 5 and then when we decide the next row we're gonna take the current value and add one so that's the only location only thing we can do so we've updated this one to be to we I'm gonna write it as separately so just you know that we basically just modify this in place for the for this one for the service location one the DP table the very first locations go is going to be the cell value plus the one that's up but that's you plus the previous cell value itself because that's the only way you can get there and then we look at the second location it's the minimum between two and four and plus the five there so it's a seven and for the cert location it's the minimum between the cell above it which means that we're coming from left in stem row or the value itself which is the previous value that's means that we are coming from the room above coming down so we take the minimum between seven and five which is five and out of one two it so look at six I'll just keep doing this for one more time we will look at the very first location we can only going down so we add four to let's just make a copy first and it's gonna be changed to six and when we look at the second location we check take the minimum between this value and the one that's a prior to it and add the number two so we get a eight year for the last location we can compare eight and six and our one so we get 7 so that's a four for this 1d version we're just gonna keep one dimension so we're gonna have with n numbers in there the river first value is going to be the top left of cell value and we're populate the very first arrow very quickly which is just to copy this I'll go last and C++ PPC to copy this I'll go last and C++ PPC to copy this I'll go last and C++ PPC equal to EP c minus 1 plus grid 0 and C that's how we populate this first row then we just modify the values inside in place plus what are we gonna do is for each of the cell values if it's 0 we add the number to itself otherwise we will do a minimum between the adjacent number and add the cell body to the minimum of the two if we are the first location then we gonna do is directly increment that tithing otherwise it's gonna be the similar to the formula to this formula here which is gonna happen between the DPC and TP 3-1 the DBC here means the DPC and TP 3-1 the DBC here means the DPC and TP 3-1 the DBC here means that we're coming from the row that's directly above it PPC minus one that's we come in from the same row but the cell of the cone and that's what's the lap of it so that's a the code for the one dimensional one so this will reduce the space to just based on the number of rows so this one is one dimension and this is the space so looks okay to me now let's see it's not working ah jeez that's the Sun check I don't want to see this ever message anymore so we have this yeah this is a number of columns the size of the number of columns so yeah only to change the space we populated the first row and then from the second row towards the end we're looking at cell by cell if it's the first cell we can only come in from above so we increment the cell value by the Great Valley otherwise we can have choices either coming from the bar or we coming from left which is the minimum between this two and we add the cell value so yeah but this looks right now okay it's accepted as well okay that's the question for today a minimum path song
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
120
Hello Hi Guys Welcome And Welcome Back To My Channel Suggestion Or After Hours Phone Information On Problem Number Love You Please Like And Subscribe My Channel And Hit Like And Show That You Get Notified When Ever Portion Video 2018 Problem Hi Problem Or Governor Triangle Hey written minimum 5 sum from top to bottom positive villages and number of problem no more family of your own indic IME under control you memo to come here index i and i plus one upon the next that aapke share let's now take this triangle okay so how To work and you will here initially in the morning you find the minimum 500 minimum 5 some from top to bottom tis from this point pro tour and provision to find the minimum 5 some prominent position after which can go to which position and the police to basically from Current December Current Position Vinegar Go to the Next Roles That Position and That Position Similarly Pimples Pet Toe From Here From Just To Be With You Will Go to Three and Four Suicide We Won't Minimum 5 Rates Minimum 5 Someone Will Go to The Moral Values Will Go To Peace in three I love you can go to six and they can go to fight 12345 Records Lesser Sukhram to three from 3251 from 5251 and 110 002 Willow elements from fiber witch can go to one and two have to give into one because selection Value to three 500 and one status will be some will be 11:00 and absolutely status will be some will be 11:00 and absolutely status will be some will be 11:00 and absolutely minimum Watson from top to vote main tujhse mod me to the problem is a unknown s b discuss right now in the explanation how water project you can think like instantly what Approach You Are Able To Think Different Right Thing Song The Instant Approach Which Comes To Mind Is That Okay Will Start From Near Old Age Variable I Will Keep On Adding A Shabd Samriddhi Shakambhari Bill A Look And When I Go To The Next 250 From This To Visit S Manya Small And This Model And For Smaller And Smaller Tubelight In The Song Of 110 From This Thi Milti Which Were Small Not Only Monoxide Small Size Amolak Subah Will Hurt In The Fight That Deviate From Five Vacancy I Dhawan And Eighth Smaller Ones Who Love To Will go to boys will be boys dance on and Sudesh approach to approach which they thank you very serious problem which is a that Patna on all essay writing letters implement same approach and sister attested this and you will be able to understand why this approach is that not Work on a flat from a little distance with already submitted to here reduce it to a minus one 123 this dynasty minus one minus be ok elected chief whom real estate businessman variable blue 201 go from near to minus one will be added in the southern railways Which to go to and three to smaller in the morning 2013 near 58225 one minus plus two one should learn from this you will go to which 201 and 34 - 201 and 34 - 201 and 34 - 151 - in this village - become hair fall on come zero 151 - in this village - become hair fall on come zero 151 - in this village - become hair fall on come zero two the soul into arav roach And Pt 1 Hai But What Mintu Raj Mintu And The Water Into Is A Minute To Find Out The Minimum 5 Samrat Me To Front Dr Ko Minimum 5 Song From Top To Bottom Up Hai Tu According To Allegation Rose Minimum Part Time Comment Bhi Zero But The Risan Respected This is not the minimum balance Want More 75 Astonished Humiliated And You Later Date Phone Par Temple From This - 128 Want To Phone Par Temple From This - 128 Want To Phone Par Temple From This - 128 Want To Listen Up And Bihar Gone To 300 - OnePlus 3 Listen Up And Bihar Gone To 300 - OnePlus 3 Listen Up And Bihar Gone To 300 - OnePlus 3 Will Be Too From This Divyanshu Vishudh Minus One And - That A Minus One And - That A Minus One And - That A That your from where Facebook got yesterday morning Ravi Bisht go to that which one is model - - - - Neeraj got equinox - right in the morning - 10th CBSE Guide 10 - morning - 10th CBSE Guide 10 - morning - 10th CBSE Guide 10 - One hence James Bond - 1800 Meaning of One hence James Bond - 1800 Meaning of One hence James Bond - 1800 Meaning of This is the Minimum 5 Sal this is the minimum parts not the one which is not playing on that your convenience approach which they have discussed right now will not work on I white will not work records pet friend this case against was that surya minus one to three live virus One End - Sai Pa Mein Supervisor To Approach S Not Working On Bigg Boss 8 Level Right At This Level Yo Honey Singh Was Not Only To Things One Month Phone Par Temple From - Vv 34 Minimum 2nd Phone Par Temple From - Vv 34 Minimum 2nd Phone Par Temple From - Vv 34 Minimum 2nd Don't See The Possibility For This Point Rate Veer Just Delhi Wholesale Price's Other Values ​​Which Caused By Decide Vinod Values ​​Which Caused By Decide Vinod Values ​​Which Caused By Decide Vinod Explorer Is Enemy To State Five-Year Missing Out The Possibilities Idea Five-Year Missing Out The Possibilities Idea Five-Year Missing Out The Possibilities Idea Rate For When Will Chuda Want To This Point Okay To Improve This Region Is Approaching Not Work In Record Label Also Here Go to 9 Life Itself from This 2012 - One Who Do Not Itself from This 2012 - One Who Do Not Itself from This 2012 - One Who Do Not Consider This Will Not Consider To Be Seen or Consider This But Not Considering Slide Dubai Only to Mandu A Ki Some Solution for This Election Stunt Will Explore the Possibilities Consider There for All the Notes Jindal level all the notes idea inter level right switch off explorer form full and see how we can do it a to agar nai lakshmi and after taxes 308 miles - one a minus one two three in one minus one - t&amp;c a minus one two three in one minus one - t&amp;c a minus one two three in one minus one - t&amp;c a look To See What Will Be Doing Giving You Samay Crash Tests For The Value Of You Soar The Values ​​Will Understand Why I Will Take You Soar The Values ​​Will Understand Why I Will Take You Soar The Values ​​Will Understand Why I Will Take Vector Ki And Exercise Yadav Actor Is Sai The Last Jis 5490 Ok And Drug Dealer Vijay Soni Mahiwal - - See What Will give us will be easy going from Mahiwal - - See What Will give us will be easy going from Mahiwal - - See What Will give us will be easy going from bottom to top oh that from bottom how to talk with God a look at this level will consider all the notes on ok so for this last level refer 10 level minimum 5 Samriddhi Jewelery Neera Left 119 level In the morning it should be kept to minimum in the evening - - - - Number level In the morning it should be kept to minimum in the evening - - - - Number level In the morning it should be kept to minimum in the evening - - - - Number 501 likes I will start from 9th second last rule will go from bottom to top o that his so absolutely go from bottom to top 100 salute o hi honge so let's find me volume And Clear Swa0 Two Have Been How To Wear Currency And Spine And Resources 012 210 Currency Rate 1051 Index Rot And Will Be Late Services One Vikas And Eggs Flight To Real Currency And One Co Ma0 Fee Position 2 And Will Explore All Possibilities To Show What benefit to get minimum 5 something this to what will be the two plus waterways minimum one and - ॐ which is minimum of minimum one and - ॐ which is minimum of minimum one and - ॐ which is minimum of Ajay Devgan and - स्वीतू plus ko Ajay Devgan and - स्वीतू plus ko Ajay Devgan and - स्वीतू plus ko minimum of the one in this world a I 10 - 101 bhi baat okay to hi meaning I 10 - 101 bhi baat okay to hi meaning I 10 - 101 bhi baat okay to hi meaning a A population lives in opposition 0.01 will be to ring these values ​​which will 0.01 will be to ring these values ​​which will 0.01 will be to ring these values ​​which will vote for this with this time ok good bye now will go to the other side pure thing first to rate this one intact is hair pack service revolver also three plus minimum of It's willow to notes you can see elements of - 151 - what is you can see elements of - 151 - what is you can see elements of - 151 - what is human 20 - human 20 - human 20 - 2013 - with you 2013 - with you 2013 - with you is at index favorite index 150 to 200 stayed in a flat me china stop color question and you if your nails this patients time then will Go to the others opposition to clear yaar - 121 the Go to the others opposition to clear yaar - 121 the Go to the others opposition to clear yaar - 121 the businesses hogi main to yaar went to avoid your intellects so what will do - 121 aplus the water at once minimum balance here what is the minimum balance here to all the best video websites the previous violence The pundits were a me in tell here what is the minimum on still here what is the meaning of birth leave for what is the minimum on this to here ready autism in this to here on a that sudhir what will you find volume minimum of ka juice one Ka's gold will be minus one plus minimum reddy who to - mile to here minus one with her reddy who to - mile to here minus one with her reddy who to - mile to here minus one with her and they will to resist and products of years to here what will get will stop - 6a - 6a - 6a main tujhe - - the minimum 5 sum from this main tujhe - - the minimum 5 sum from this main tujhe - - the minimum 5 sum from this top road to The water is just a virus hotspot of a in a TAFE that the said try to relative lineage can increase Aircraft Problems and Dynamic Programming Why Not Legal Explained Above Is Dynamic Programming Course See It's Pretty Much Clearer And What We Do That Here Fish Value Right Dynamic Programming S2 Condition Overlapping Sub Problem That And Optimal Substructure Right Optimal Substructure That And Overlapping Sub Problem Poti Is Condition Dabang Full Year How See Optimal Subtraction Means Pieces Mi Fit Minimum 5 Committee Member Node The Right It Depends On The Minimum 5 Something This and minimum 5 balanced here example history to front minimum 5 us 10 different and minimum 5 augmented and minimum basen co because of mango toe value winter minimum remained so this minimum text message the bottom toe values switch of commerce subject a night one You will see examples for this sub problem 1628 you will request free for this you will see raw overlapping sub problems for the day that understandable properties of satisfying problem diet high speed we can think of using dynamic program ok to see result right back to Us to the results here jam on minimum 5 flat 10 minutes to minimum 5 committee 10 minutes to those view take up this matter to oo to improve wikinews ok take ko don't agree care oil is this comment iron once so code ok c u a Possible Applicants Maintenance Factor Android Triangle Don't Back What Means Do It Well and Feel The Matter With Last Values ​​Which Will Make With The Milne Feel The Matter With Last Values ​​Which Will Make With The Milne Feel The Matter With Last Values ​​Which Will Make With The Milne Inspector Will Be Something Like 418 That You Like This You Student Will Start From Second Last Row Will Go To Which Element in metros and will find the volume minimum 5 something is that a time and already 210 will find the minimum bathroom suzy inch plus one key and current value will hide in the waterboy tamil mobile and wish to renewal pimples index deficits to baby toys Toys For This Cream With Straw And Share A That Rathore Be Written In The Volume Two Chapter 07 2010 Year - Verses Know 07 2010 Year - Verses Know 07 2010 Year - Verses Know And Strengthen The Solution Pran Vanshi Tunes Payment Clear A Time Complexity And See What Are You Doing To Here We Are That Attack On Single role and where gone into this element in life you can search and square that and time complexity is who is the speech for collective is virat english actor switch off in key side open to problem and approach but he has done his duty in mixer for individual please Like share subscribe my channel mix thank you
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
1,685
hello and welcome to another video in this video we're going to be working on some of absolute differences in a sorted array and in the problem you're given an inary num sort in ncreasing order and what you want to do is you want to build an integer ARR result where the result is the sum of taking every single number in the array and subtracting the number at the current index and getting the absolute value all those so for example for this first one result zero is so you do 2 - 2 3 - 2 5 - two absolute value do 2 - 2 3 - 2 5 - two absolute value do 2 - 2 3 - 2 5 - two absolute value all of them add them all together you get four then for the second index you do 2 - 3 - 3 5 - 3 or it doesn't do 2 - 3 - 3 5 - 3 or it doesn't do 2 - 3 - 3 5 - 3 or it doesn't matter because absolute value that's pretty much what you need to do so you need to take every single number subtract the current number at the current index and add all those together so the problem here is it's kind of hard to see a pattern because like it's increasing then decreasing then increasing and also the constraints are kind of big so immediately when the strengths are kind of big uh 10 the fifth pretty common you want to look for like a sliding window two-pointer as I like a sliding window two-pointer as I like a sliding window two-pointer as I said before so it's kind of actually not super easy to figure out what to do so we're actually going to break this problem down into two sub problems and then it's going to make it a lot easier so let's take the second example and what we're going to do is we are going to actually do this but with a slight of modification so instead of this we will have zero as the first number and that's going to make a lot clearer like what the solution is so we're going to take all these numbers and what we're going to ask for is give me the sum of every number greater or equal to Cur minus curve right so for example what would happen is for zero we do like 1 - 0 plus happen is for zero we do like 1 - 0 plus happen is for zero we do like 1 - 0 plus 4 - 0 plus 6 - 0 Plus 8 - 0 plus 10 - 0 4 - 0 plus 6 - 0 Plus 8 - 0 plus 10 - 0 4 - 0 plus 6 - 0 Plus 8 - 0 plus 10 - 0 for one it would be like 4 - 1 + 6 - 1 + for one it would be like 4 - 1 + 6 - 1 + for one it would be like 4 - 1 + 6 - 1 + 8 - 1 + 10 - 1 right kind of similar to 8 - 1 + 10 - 1 right kind of similar to 8 - 1 + 10 - 1 right kind of similar to this for problem except we're only focusing on numbers that are bigger than that number and you're going to see why the zero helps a lot so let's actually uh copy this because we're going to use this so originally for zero it's pretty straightforward right like for zero U let's actually use this for zero it's just going to be the sum of the whole thing right cuz every number minus zero would just be every number so what's the sum here it's 5 + 6 number so what's the sum here it's 5 + 6 number so what's the sum here it's 5 + 6 11 + 18 so 29 so for Z tribute 11 + 18 so 29 so for Z tribute 11 + 18 so 29 so for Z tribute 29 now basically like I said for zero it's basically just the sum of this whole thing right now for one you can say okay well let's just do every single number bigger than one subtract one and add those but the problem is we'll have an N squ solution so how do we go from 0 to one right we got every number that's bigger than 0 minus 0 but how do we do this preferably no of one well zero was every single number so we have six numbers we can write this down actually so zero we have six numbers write down at the top have a sum of 29 so to go from one number to the next number what you need to do is you need to figure out like what's the range of numbers you're decreasing because it's going to be decreased right every time you sub you subtract a bigger number you're going to get a smaller result so all these sums are going to decrease so it's going to be if zero let's actually make some more variables as well so let's call zero previous and let's have a curve variable which is the number we're on so let's say that's one and then we also have a length of the like actual range we are decreasing so in the beginning it's all the numbers so let's call that six so to make this like transition from one number to the other it's actually going to be and you're going to see how this works it's going to be the current number minus the previous number times the range we're decreasing that is going to be what we're going to be subtracting from our old number right so we could say I guess this is like old sum or something let's say old sum minus this whole thing and let's kind of see why that is right so what we're doing is when we're going from 0 to one we are basically saying let's take every number and subtract one every single number obviously not the zero right so we are not doing the zero but it's going to be all of these numbers so how many numbers are we subtracting one from We're subtracting one from five numbers so the length is actually going to be five because we're subtracting one from five numbers and you can easily get the length by just figuring out like what index you're on and it's going to be whatever index you're on to the end of the array so in this case it's five so we're subtracting one from five numbers because right because it's it goes from 0 to one that means we're subtracting five total so if we do this like old sum thing so except this is not going to be six now this is going to be let's actually rename this to length uh and then let's maybe do this or something so we have enough space okay there we go so let's uh plug all the stuff in now so our old sum which is our previous sum so that's 29 minus the difference so here we went from 0 to 1 so it's going to be the difference is going to be one times the length of the range that we are going to be decreasing and remember we're going to be decreasing the range of every number from where we're at to the end so we're at one so we're going to be decreasing all this so this will be five so this is 29 - 5 we get five so this is 29 - 5 we get five so this is 29 - 5 we get 24 and let's double check if we did this manually it would be 1 - 1+ 4 - 1 and so on right so it be 1 - 1+ 4 - 1 and so on right so it be 1 - 1+ 4 - 1 and so on right so it be 1 + 3 which is 3 + 5 which is 8 + 7 be 1 + 3 which is 3 + 5 which is 8 + 7 be 1 + 3 which is 3 + 5 which is 8 + 7 which is 15 + 9 which is 15 + 9 which is 15 + 9 which is 24 that's correct so basically we just have to figure out like what's the numbers we're decreasing like how many numbers are we decreasing and by how much are we decreasing each of them and then we can do this in o one so now the reason I drew this is because we're going to actually change these to what they are now right our sum originally was all these combined now we subtracted one from all of these so what's going to happen here is all of these numbers will now be decreased by one right so this is going to be let's change all these so this is going to be uh three five it's going to be easier to visualize that way seven n right this is our new sum that we are getting here okay now for the next number four we're going to do this formula again so how many numbers are we decreasing we are decreasing four numbers right so we let's change all these values so previous is now one Cur is four length is four plug all that into our equation what's our old sum it is 24 now uh curve minus previous is 4 - 1 now uh curve minus previous is 4 - 1 now uh curve minus previous is 4 - 1 which is three and then how many numbers are we decreasing we're decreasing four numbers here so this is 24 minus 12 so we get 12 and that is correct because um essentially what we're doing is we're saying okay for all these numbers let's decrease them all by not by four right because we already decreased them by one before we're going to decrease them by the difference between one and four we already decreased them by one so we need to decrease them by three more so now we're going to change all these two so this should be uh zero then this should be two and this should be 79 so it's going to be four and six I did that correctly yeah so we have 12 exactly okay now we go to the next number so our previous is now four our current is six and the range we're going to be decreasing is just these three numbers that are left over right it's whatever we have left so this length is going to be three so going back to our formula old sum is 12 what's the difference between the current number and the old number 4 - 6 current number and the old number 4 - 6 current number and the old number 4 - 6 Force two and uh how many numbers are we decreasing we're decreasing three so if we're decreasing three let's do this so we have six total which is correct again so that is correct and now we need to go to the next one so basically let's actually decrease this as well so essentially we're decreasing all these by two more right we already decreased them by four so we need to decrease them all by two more so it's going to be zero two and four okay so we have a sum of six left now let's go to the next number over here so we are at eight same kind of thing so previous will be six per will be eight length how many numbers do we have left we have two numbers left so let's plug this into this equation so we have our previous sum is six and our difference is two again and we have two numbers so this is going to be two so this will just be two and basically same thing we are decreasing all these by two because we already decreased them all by six already so now so basically what we're doing is we're just saying like Okay how much they we decreased by already and then how much more do we need to decrease it by and we can do this in0 of one so hopefully you can see the pattern by now so this is going to be0 and two and then finally for our last number it's just going to be 10- 10 which will it's just going to be 10- 10 which will it's just going to be 10- 10 which will be zero and so that is to get the right side so now for the original problem this is basically it this will give you the right side but now you also want to get the left side right so to get the left side you need to and you could see how this is pretty much this is just the right side but now we are asked to get the left side so we got every single number here we got the difference of current number and every number bigger and now basically we need to do the exact same thing with every number smaller and then we just add it on both sides right for example when we are on number like six we will get this right side doing this part right so we'll do like 8 - 8 - this part right so we'll do like 8 - 8 - this part right so we'll do like 8 - 8 - 6 10 - 6 whatever but we also need to do 6 10 - 6 whatever but we also need to do 6 10 - 6 whatever but we also need to do this left side because six will be bigger than some of these right so this will be 6 - 4 6 - 1 and this will be 6 - 4 6 - 1 and this will be 6 - 4 6 - 1 and this will be different so essentially what you need to do is you need to do a left and the right side and then you need to bring them together so let's actually do the right side but let's um or let's do the left side but we're going to speed it up a bit so instead of like writing every single step we're just going to speed up their currence relation and it's going to be very similar so let's do this uh the same thing we're going to start with this initial array and let's do the left side so what's going to happen here is this is going to be like 0 1 4 6 8 10 now initially the left now instead of actually drawing out these numbers like I said we're going to speed it up a bit um we're just going to keep a cumulative total and we're going to figure out what it's what to subtract so initially our cumulative total will just be zero right because for our first number there are no numbers that it's bigger than right so for like this number there are no numbers that zero is bigger than so before every number was bigger than zero that's why we had this original sum be the sum of the whole thing but now our cumulative total will start off being zero so our sum will be zero so let's start filling these in and then we'll figure out like a Regence relation I'm not going to show all of these numbers just because this is going to be a little bit too long um so let's speed up a bit so for zero obviously this the first one will be zero because there's nothing zero is bigger than now for one how many numbers is one bigger than so one is bigger than zero right so basically what you need to do is you need to figure out what's the range you're increasing and by how much so the range you're increasing is going to be every number before the one which is just one number here and how much are you increasing you're increasing by one so we're taking our old sum and the range we're increasing is just one number so it's just going to be some 1 + one here 0 + just going to be some 1 + one here 0 + just going to be some 1 + one here 0 + one and that's correct right because one is bigger than zero and the cumulative difference here is one so here we would have one now for four is three bigger than one so it's going to be three times the range we're increasing this whole range there's two numbers at four is bigger than so it's going to be 3 * 2 which is going to be 6 going to be 3 * 2 which is going to be 6 going to be 3 * 2 which is going to be 6 + 1 right because one is our old number + 1 right because one is our old number + 1 right because one is our old number so we have seven and that's also correct right 4 - 1 is 3 4 - 0 is four so the right 4 - 1 is 3 4 - 0 is four so the right 4 - 1 is 3 4 - 0 is four so the total is seven there so for six same kind of thing what's the range we increasing this whole range so three numbers how much are we increasing by we're increasing it by two so by two 6 plus the old number plus 7 so it's going to be 13 and I'm going to quickly show that this is squ one more time and then we'll just uh not do that for the rest so let's take a look so here we have a difference of two here we have a difference of five so that's seven + 6 difference of five so that's seven + 6 difference of five so that's seven + 6 is 13 right so that's correct so now our total sum is 13 48 same thing difference is two compared to the previous number and the range is four numbers so we have 8 plus the old number which is 13 so we have 21 here and finally for this zero or for this 10 we have uh same thing difference of two and the range is five numbers so we're going to increase by 10 here so it's going to be 21 + 10 by 10 here so it's going to be 21 + 10 by 10 here so it's going to be 21 + 10 right five numbers difference of two so 31 okay now that we have all this let's actually get rid of all this so essentially for this exact example now that we have a left and a right remember the left is the numbers that this number let's write this down so the left is the sum of all the differences of Cur and numbers that it's greater than and the right is the sum of all the differences of Cur and all the numbers that it's less than so if we add all these together then it will be the sum of all the differences of every single number including with C right it'll be for the current number it'll be the sum of all differences of c and all the numbers that it's greater than and the numbers that it's less than and that's what we want right like if we scroll back up to the actual problem for example for two we want to get all the numbers that it's greater than and all the numbers that it's less than and now we figured out our currence relation to actually calculate the left and right on the fly so now we can have an ENT solution with zero space because we can just take an old sum figure out like what kind of range we're iterating through and how much the difference is and that's basically all we need so it is a little confusing um but yeah this is going to be the solution and I will code it up as well and we'll kind of explain it as we go so let's do that so remember our right will start out being as a sum of every single number because originally every number is bigger than our current number and to make this easy also for our left it'll be zero we'll just say there is no number smaller now for the result we're just going to have a empty array and what we're going to do to make it easier is we had a previous in Ur So what I'll actually do is I'll make previous zero because that way it's going to be easy to figure out like how much did our number increase by so it's going to make it easier in the code so we'll say previous is zero our right is just the sum of all of our numbers and our left is zero which makes sense so now we have we'll have n equals length of nums and essentially we need to go through all of our numbers and calculator left calculator Right add them together and put that in the result so we'll say for IV in enumerate nums right so this is the part where we need to calculate so we need to calculate the right and the left so we'll say right was originally the sum but how much are we subtracting right we're always going to be subtracting from the right and we're always going to be adding to the left so for the right we are going to be subtracting the current value minus previous and we need to figure out the range so the range is remember going to be the current index to the very end of the array which is going to be uh n minus I so for example if this was like an array of length three and we were on index zero then we would have three elements right so n is going to be the length and this going to be that so we're subtracting from the right now we need to do a very similar thing add to the left and so what are we adding to the left once again it's going to be the how many numbers are there so the number the range for the left is going to be all of the numbers up to the current number which is just I so it's up to not including actually because um if you think about it the number can't be greater than itself so if you had numbers like 1 2 3 4 five when you're figuring out like how much to add for numbers that are greater than one isn't greater than one so you really need to add to every number to the left of one right so what's that how many numbers are there well that's just going to be I so for like I equals z there will be no numbers for I equals 1 there will be one number and so on right I did include the zero in our original thing but we're not going to have the zero as the part of our array actually so that's why it's not so that's why we're not including the zero index we're just having the zero value okay so essentially the range here is I and how much are we adding now well it's just going to be the difference again so the current value minus the previous so we subtract from Right add to left now finally we append left plus right and we set our previous equal to the old value now you don't need a previous um I just made a previous because like for uh because I wanted it to be zero to make it easier but you could say like if the index is zero then the previous value is uh zero otherwise let's just take the value at IUS one like that's totally fine so you don't need a previous but it doesn't really matter okay and then finally we return the result so we essentially figure we figured out our culation in place by figuring out like when we change our number what do we have to do and you could see this is a very efficient solution so this one is kind of tricky to figure out I think it's super it's not super straightforward but once you figure out uh like one side like literally just simplify your problem into like I said this thing that I said originally just how do I get the difference between my number and every number that's bigger figure that out then how do I get the left side figure that out and then figure out um yeah actually I think if you can get the right side in o one right so literally just solve the problem of uh get the difference of every number bigger than that number in and that number and get the recurrence relation in of one then you basically solve it right so you get that recurrence relation of one you get the left recurrence relation of one and it's just both of those combined I think this is kind of similar to I think there's some other problems like this um there's like a multiply every number except for itself or something like that so and the big thing to look for here that actually made me realize that this is the case is as your number gets bigger the numbers the sum to the right decreases and sum to the left increases and that's really what you want your you want to pick your El Curren relation to use things that increase or decrease you don't want it to be fluctuating because if it's fluctuating it's kind of hard to say like what it's going to be but if it's increasing or decreasing by something you can predict that's going to be a lot easier to actually have this uh CH small change right to make it an o one otherwise you'd have to do something like DP or something and like I said it's going to be hard to do DP because this is too big so let's do the time and space real quick should be pretty straightforward um it's just going to be ENT time and ENT space uh sorry o one space right we didn't that's the other thing try to find an no one space solution if you can and then if you're really having trouble like if you think oh I have to have this data structure then add that in so I think you can actually do this like with prefix sums or something but I just thought of this originally without even using a prefix sums it was reasonably intuitive so yeah I think that's going to be everything for this one so hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Sum of Absolute Differences in a Sorted Array
stone-game-v
You are given an integer array `nums` sorted in **non-decreasing** order. Build and return _an integer array_ `result` _with the same length as_ `nums` _such that_ `result[i]` _is equal to the **summation of absolute differences** between_ `nums[i]` _and all the other elements in the array._ In other words, `result[i]` is equal to `sum(|nums[i]-nums[j]|)` where `0 <= j < nums.length` and `j != i` (**0-indexed**). **Example 1:** **Input:** nums = \[2,3,5\] **Output:** \[4,3,5\] **Explanation:** Assuming the arrays are 0-indexed, then result\[0\] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4, result\[1\] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3, result\[2\] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5. **Example 2:** **Input:** nums = \[1,4,6,8,10\] **Output:** \[24,15,13,15,21\] **Constraints:** * `2 <= nums.length <= 105` * `1 <= nums[i] <= nums[i + 1] <= 104`
We need to try all possible divisions for the current row to get the max score. As calculating all possible divisions will lead us to calculate some sub-problems more than once, we need to think of dynamic programming.
Array,Math,Dynamic Programming,Game Theory
Hard
909,1240,1522,1617,1788,1808,2002,2156
1,093
I always Calvin here so today we will discuss about a problem called statistic from a large sample from weekly contest 142 so we are given array of size 2200 and 456 the represent frequency of number from 0 to 255 so first index representing number of 0 second X representing number of 1 second index presenting number of 2 and so on so we try to find the minimum element in our array maximum element in our array mean median and mode so for minimum if you see here our minimum element is 1 because 1 is the first element that exists in our array we would need to ignore all the 0 because 0 basically the data is not there so this is the first one with me and that is the minimum for is the last step that we meet that means the element is the maximum and the next thing is for reference so we just need to sub to get all of this sum and multiply which is on value so total data here we have 8 and all the value here is 1 times 1 2 times 3 and three times four and then we can define the sum with the total number of data and then we can get mean there and let's give the median first and the mode here is the most frequent element that appear in our town so from the whole array we need to find the highest frequency there right and for median so if our data is even let's say we have data fake so 8 divided by 2 is 4 so we need 8 a number 4 and number 5 being added and then divided by 2 so here our first photo device here and this is our data from 5 to pay crank so data number 4 is 2 and data number 5 is 3 so 2 plus 3 divided by 2 is 2 point 5 but let's say if our number of alignment inside in total is an odd number let's say 7 then we only need to divide 7 by 2 and then plus 1 so 7 divided by 2 is 3 and we plus 1/4 so we only need the fourth data plus 1/4 so we only need the fourth data plus 1/4 so we only need the fourth data itself so only one element and they actually put explanation here for that one so yeah as my explanation there so they expect our return is a array of five for minimum maximum mean median and mode so the first value we've met that is not zero it's our minimum value and the last video we met that is not zero is our max value and here the largest frequency we met is the our mod value there so we keep updating our max current max frequency that we meet if there are such that there is such element that is larger than our current maximum value we keep updating our current maximum value and then update our mode variable itself and Councilman Sam it's the one I explained about afraid so this is the not total number of data and some is the current number D times the frequency itself and then we can find our average from the sum divided by the total number of data and the rest is median so I divide it by two method so first method here is if we have even number of video we need to find our first value here so come some / - like a divided by here so come some / - like a divided by here so come some / - like a divided by two is four and then the data a number five so here I try to find data number four and data number five and then we add it up and divide it by two but if our number of element is odd it means we only look for date on number like 75 by 2 so if we have 70 35 by 2 is 3 plus 1 is 4 so we look for the data number 4 and once we find such value then basically that is the answer for up to 3 and we return the whole output there as us by the question so yeah that's all about this question and see you on the next lip code contests you
Statistics from a Large Sample
recover-a-tree-from-preorder-traversal
You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the **number of times** that `k` appears in the sample. Calculate the following statistics: * `minimum`: The minimum element in the sample. * `maximum`: The maximum element in the sample. * `mean`: The average of the sample, calculated as the total sum of all elements divided by the total number of elements. * `median`: * If the sample has an odd number of elements, then the `median` is the middle element once the sample is sorted. * If the sample has an even number of elements, then the `median` is the average of the two middle elements once the sample is sorted. * `mode`: The number that appears the most in the sample. It is guaranteed to be **unique**. Return _the statistics of the sample as an array of floating-point numbers_ `[minimum, maximum, mean, median, mode]`_. Answers within_ `10-5` _of the actual answer will be accepted._ **Example 1:** **Input:** count = \[0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\] **Output:** \[1.00000,3.00000,2.37500,2.50000,3.00000\] **Explanation:** The sample represented by count is \[1,2,2,2,3,3,3,3\]. The minimum and maximum are 1 and 3 respectively. The mean is (1+2+2+2+3+3+3+3) / 8 = 19 / 8 = 2.375. Since the size of the sample is even, the median is the average of the two middle elements 2 and 3, which is 2.5. The mode is 3 as it appears the most in the sample. **Example 2:** **Input:** count = \[0,4,3,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\] **Output:** \[1.00000,4.00000,2.18182,2.00000,1.00000\] **Explanation:** The sample represented by count is \[1,1,1,1,2,2,2,3,3,4,4\]. The minimum and maximum are 1 and 4 respectively. The mean is (1+1+1+1+2+2+2+3+3+4+4) / 11 = 24 / 11 = 2.18181818... (for display purposes, the output shows the rounded number 2.18182). Since the size of the sample is odd, the median is the middle element 2. The mode is 1 as it appears the most in the sample. **Constraints:** * `count.length == 256` * `0 <= count[i] <= 109` * `1 <= sum(count) <= 109` * The mode of the sample that `count` represents is **unique**.
Do an iterative depth first search, parsing dashes from the string to inform you how to link the nodes together.
String,Tree,Depth-First Search,Binary Tree
Hard
null
670
hello and welcome back to the cracking Fang YouTube channel today we are solving one of my least favorite questions this problem is extremely annoying to code up and even though it's not that hard to solve conceptually it's just a horrible problem that requires way too much uh work to do okay it is 670 maximum swap you are given an integer num you can swap two digits at most to get the maximum value number and return the maximum valued number you can get so let's look at an example 27 36 so what is the maximum swap here well we can see that actually if you swap the seven and the two you will get the number 7 2 3 6 and there's actually no number we can make that's uh larger than this because 7 is the largest number here so putting it in the front would give us something in the 7,000 and give us something in the 7,000 and give us something in the 7,000 and there's no other possible combination we could do here uh to give us that and then here we have 9973 there's nothing we want to swap because n is the largest digit we have so we wouldn't want that to get rid of uh to get rid of it in the first position same with the second position nine is the greatest digit so there's no reason to get rid of that again seven is the next largest digit and then three is the next largest digit so there's nothing we can do here we just leave it as it is okay this problem if you're just looking at the actual input it's really easy for your brain to just figure out what the biggest swap is because you can kind of just do it in your head you just take whatever the biggest number is swap it whatever with whatever the smallest number to the left of it is and you're done unfortunately uh while that's the general intuition we want is like find uh leftmost uh smallest oops smallest uh num and then we want to swap it with the rightmost uh with the number to the right of it that's actually the biggest so rightmost uh largest wow my handwriting sucks largest number uh actually executing this is a massive pain in the ass because you just have to do so many things in this problem but uh instead of actually going through kind of the intuition here because I mean generally this is what you want to do you just want to find the leftmost smallest number and then whatever the largest number to the right of it is uh you just want to swap it with that so essentially that's what we want to do it's just actually how you do this and keeping track of those positions that's the annoying part there's not really too much you need to know for the intuition you just know need to know how to actually execute and write the code so instead of kind of going over uh iteration by iteration let's just go to the code editor and actually write this up because it will be a lot clearer and there's a lot of extra steps that we need to do unfortunately to get the solution here anyway that's enough rambling I'll see you in the code editor momentarily okay we went over the basic intuition for this problem now let's actually code it up and you'll see just what I mean when I say this problem is a pain in the ass the first thing to realize is that if our number is actually less than 11 uh then it's either a digit the number 10 or 11 in all those cases that's actually the largest number that we can get and we actually don't need to swap anything there so we're just going to do a quick little thing that says if num is less than or equal to 11 then we can actually return the num this part I guess it's not really necessary cuz the logic will take care of anyway but whatever the next thing we want to do is we realize that our number is an integer and we obviously can't swap things by index in an integer so we need to take our number and actually transform it into a list where each element is actually the um you know the digit so we have an index that we can swap with so what we need to do is we need to basically just put this into an array and what we're going to do is we're going to do num as array is going to equal to collections. deck uh and an empty uh q and the reason that we're going to use a q is you'll see in a second so we're going to say while num we're going to say num as array. aend left uh num modulo 10 so we basically need to extract all of the digits from num now doing num modulo 10 will actually give us the rightmost digit but if it's a list and we append then when we get our final list it will actually be in the reverse order because we get the rightmost element first and we keep appending so that's why we use a deck because we can actually append to the left in constant time and we don't have to actually waste uh one pass through our number to actually reverse it because it will be in the wrong order if we just use an array as you can see this problem is annoying so after we have appended the rightmost digit then we need to just um decrease it by a factor of 10 each time until num basically is zero and this while loop ends so for example if we had 1 2 3 4 if we were using an array we would get the four first append it the three first then append it two and then one obviously that's the wrong order so we need to reverse it whereas if we use a deck we can just put four and then we can append to the left so three here uh and then we can append the two and then we can append the one so it saves us actually having to reverse it so that's just one pass through that we save okay we now have our number as an array now we can actually work with something so remember that we want to keep track of the maximum number that we've seen and where we see it because we'll have to swap that with basically the smallest number to the left of it so what we're going to do is we're going to say the maximum scene is going to be minus one we haven't seen anything yet and we're going to say the maximum seen at is going to equal to well basically the length of the array because we haven't processed anything yet so we are going to actually go from right to left because we want to keep track for each element what is the largest element to the right of it and once we have that information what we can do is then go from left to right and actually swap with whatever the smallest element is again extremely annoying so what do we want to basically go from right to left over ourr so we're going to say while I is greater than um oh sorry yeah I forgot to set I so I is equal to the last element in the array so num as array minus one then we want to go backwards so while I is actually greater than zero we're going to say that the current number is going to equal to num as array of I now what we want to do is we want to override our num as array and we want to store some extra information at each IND index so we're going to say num as array of I we're going to store a tuple and it's going to contain a few bits of information we want to still keep whatever the current number is and we want to keep whatever the maximum to the uh right of it is and whatever the index that was seen that way when we go back from left to right we can actually do the swaps for each element so we're going to say whatever the maximum scene is and the max scene at now what we want to do is we actually want to update our maximum scene in case that our current number is actually the um maximum so we're going to say if the current num is actually greater than the maximum scene then what we want to do is maximum scene is now the current number uh and the maximum was seen at our current index okay the last thing we need to do is obviously decrement our um while loop here to make sure that we don't get caught in an infinite recursion and that will basically parse through and for each element set the current number whatever the max was seen so far coming from the right and whatever the index is now what we can do is we can actually go from the left and basically do the swap so we're going to say that I is now zero and we're going to say while I is less than the length of the array oops length of num as array now we're going to go from left to right and we're going to say that the current number the max to the right of our current number and the maximum uh was whatever it was seen at is nums sorry num as array of I so those are the new elements we have at each index here now what we want to do is we want to actually decide whether or not we want to make the swap so we're going to say if the max to the right of our current number is actually greater than our current number then this is the swap we want to make right and the reason we're doing this is because we're starting at index zero so basically we want to take the very first element um that's smaller that has a smaller number later on um sorry we take the smallest element that we see remember so if the thing was like 73 uh 2 3 74 then the smallest element to the right of two is obviously going to be the s so we take whatever H okay as you can see this problem is annoying we have 2374 the largest element to the right of our two is going to be the seven so we want to just swap it immediately uh when we do it and we'll actually do 7 3 2 4 so as soon as we get an element that's smaller than whatever the maximum scene is then we just make the swap so that's the reason that we go from the left because we want to get that smallest element on the left side and swap it with whatever the maximum element is in our um array so if we hit this condition that the maximum to the right of our element is actually greater than the current number then we make the swap so we're going to say nums uh sorry num as array of I and we want to swap it with num as array of whatever the max was seen at Max uh seen at and we want to swap these two so we're going to say um num as array of Max seen at I want to swap with num as array of I so we basically do the swap and then at this point we're done because we can only swap one time so we simply break out of our Loop and we're done otherwise um if this condition doesn't hit then we need to keep going through our array to basically just um parse further so we can just I plus equals to one here now our while loop uh will either break because we broke manually or we will hit the end of the um array which means that we are basically done unfortunately and this is where this problem is annoying we need to return an integer so we now need to take our list which contains the elements and turn it back into an integer undoing what we did here taking in an integer and making it a list so now we have to go through our array one more time so we're going to say for the current number we actually don't care about the other things because they're not going to be useful for us anymore in Num as array we now need to reconstruct our integer here so we're going to say num equals to num * 10 plus whatever the num equals to num * 10 plus whatever the num equals to num * 10 plus whatever the current number is to basically reconstruct um the value there okay now we have reconstructed our value we can simply just return uh num right oh sorry we actually need to Define num so num equals to zero so num is our result in this case okay let me make sure I haven't make any syntax mistakes because this problem is beyond annoying and accept it okay cool I was expecting to get some recursion issue all right submit it and we can see that it's accepted okay thank God we are done with that what is the time and space complexity here so as you can see all we do is go back and forth through our array some number of times so the time complexity here is just going to be Big O of n uh what is n equals the number of digits inside of num right uh because that is how long this num as array will be right because however many digits are in here that's how many times uh you know that's going to be the time complexity we're really just looping over an array from back to front uh a few times so it's really just a string of Big O of n operations but ASM totically we know that it's just big O of n um for the space complexity whoops for the space complexity again we are just storing an array uh which basically stores each digit so this is going to again depend on how many digits are in Num so that is really it we have you know multiple Big O of n uh storages here because we need to basically just have the array and then we override it with these things um but again it's just big O of n so that is your solution uh in this time it's Big O of n in the space it's Big O of n as I said in the beginning this question isn't that hard like you know you're just basically taking a number making it into an array iterating over that array from right to left and then from left to right and then just iterating over the array you know technically speaking like nothing in this problem is that hard it's just actually going through the process and making sure you don't mess anything up and it's not a technically hard question it's just annoying to code up and you can definitely make a lot of bugs there's probably places you can optimize obviously I did the um using a que here to optimize you can probably not do the second while loop in the case that there is no swap to be made but let's just not make it more complex than it needs to be this is already the most optimal solution so yeah that's how you solve maximum swap like I said one of my least favorite problems just cuz it's so annoying to cat up it's really annoying to explain uh I even got tripped up a few times and I've done this problem like a dozen times anyway hope you enjoyed video hopefully um you suffered through it uh with me and you know why not leave me a like and a subscription uh for explaining this God awful problem to you guys anyway thanks so much for watching I will see you in the next one bye
Maximum Swap
maximum-swap
You are given an integer `num`. You can swap two digits at most once to get the maximum valued number. Return _the maximum valued number you can get_. **Example 1:** **Input:** num = 2736 **Output:** 7236 **Explanation:** Swap the number 2 and the number 7. **Example 2:** **Input:** num = 9973 **Output:** 9973 **Explanation:** No swap. **Constraints:** * `0 <= num <= 108`
null
Math,Greedy
Medium
321
1,646
hi there so today's problem is get maximum in generated array so we are given an input of an integer n and what we are going to do we are going to fill the array of size n and return the value which is maximum in the array here we go we basically gonna have an array of size n here our size is seven so indexed from zero to seven and we have to fill the array with values and ah have to return what is the maximum value as the output so there are rules to fill the array the first if you look at the rules the index can be represented as multiple of two so if the if it is an even number or a multiple of 2 then the value is nums of i and if it is an odd number then the number can be represented as multiple of 2 plus 1. so the value will be numbers of i plus 1 so let's see this is the example given in our problem so numbers of 0 is 0 and numbers of 1 is 1 this is a standard value we will assign from 2 we are going to calculate the nums from the previous values that is from numbers of 0 in numbers of 1. so if you look at the even numbers that is 2 4 and 6 it is quite easy to find the uh index that is one list to two is represented as one into two and four is represented as two into two and three is represented as three into two so six is represented as three into two so there is a easier way to find that particular index here for index 2 we have the value norms of 1 so here this 1 can be represented as i by 2 because there is a 2 so 2 by 2 is 1 so if you observe 4 by 2 is 2 so here we are taking the values of numbers of 2. similarly for six by two is three and we are taking the numbers of value three so by this we are we had easily gonna get the value of even integers so coming to the odd numbers or our odd indexes the index can be represented as i by 2 plus 1 so here norms of 1 we represent as i by 2 here numbers of 2 and numbers of 3 how do we represent the next number that is i by two plus one that will become numbers of one plus one numbers of two plus one is numbers of three terms of three plus one is terms of four so this is how we are going to calculate our even and odd indexes so let's take our first example that is 7 which has index from 0 to 6 let us fill the values 0 1 so next number is an even number here we are going to calculate i by 2 that is 2 by 2 equal to 1 so here goes the numbers of value 1 so coming to the next number which is 3 which is the odd number i by 2 and i by 2 plus 1 here i by 2 is 2 by 2 plus 1 that is 1 plus 1 2 so we are going to take 2 by 2 is 1 numbers of 1 plus nums of 2 here numbers of 1 plus numbers of 2 is 2 going to the next number that is 4 by 2 is 2 we are going to put the nums of two value directly to four here we are moving to the fifth index that is 5 by 2 plus 1 so since it is an integer 5 by 2 would be 2 plus 1 that is 3 so we are going to add nums of 2 and numbers of 3 so numbers of 2 and numbers of 3 adds up to 3 again we are moving to the 6th index here 6 by 2 is 3 directly going to put the value of numbers of 3 to 6 so finally when you see 3 is the greatest number or maximum number in the array so we have to written 3 as our input sorry output so let's go to the coding page as we explain this example moving on to the coding part we are first going to declare an integer array nums to calculate our number values it is of size n so we are going to declare another variable max to calculate the output we are going to alterate before that we are going to declare numbers of 0 as 0 because these are the default values given in the problem and numbers of 1 s1 so what if n is equal to 0 there is one condition n is equal to 0 in that case if n is equal to 0 then return n so because n is the greatest value in the array so now we are going to iterate from subscribed index because we have already assigned values for zeroth index and first index since we are going to give a less than or equal to n let me increase the size of the array by one number i we are going to check first whether the number is an odd index or an even index so if it is an even index then norms of i is equal to i by 2 yes so i by 2 plus 1 so yes now we calculated the array inside the for loop now inside the for loop itself we are going to calculate our maximum so every time it inserts a new value in a number array it is going to calculate and store the maximum value out of the numbers now let's return the max value you
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
744
hello and welcome to another Elite code problem today we're going to be doing the promo of the day for June 9th and it's fine smallest letter greater than Target it's pretty straightforward it says you're given an array letters sorted in non-decreasing order in a character non-decreasing order in a character non-decreasing order in a character Target there are at least two different characters and letters return the smallest character and letter that is lexographically greater than Target such a character does not exist return first character in letters so what we can do imagine instead of having this like Target and characters imagine if we just have numbers right so let's just say we have yeah let's just say we have like a target of one in this example and then our letters would be like two three four so how would we do this and this would be the same way that we would do this we would simply what would be like the easiest thing to do well the easiest thing to do is just go right to left right and keep checking if the character is bigger than the Target and if it's non-stop right so we can check if it's non-stop right so we can check if it's non-stop right so we can check this it's bigger yes it's a bigger yes and then the last character that's greater than Target is our answer so like let's say we had a zero here then we would say yes no and that means this would be the character however the problem with this method is it's going to be a linear time right we have to search through the entire array and so what we could do is like I said in a lot of my other videos when you have a sorted array and you're trying to look for a Target the best thing to do generally pretty much is a binary search and so we're going to do kind of the same thing except now instead of doing that we're going to be we're instead of searching linearly we're going to be doing a binary search so we're just going to take some middle index and we're going to ask ourselves like okay this is greater than or less than Target okay well it's greater fine let's record this index we saw and if this is greater then we have to check to the left to see if there's anything else that's greater and if it's less than Target right let's say we have something like this one two three four five and let's say our Target is three or two yeah let's say fair gets five actually okay so we'd get to some middle element and we'd say okay this is smaller than Target which means we don't store this index as something we've encountered and we're obviously going to search over here and so if the number is smaller than Target we're going to search to the right if the number is greater than Target we're going to search to the left and we're also going to record that number and then we're just gonna search the left but we're going to pour the number and then whatever number we last recorded is the number that's you know greater like the first one greater than or equal to Target so let's kind of walk through how this will work for this example so let's say we have these indices zero one two three four five six and we have a res here then we can just make uh so we're going to make a number to start off so we'll just say because we want a number greater than Target we'll just make her as Infinity we want the smallest number greater than Target we're trying to minimize it right so we'll just make it infinity and I think there's guaranteed to be an output but even if there is a we can just check at the end as our as Infinity if yes then there is no number of Greater but anyway so I'll see how this would work so we would do a binary search so the binary search takes the middle of the array and if there's two elements in the middle it's going to take the leftmost one so we're going to go over here we're going to ask ourselves and there's going to be a left and a right um a left and a right Bound for the binary search so when we take this middle we're going to ask ourselves is this smaller or greater than Target it's smaller so we need to search to the right so if we need to search to the right we need to update our left pointer to be over here okay now we get a middle again so we're over here is a smaller gradient Target well actually equals Target and so if it equals Target we want numbers that are greater than Target so we need to search to the right again right so then we once again we update our left to be over here and now our left and the right are the same value and so we would get the six and that would be our result kind of how it would work is just a standard binary search algorithm pretty straightforward we just record numbers that we see along the way and then the last one we find I like to do it this way where I don't like to break like you could do something like you could say if you're like let's say you get to a number right let's say you're looking for number three and you have one two three four five six and you say you're looking for a number greater than three and you get to this four and you say you can technically have a thing saying like oh if my number is right after the one I'm looking for then that has to be the result so you could technically do this but then you have to do more comparisons and the time complexity is not going to change like when you do a full binary search of something it's still going to be log n it's not going to be any slower but then you have to do more comparisons and there's more edge cases so I prefer just doing a binary search until I'm out of bounds and then just storing whatever number is the smallest so let's code that up so we're going to have a res equals infinity yeah now I compared these with letters but um so actually instead of resume making instead of res being Infinity we just need something that's greater than the greatest than Z and I think that's something like ZZ would be greater than Z technically we could also get the ASCII value but this would work as well so this would be kind of like our Infinity quote unquote okay and so now we would do the rest of it would be the same we could just compare characters with a greater than or equal to type thing so now we have a left NRA just like in normal binary search length letters okay that's minus one it's a standard binary search algorithm okay so we need a pivot value and so remember our cases if letters pivot so one case is it's equal to Target then remember we need to go to the right because we need the greater elements so that's going to be left equals pivot plus one L if letters pivot is less than Target so actually what we could do here is we can combine these so if it's less than or equal to Target here we can combine that because we're going to go the same way if it's less than or equal to we need to go right so we can do that now we can have an else here so else what we need to do is we need to update our res right so whereas equals so I don't think you could do a Min but I can just have an if here so if res is uh greater than yeah uh letters pivot then we need to update our res we also want yeah so we don't we want the letter we want we don't want the index so we can just update directly uh so that's gonna be okay so we updated it now this is the case remember that we are greater than targets and now we need to go left so we need to do right equals pivot minus one now we're just going to do this full binary search so it's done then we can return res uh and then we will we'll just say We'll turn rather for as does not equal z this actually I think upper might be before so let's just do this just in case else res so we're just saying if we found something that's smaller than ZZ which would be any letter then we can return otherwise we uh we want to return if the letter does not exist yeah the return the first character in letters here we go so we want the first character in letters so less letters uh yeah that should work I think yeah all right cool so it's pretty straightforward what you could do if you don't want to do this letter comparison is there something in python or another language it's called the word I think which gives you the ASCII value of a letter and so then you can make Raz equals like infinity and then you could do order of all these letters which would give you the ASCII value and compare ASCII values that works as well but anyway let's think of the time and space complexity so for a binary search the time is um n log n because the most times like the longest it can be is um actually sorry it's not n log n it's login yeah so if our binary searches log in it should be slower faster than any time because we're dividing our output by two every time so if we have something linked like a thousand we're cutting off half every time right so we're dividing by two getting 500 dividing by 2 getting 250 and so on and so when you keep dividing by 2 then it would be something like 2 to the N equals whatever our length is our length and then n equals log base 2 of the length which is uh n okay and so that's the time and for the space we didn't make anything else we just use this left and right and red so that's constant space that's going to be a bigger one okay so hopefully you like this problem it was definitely kind of easy and uh if you did please like to subscribe to the video and I'll see you in the next one thanks for watching
Find Smallest Letter Greater Than Target
network-delay-time
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`. **Example 1:** **Input:** letters = \[ "c ", "f ", "j "\], target = "a " **Output:** "c " **Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'. **Example 2:** **Input:** letters = \[ "c ", "f ", "j "\], target = "c " **Output:** "f " **Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'. **Example 3:** **Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z " **Output:** "x " **Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\]. **Constraints:** * `2 <= letters.length <= 104` * `letters[i]` is a lowercase English letter. * `letters` is sorted in **non-decreasing** order. * `letters` contains at least two different characters. * `target` is a lowercase English letter.
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
Medium
2151,2171
1,675
thank you hello everyone so today we have this hard problem it's minimized deviation in Array um let's read the description you are given an array nums of n positive integers like given here and you can perform two types of operation on any element of the array any number of times okay if the element is even divided by 2 okay we can divide even numbers by two if the element is odd multiplied by 2 if it's odd we can multiply by 2 the deviation of the array is the maximum difference between any two elements in the array make some difference between any two elements of the other case so we have to find the difference between Min and Max of the array and then we have to return the minimum deviation the array can have after performing some number of operation okay so we have to minimize the difference between Min and maximum element by uh doing these operations that we can perform any number of times uh okay let's look at the example one two three four and see what exactly we are supposed to do so its deviation D is 4 minus 1 that is 3. so what we can do is we can divide this 4 it's an even we can divide it by 2 and we will be left with uh 4 1 3 2 and the max here will be three so D will be 3 minus 1 that is 2. then again what we can do is we have a Min as one what we can do is we can multiply it by 2 and then we will have uh two three two that will have 3 minus 2 and this will be 2. this is our maximum since we are trying to reduce the difference between Max and Mini foreign like this so we cannot do any operation on odd number to bring it down but we can bring it take it up to like take it closer to our Max number so that's how it is I think we will require a sorted array that we will have and login and this will be done like every number of time let's try if we can do it nums is nums.sort in English create a function in what this will do is it will just simply solve whatever array we gathered noise equals to nums.numz refers to Salt nodes and now what we have to do is uh we have this sorter so if we look at the minimum number we have to like increase it such that it becomes an even number and uh then once it's even then that means we are nearest uh to our high since high can be even or an odd change let's do a preparation I'm starting now and if and person 2 equals to zero we return n multiplied by 2 so let's return as okay because other thing that we can do is we can like keep multiplying it by two until uh actually if we multiply an odd number then we get an even number so three plus three is six one plus one is two five plus five is ten so once multiplying it once will give it our number and once we have it then we sort it again actually we don't have to solve it in the beginning we can move our sort here once we have this and then what we can do is we can move uh maybe like suppose it was like this and what we did is we made it two and we made it six and this sort sorting mode will make it like this so now what we have to do is we have to take this six and since it's the maximum and we have to take it down so what we do is we take it divided by 2 and add it back to our array so it will be two three six and now our difference is 4 minus 2 that is 2. so now since it's true what we do is we again uh we again take it and we've divided it will become 2 so we keep doing this operation until we have either our odd number or the difference is uh I think just having an odd number will surface we cannot take it down further so for this let's have okay and then we let Max is nums Dot part and at the end we have Max demand is zero okay now what we have to do is induct deviation equals to Infinity and then deviation is math dot main off Max minus min or this area person 2 is not even derivative of we have to return navigation division will be calculated like this and you can The Tick Max divided by two and we add it to array and then we sort the array let's see if it's working fine one two three four what we did is we did this now we have this array go to okay three and then we come inside we find Min and that is hello we find Max that is three we find deviation that is infinity or 1 and then deviation is one then Max person 2 is accumulated or so this is odd and we break and we return deviation let's take another example four one this so what we did is we multiplied one with two five with ten three with six and then sorted it so we have two four six ten twenty okay and then what we did is we went inside minus 2 . Min is 2 max is twenty and then we find a deviation that is 18 deviation is 18. and then Max percent it's not odd so we continue and push Max divided by 2 that is 20 divided by 2 is 10 so in the next step we have this and then we sorted then go back again take 10 and find a 8 deviation and push 10 inside it will go here then again take this will be it and we have another five here this will be taken out and we have deviation as four then we do it again 6 is now three and then we have five that is three it should be three yeah right let's see if it works it might give us a tle scenario oh that's a wrong answer let's try to see what is our nums in dnu now this is one two deviation is math dot min of deviation or Max management okay output is 2 how is it 2 if our deviation is 2 minus 1 that is 1. we are clicking minimum should be unsold.log let's run it again seven four one three one hmm deviation is three Max is 3 minus one initially Max is 4 . not equals to zero if it's odd then we multiply it you have to work uh it might give us a tle since we are doing a lots of a lot of sorting here maybe instead of this we can use a priority queue Max Heap that will give us a Max element and much less time yeah I was right it's a clearly so Min uh Min will be same initially Min will be this and then let's try to build them in priority cubes let's sort it first then build a value X equals to new uh I will have to check foreign the syntax for Max prior DQ okay it's this new Max priority queue okay then add everything to our Cube now this will have Max here minus here now what we do is we find Max from here speak she got DQ dot element and then let me find the difference and we push it to our priority queue EQ Dot and Q also we will have to see if a Min has been breached map Dot main off Min or Max developer 2. and uh let's see if we can run this let's start menu time limit exceeded again yeah right I didn't remove this statement I don't have to sort then array since you are using our private EQ now or let's try to submit it again ah nice finally we were able to do it and uh there are not many solution here someone used an AVL tree for it's pretty long okay thank you that's all for today uh we used uh beep let's add tag and that's all bye
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
246
welcome back everyone we're going to be solving Lee code 246 strabogrammatic number so we're given a string called num which represents an integer and we want to return true if that number is a stravogrammatic number and they Define a strip of grammatic number as a number that looks the same when we're rotated 180 degrees so 69 will look the same 88 will look the same and 960 will look the same so essentially all we have to do is um working with the string so we can't um we cannot modify it so we're gonna have to have some sort of array right and let's extend this array to be the same length as our number all right we're just going to return the string join at the end let's also have a mapping and that will contain the numbers that can be rotated so six can be rotated and it will look like nine and nine can be rotated and it will look like six so now what now let's make uh let's make a set to contain the numbers that we do not want um and so it'll be character four character in range can't do that I could okay we'll just make a tuple um so the characters that cannot be flipped right so two doesn't look the same as two flipped so we've got two three four five seven um I believe that's it okay so now what can we do essentially what we want to do is Loop through our number grab the character and place it in our array right but we know we're gonna have to if we do that right we'll have 6 will become nine so we place nine inside of our array nine will become six we play six inside of our array so inside of our array it's going to be 96. so what we have to do is reverse that at the end right when we return our string joint in order to get 69 which is what we're looking for so instead of having to you know Loop through do an O of N Run time to grab these numbers put them in our array and then have to do another o of n operation in order to reverse the array to get what we're looking for we can just use a pointer and we will set this pointer to be equal to the last position in our array right so if our array is of length 5 we have five elements in it so we will set our pointer to be four so we can get the very last element inside of our array okay so now we can Loop through our string so we'll say four character and num if that character is in um the Tuple Triple S right we know that those numbers cannot be flipped so we can just return false automatically otherwise if that character is in our mapping what do we want to place that number inside of our array but the flipped version so we will say array at position right we're going backwards instead of having to reverse it at the end we'll just do it all at once so we need the pointer the at the pointer position that will now equal mapping of that character right so if it's six it'll be nine in the uh whatever position we're at right and then once we do that we have to update our pointer so we'll decrease it by one okay so what if that character is not inside of our mapping right that means we can just append the uh we'll just place that character inside of our array so we'll say array of pointer will equal character and then we'll update our pointer and then we can just print this out so you can see it first print out a printout array get that out so what do we get so we've got six nine in our array so once we do a string join in return we'll get the correct answers here but um I guess what I'm trying to show you is that by reversing it by using a pointer we can just add the characters in reverse order instead of having to you know return um reverse our array at the end so now we can just return this return the string join of our array get rid of some spaces here we'll run this pass all the test cases submit so what did we do wrong here okay so we actually have to compare to the number submit and there we go it runs okay so what are the time and space complexities of this well the time complexities are going to be we have a for Loop here so this is going to be whole of n right we're using the in operator which is generally o of n but we're using it with a map so this is O of one so this entire thing is going to be an O of n runtime so we'll say o of N and then our space complexity is going to be uh the pointer is just constant um space complexity is going to be the length of our array plus the length of our mapping plus the length of our Tuple that we created so the space complexity again just down here just to type it out it'll be the length of our array Plus the length of our mapping Plus the length of our Tuple okay that'll do it for the code 246.
Strobogrammatic Number
strobogrammatic-number
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:** num = "69 " **Output:** true **Example 2:** **Input:** num = "88 " **Output:** true **Example 3:** **Input:** num = "962 " **Output:** false **Constraints:** * `1 <= num.length <= 50` * `num` consists of only digits. * `num` does not contain any leading zeros except for zero itself.
null
Hash Table,Two Pointers,String
Easy
247,248,1069
1,835
hi everyone in this video we are going to discuss the finds or sum of all things bitwise and so uh let us understand what the question demands so you are given two array let us say these are two arrays and then you will have to create a new array each element taking and with the other element of the array in this way and then you have to take the order of all these elements of the array three and then you have to return it so like a name star of alf bizarre of this you got it oh you have to return this so basically like first of all we look at the end it's 10 to the power 5 so the n square approach like creating the whole area three creating this area three and then iterating over the array three and taking this or of all the elements won't work since it will be of n square complexity so we have to do it in order of n so basically like we could have one intuition for zoro of two elements like let us say this is a element and this is b and this is c let me put some random values so any so if like we know this like if the count of the ones of any bit is odd then your then that bit is set so for example like here the count of one is zero so it will be zero doesn't matter the count of 1 is 1 so this will be your final bit after taking is or b's or c and here it will be 0 so we could use this intuition and we could solve this question now so i'll explain what we have to do like so let us say you are given this array abcd and then you will create a new vector like storing the 31 bits put in a vector and like and you have to store increase the bits increase that like for example the binary representation is one zero and for b is zero one so what i will be storing in my vector is one let us say it is two and one like i'll be storing the sum of the ones in vector so we would have to do this for array two like we would have to store the count of this ones and then once our vector v is created then we have to iterate over the elements of area one and if like and then we would have to iterate over every element of the area and we would see like which set bits are there and we would add the answer of that set bit into our final answer and we would also have to check like the count of the ones should be fought in that scenario and if it's odd then it shows like that value would be added and then we would take the power of 2 to the power that index it would be more clear from the code what i'm going to write so let us first declare this vector of 31 bits this is a final vector of 31 books so and then i would have to make check for um like you would have to like check that f which bit is set and you will have to increase it count over here like if so this value is greater than 0 then i would be updating my vector like this way and similarly now i would be iterating for the variable so i will check like if this is set then i would implement my final film and then i will move hydrate into my vector and i will see like if this taking it long and then i will return this answer so in this ways it will be in order of n into 30 in one complexity like order of n only thank you hmm i have to do this foreign so like to explain one more time like what i am doing is like i am checking like if a bit is set then i will be incrementing that index um in the vector and then i'll also check for this array one and i'll like update the summation of this value of the vector like which i got for a particular index and then i will check like if my finale of i contains the odd number of ones in that case i would increment my answer with power 2 to the power i to 2 to the power i and then i will return that answer so yeah this is the food so in case if you have any query you could ask in the comment section i'll try to answer thank you
Find XOR Sum of All Pairs Bitwise AND
decode-xored-permutation
The **XOR sum** of a list is the bitwise `XOR` of all its elements. If the list only contains one element, then its **XOR sum** will be equal to this element. * For example, the **XOR sum** of `[1,2,3,4]` is equal to `1 XOR 2 XOR 3 XOR 4 = 4`, and the **XOR sum** of `[3]` is equal to `3`. You are given two **0-indexed** arrays `arr1` and `arr2` that consist only of non-negative integers. Consider the list containing the result of `arr1[i] AND arr2[j]` (bitwise `AND`) for every `(i, j)` pair where `0 <= i < arr1.length` and `0 <= j < arr2.length`. Return _the **XOR sum** of the aforementioned list_. **Example 1:** **Input:** arr1 = \[1,2,3\], arr2 = \[6,5\] **Output:** 0 **Explanation:** The list = \[1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5\] = \[0,1,2,0,2,1\]. The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0. **Example 2:** **Input:** arr1 = \[12\], arr2 = \[4\] **Output:** 4 **Explanation:** The list = \[12 AND 4\] = \[4\]. The XOR sum = 4. **Constraints:** * `1 <= arr1.length, arr2.length <= 105` * `0 <= arr1[i], arr2[j] <= 109`
Compute the XOR of the numbers between 1 and n, and think about how it can be used. Let it be x. Think why n is odd. perm[0] = x XOR encoded[1] XOR encoded[3] XOR encoded[5] ... perm[i] = perm[i-1] XOR encoded[i-1]
Array,Bit Manipulation
Medium
null
1,822
welcome back everyone today we're going to be solving Lee code 1822 sign of the product of an array so we are given a function sine function which takes in one parameter X which returns 1 if x is positive negative one if x is negative and 0 if x is equal to zero so we're given an array an integer array and we need to let the product be the product of all values in the array nums and we need to return the sine function of the product so essentially what they're asking for is If the product of all the elements in our array is positive return one if it's negative return negative one otherwise if there's a zero in there somewhere right obviously zero multiplied by anything is going to be zero so we return 0. so to solve this we can do this in O of n time and of linear space or constant space I should say so how can we do that well we can just say we have a sine we'll initially set it to one now we can Loop through for every num in nums right if uh that num is equal to zero we know right away right that we can just return zero that's going to be our base case um otherwise if the number we are currently at if it's a less than zero it means it's negative so what do we do when we run into a negative number right negative times a negative is a positive negative times a positive will be a negative right so the signs are just flipped so we can just say sine will be equal to the opposite of whatever our current sign is and that's it that's all we have to do then we can just return sign at the end right because say we'll run through an example we'll say if we are at if our current number is um we'll say negative two right it's less than zero so our sign is already positive right and a negative times a positive will be what it'll be a negative and that'll flip our sign to be negative one if we run into a positive value we don't have to do anything if this is already negative when we run into a positive value the sign is going to stay negative if the sign is already positive we run into a positive value it'll stay positive so this is all we have to do we'll run this submit does pass and we can go back to the description and as I said the time complexity is going to be o of n we're just looping through every element in our original data structure and the space complexity is going to be o of one we're not using any extra data structures and that'll do it for Lee code 1822.
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
218
The problem is 218 10 and what is its height. Regarding its starting, I basically have to tell a skyline, which is basically how I am saying that if I draw its outline laterally, then my result will be something like this. Okay, this value also. So I can take that means why am I not taking this value or this value is given to me in the question that I have to take the starting position, here the value is changing for the first time, okay that means it is 15 so I have to start, I have to build. Okay, I have to return this in the output, so I know I have to return the output, so I have created the result, I have defined it and what I am doing is I am giving each building its starting point. Now basically this means what is their location in the building. I am doing it on the basis, okay, now look, this is a building, the building has started on you, its starting - 10 means what is its height - 10 starting - 10 means what is its height - 10 starting - 10 means what is its height - 10 okay, now as soon as the PlayStation comes, what will be the meaning of the building being cleared, I also mean multi. Set basically, here I will create a multistory, basically inside it I will store the height of all the buildings that I have so far, okay because I want to add a point, I want the maximum height from a particular location, like see if I go to this Location, what details do I have in this location, height is also 15, but which one will I get, will I take 15? The value is ok because I know what my value will be inside the skyline, whether it will be 15 or other values ​​too, then the maximum value. other values ​​too, then the maximum value. other values ​​too, then the maximum value. I will take 15, so I am doing multi setup so that I can extract the maximum value from here. Okay, I am defining another variable here, its name is current, which is basically what I am doing. What is the problem in keeping its top value? I can only remove it, whereas here I want that I want a maximum value on the point, neither from where will I get the maximum value, either from hit or I can get it from the formula of set multi set, so basically what is duplicate in multi set? Can be copied and I can store the value in sorted order Okay so I am setting my height multi in hit so I am not doing that inside the multi set inside the particular value I can do this I will pick you up how I am doing it ok and from here I can get maximum value from multi set I can get minimum because inside multiced the values ​​are because inside multiced the values ​​are because inside multiced the values ​​are arranged in ascending order ok now from LED I have initial value inside multi set is zero. And here the value of my current height is initially zero, okay, I will travel till here and tell you the complete value, now I will tell you the output value which will be the result within our result, how is it okay, till where will the result come, okay, it is zero. Ok current, this is a building started, what is its height, it is 10, so I wrote 10, ok, now my current value and the maximum value inside the multi set are different, ok, first I changed my current value a bit, so I made the point clear story. 15 Okay, now I will see my current, what is the maximum height inside the multi side, what is my current, it is 10, so this has changed, it means to update my current height, how much should I do, 15, I will have to do a little, sorry, some time has started in this, now I The next one is changing, meaning the value of the current one is changing, so I will write this point also, which index will be 3 and the height will be 15, then which results will be stored in my store till now. 0 I am five minus 12, so what will be my value in the multiple now? 12 is also my current height. How much current did it take? It was 15 and what is the maximum height now? What is the maximum height of 15? What are the values ​​at the maximum here? It is C train, I have 15 What are the values ​​at the maximum here? It is C train, I have 15 What are the values ​​at the maximum here? It is C train, I have 15 B, but which 15 will I take? It's okay, so here what is 59, the value of my 59 will come, the maximum value inside the multi set and what is the current height of my 15, which is both of them. Both are equal, what does it mean, I want this index because already here I have already taken it in 59, earlier which I have taken in three, this is what it means I will not take it, I will make it 12 minutes but I will take it. And what is my current height, okay and I will see in it after removing it, the maximum height in it is 12 which is different from my 15, it is different from the current height, it means that this point has fallen here or here. Fall has happened, it means I have to take this point also, so here I will update my current value first. Okay, after updating, my current value will be one and on which index the current thing has happened, then seven, earn, 12, output. Okay, I had already written this, I will make it a little bigger, clearly, the height of that building is not available, then I will update the current head with the maximum height and shoot it inside the result which I have just created. I have shown you till now, I will do this further also, so I basically want the result, I will do that little by little, now I will basically travel inside the building, okay, building, ending, with height, it is okay, meaning, I have reached this position till this position. Where am I till here, do I store dot and sorting If the first index of both is equal, then from here I would have got my question sorting, so what to do, basically now I have to define multi and define my variables. And now I will set default in one of my multi, what type of brick is its ok from multi, now I first set the default value in it initially shirt zero is ok if the value is negative what will be the second thing what will be the second case when it is inside positive By multiplying the store by If you want to start inside the result, then the same concept has to be requested. Okay, GST is fine, I have done it, I mean, I am Where is the value, the right part, OK, I want current inside the result, it should be equal to Star City, first current, I want inside my result, if that value is positive, it means I have to remove that and after that, set the present height which is the maximum height as multi. Inside, if there is a difference from my current height, that means I am at the down point, then I want that point also, inside the result, I make it mainstream. Okay, so once I travel all the way, then I will go here. What will I do? Return result is ok and here did you define min current height here.
The Skyline Problem
the-skyline-problem
A city's **skyline** is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return _the **skyline** formed by these buildings collectively_. The geometric information of each building is given in the array `buildings` where `buildings[i] = [lefti, righti, heighti]`: * `lefti` is the x coordinate of the left edge of the `ith` building. * `righti` is the x coordinate of the right edge of the `ith` building. * `heighti` is the height of the `ith` building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`. The **skyline** should be represented as a list of "key points " **sorted by their x-coordinate** in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. **Note:** There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]` **Example 1:** **Input:** buildings = \[\[2,9,10\],\[3,7,15\],\[5,12,12\],\[15,20,10\],\[19,24,8\]\] **Output:** \[\[2,10\],\[3,15\],\[7,12\],\[12,0\],\[15,10\],\[20,8\],\[24,0\]\] **Explanation:** Figure A shows the buildings of the input. Figure B shows the skyline formed by those buildings. The red points in figure B represent the key points in the output list. **Example 2:** **Input:** buildings = \[\[0,2,3\],\[2,5,3\]\] **Output:** \[\[0,3\],\[5,0\]\] **Constraints:** * `1 <= buildings.length <= 104` * `0 <= lefti < righti <= 231 - 1` * `1 <= heighti <= 231 - 1` * `buildings` is sorted by `lefti` in non-decreasing order.
null
Array,Divide and Conquer,Binary Indexed Tree,Segment Tree,Line Sweep,Heap (Priority Queue),Ordered Set
Hard
699
1,168
hello everyone welcome um to another video this is optimize water distribution in a village it's a legal problem um which is premium right a premium liquid problem I'm asked by Google Facebook and Microsoft so I hope you guys you know get a lot of utility from this video um uh there are basically we have um it's not like going deep and reading the question let me just like to explain it basically you have a number of nodes right um that represents houses and there are houses in a village and then we have been given a cost array which is pipes which shows you the connection between uh you know any two houses is a bi-directional connection and then it bi-directional connection and then it bi-directional connection and then it gives you the weight right the weight is the third element in the you know in the array right um and basically you've also been given another cost um I really called Wells where Wells is showing you the course of building a world at any house right um and then the question is asking you to return the total cost to supply water to all houses so you've been given a graph and then you're supposed to connect it such that it connects to every house right and then you supply water to every house so the question is how are we gonna solve this and if the previous explanation or what I was saying about connecting the main course connecting um different nodes and Rings a building you know that we are going to use cusco's algorithm right so we ensure couscous algorithm is a use of the unit find method right where um nodes that have it been previously connected can get connected and once they are connected you have the same parents right and if they have the same parents then any subsequent connection that wants to use um you know make those kind of connections redundant it's not going to be uh you know allowed so to even be able to solve this question you should probably look at redundant connection I one of the more popularly equal questions and also look at the main cause of connection houses which also a specialized legal question where you will use the union fine method so by using a union file we can create a minimum spine entry which connects every house MSD connect every house and then now the question is how are we going to approach it with the wells because we also have to have at least one house connected to a well right so that it can supply what's up to everyone well we can still have this as an MSD problem if we create an imaginary node called node zero and then use the well like we connect the node zero to all the nodes right so we call the currency to node 10203 here right and then after connecting them we choose the one with the least weight I will be using couscous algorithm and then its weight will be the cost of building what the house hey sorry building the well in the house that is connected to right so um that's how we are going to approach the problem and I just want to demonstrate it using uh on the Whiteboard right so basically we are just going to look at the one from the question one right where we have the edges and as I was explaining I want to have an imaginary note like this zero and then basically with the minimum science is gonna connect to one of these nodes but I'm going to choose the one with the least width so here we have the one with the list which being one so what's it connecting to one as well as the course one so in the end you add this and this these three um cost each of one and you get the total cost the minimum total cost so I wouldn't make a minimum spanning tree so how are we going to build our minimum Furniture as I was saying that like you make I know so like you know zero connected to what every single note to have no zero connected to one and it was the course of that is what one which is the cost of building then the um water source at one right so one um again from zero to node two what's the cause the cost is two and then from zero to node three and then all the nodes we also have in here right we have um we have one two the course is what one and then we have about two to three and of course is what one so my cool skills algorithm I will be will initially sort the edges all the edges we have by their ways right so the minimum wage once will be there first and then we connect them like based on the ones with the minimum wage so the ones the minimum weight here I would I'm zero one two and two three right so um in the end we have we'll pick the first one which was zero one zero and one they have the same parents right so a connection like zero two would not be valid because like it would not be valid at the time that I want to use that right so let's you know first go through the edges that we are interested in so zero one and uh cost one um one two cost two one again right and then um two three uh also has a cost one right so in the end we've actually we met all the notes right if um satisfied not one no two no three and I'm new imagine you know zero right we've reached the End plus one notes so we've actually processed everything and then we just return our main cost but let's see that um this 0 and 2 was what one The Edge was one and then we had previously made this connection made a connection with um two and one in the same group one and zero in the same group and now we have this and we want to connect zero and two it wouldn't I wouldn't be allowed to do that because um Arduino find method is going to detect that they are already in the same group so if it's in the same group that connection is redundant so I'm not going to use that it's not going to appear in a minimal spanning tree so basically these are MST um and without further Ado let's get into the coding um I don't really have a preference between what I usually do which is like whether I use the dark mode or the lights I think the light one is easier for the demonstrations but first we want a priority queue and I'm going to take an edge right and so we'll call it here where um let me if you have um two elements EB and I'm going to click create those class bar right back in season right okay so basically what I want to do first is create um and let me list them in steps all right so that it makes sense um create an edge class um second I want to go to create uh you know find class and then um use um sort by weights I think I've already started by doing that with a priority queue and then um build our MST so basically this and let me just follow the rest and then we'll get back to this function which is for me and cost to supply water so um a class of edge all right which arguments is he taking basically it's going to take the sauce and all right so you we're gonna take um V and it's going through the costs right so probably and this is how I want to be and then the cost all right so this is equal to you and this is equal to V and this of course is equal to cost right so now down with that part and then we also want to create a class of you know find okay so um you know if I will have parents right and every node will initially be able to own parents will have ranked and then um probably you know fine to take and ends in and then our parents are will be an interview of what m size n and then rank also was being an entering of size n right and then basically I want to set each parent to itself actually right so yeah uh and let me just use n right and K plus key is set to key I'm current uh also and run okay it says one initially all right so I have an intimate method where we send the appearance right so it's while I is not equal to parent I you do some path compression appearance I right parents of clearance you see I'm going and then eyes um it says to print I and when this while loop is done executing return our eye right um and then we have abusion function where I'll use it to you know connect you know two no two we are connected to those only check first who their parents are and if their parents are the same as them you know that it's already connected so um if you would a is equal it's a is equal to speed right in the house we can and I'll return false right y because they are already connected else we want to then assign the based on rank um assign Roots based on ranks we'll see um parents sorry um if the rank of root a is greater than the rank of root B there would be experience now becomes root a uh right release B is equal to a and then the rank of roots a increases by the rank of roots being um do the oppositions Within foreign okay so once that is done we repent through right we've connected um the components successfully they run already connected um so that's done Chris Edge class create unify class and now I'm going to sort by Roots right so that's what we're initially doing here where we create our priority queue which is Edge right and then it solves the edges by the cost or the weights right um so that said I want to also create a union find objects right this is what we'll be using to make our MST I mean it's going to be n plus one why because of that zero it Edge that we created right so it's going to be up to n plus one all right cool and I also need um our main course right that's the cost of making a spanning tree and then the number of nodes that we've process so if the number of knowledgeable process you want to when we process n plus one note then we you know stop working on it so basically you want to watch you first right so in filling our PQ we're going to create those new edges which connect the zero ethno to each of these nodes so I'll save for I mean it's K is equal to one and it is less than um and plus one right and then K plus then I want to create a new Edge so call it as a new Edge is equal to uh is equal to zero and then it's going to go to sorry it's going to go to key right and then we're going to use who else K minus one right look and the question even likely to you so for each house we can either build a world inside with a direct after I do the course Wheels I minus one right and minus one um Okay cool so K minus one when I'm building it well and then we add that to our priority here right else um we once go through pipe and add every edging pipe to operate again like tools see again a new ad is being created a new Edge is equal to wow pipes is zero either pipe one right which is the source and the destination but this biodeirectional and then the crossroad which is part two basically um okay cool so we filled our PQ now is I think we're going to do is to go through every element in our Peak you know sorting by what I'm gonna sort by um by The Edge weights right so who has a picture is no empty and by the number of notes we process is less than n plus one if it is less than n plus one then we are good to go so then we take the current Edge that we have to see as the current this was the current this was the current this was the and then I want to say it's I is equal to that current dot U right and then J is equal to V and then and um and uh let me see let me call it w right it's our current dot cost right so we have a Boolean and I want to call it unite right um so basically it's going to take the unifying object we have and then um have a make a union between I and G right now basically if the is already being connected it's going to return false but if it's not being connected it's now being connected it's going to return true so basically based on the value of United you can um add to our main cost or not so um if you're nice right that means we just added them they are now it's not a new connection also this increase the number of pro motive process will actually increase process by one and then the cost is going to be in exercise it's four main course right the main course is going to be increased by what the cost is here which is what's W right so then once this is done executing we are done you know either condition without the priority becomes empty or you know we hit the number of nodes 200 has been processed right once you are done with that we want to return our main cost so that's that should be it um it passes first two tests successfully and then right beats 70 something percent so that's good enough um okay so now the question is um what's the runtime right that's a good question to ask now and let's go through this together basically we look through each Edge right so and edges we create for each but we are creating them here so n of n operations here of an operation is here right and then off and operations here basically for each Edge you're going to check if what we can add it to uh you know find method now a unifying method right this class is going to have a whole runtime of course Alpha whatever Alpha is I think Alpha is like almost constant right so it is n times Alpha that'll be your runtime overall and um that should be it guys um I you feel free to look at the code in the um the description below um like And subscribe I'll see you on the next one see you guys soon bye
Optimize Water Distribution in a Village
duplicate-zeros
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Array,Two Pointers
Easy
null
810
cool okay 810 chalkboard XOR game we're giving non-negative integers num sub I giving non-negative integers num sub I giving non-negative integers num sub I which I've been on a chalkboard Alice and Bob which open common names in game theory so I feel like it's gonna be a game for you one Alice and Bob take turns you racing exactly one number from a child boy but Alice starting first if you're raising a number course the bitwise XOR all the elements in the childhood to come soon then that player loses also go say dip it by six or advise knowing no element it's yeah okay also if any player start to turn with advise X of all elements you go to see that point wins okay we turned true if and only if Alice wins the game assuming both ways quite optimally not journalist in Boca okay so Alice have two choices UN spawning race to end it's a thousand and you trip the number is to 216 that's actually apply the key thing to know because 316 for like 30 mm Oh $65 I shined on Darwin if that's the $65 I shined on Darwin if that's the $65 I shined on Darwin if that's the number of bits and like a short way sorry Eggman said that long it's not to them with pizza - went but that's like in a with pizza - went but that's like in a with pizza - went but that's like in a short test the biggest number anyway okay and okay so no moon haha that's fair I mean it definitely forces me to think about stuff for sure I think mmm don't bring a thousand is a little wonky like otherwise I will have some way of proof forcing it I mean my problem with some of these game theory once is that sometimes there are they just like a very weird catch to it and I don't know but wait do you like it makes it less programming me and more came free ve which maybe it's okay about who you ask I'd say one thing just like in general the two to the sixteen makes me think maybe there's a way to can't prove force it but I know maybe there's a way to pre-process these maybe there's a way to pre-process these maybe there's a way to pre-process these numbers as well sixty-five thousand and eleven max but sixty-five thousand and eleven max but sixty-five thousand and eleven max but that also depends on the state of the numbers available you just cost wise a little weird but maybe it's not because you can't like go backwards on it and the other person is not going to well I think one thing I'm trying to think first of all is well is it path dependent cause you're never gonna I'm Preakness you never gonna use the same number twice I mean except in this case where we like we moved to duplicates because that doesn't change the game right because it's like easy proof where you could remove not all duplicates but just pairs of them because of Alice goes first and what and you choose one of the numbers then if it is optimal then Bob will just choose to same number and then you have the same state and if it's not optimal there and you just lost a game so there's no reason for you to choose that or it doesn't affect I'll come with the game right like someone like okay so you have a number to not play maybe two four and six I think there's like a weird thing where like you count the number of bits and then like number of ones and then that will determine like the parity of the game and you always want to stay within the same parity something like that like some kind of like in the names came right well let's see when I started initial state of the game nothing with it did before to like even one two three then you could get into loop one is the right solution for one two three all right you can't get into that because if you start on this state you already win so that's not a good status so you're taking it and making it so you will never be in this state because it would mean you were lost or one night yeah restarting the state you win right so yeah so you don't get any weird psychos maybe and in that case maybe you only you could assume that each number only gets used once and then you could to be cushioned based off that maybe oh I'm I think that I'm just gonna play around with coding this out and see how food have some assumptions that been trying a little bit understated browsers iPod I can see was an interview or at least of your baby view that I can finance and doing some kind of no crazy and it let it go stuff or something right yeah that's my type of search should be N squared and okay you're right mm that sound what's happened my what they're knowing about part about this is that I don't generally have a good sense of how hard it is sometimes like the last one I got you looking like okay this is hard but this one I don't know could go either way well I like yeah I mean it's still hard just like maybe I know the answer or not is it odd something I could judge easily this is a winning state for nobody's you only window on out of there don't know if this is right that's a general right here - five huh these have two different things now because you could burn a zero to be in the same state to change parity Wow there was a weird I just thought you would just ignore it and this it helps you okay I'm gonna cheat it over and see if that changes things okay well and that makes sense as you could use zeros to change the parity and then match them afterwards that helps you win if you go first yeah I really don't have a color test for this okay good I don't think I was worried just I was really lucky and obviously during a contest I probably have submitted anyway to be honest because I have no more pits to kind of like I don't know anything about okay so it's less consistent that if things as a real-estate race now I need maybe I as a real-estate race now I need maybe I as a real-estate race now I need maybe I need a an example that's what I just bought and this one's to you maybe number that I had oh that's good maybe on your deaf research cause every time to district office like I feel like having it family I'm saying do all the other ones with again just so I don't smoke everything yep so this is still the unique case Cory stop thinking about it okay so what do I have here I have one so there's no way to get sue in the middle and us News as you pick any number how this will be stuck in the last move which I don't really consider in how I do it just a good book go to 15 or the one number what's a parrot 9 to 15 and two numbers and I get a seven and an eight that's not what I want to do okay come at me I'm just gonna be write this in deficit you feel like I'm messed up the combination of improv research yeah because what you want to be cute next appointments okay otherwise if Titus true meaning day one you don't want it to it and I'll be cashing attendez shows bit I guess it is evil I'd even with this psychosis clatters it's the way I do it is I caused hey I missed that point when I said I wanted to do an easy one too I mean I think that's the palm of teasers game theory ones is that I don't know like it's not very here's a fun part it's just not an interview question yes which is kind of weird fully code but maybe not thanks for the kind of staying with meter I think to be honest if you know I try my thing on all the contests and then I'm fine I'm just giving up on this one because I feel like can't be what game theory stuff is kind of hard and weird yeah but I also feel like game theory is not a thing that I don't know interview should be testing unless you're like I guess and Finance or something like if you give me a hit sorry I've kept you I still need to figure the extra sample that's we're good I used it for like probability stuff like statistics but uh but not anything too crazy and I could think about I don't know maybe I have I met there is that one time where are you styling programming tick to tile pictures on a in a pretty way using some cost function but I did use dynamic programming back in they come when I was really into computational biology back in the day but uh that was part I could take and a half ago so thanks I am trying to still figure out this one for us and they may run to that one thanks okay let's break this down what is it what does it mean when what does this number mean over there yeah it's been a while I mean I'm not good enough to do researched type things well I don't have the patience or I mean maybe both but uh but definitely back in the day I was way too interested in it and it was good okay they say there's a zero what does that mean if just X of everything is that means to Italy what's what why don't we tell anything but expected to be true let's go so about it that's cool why is that true oh because okay well now they're obviously because if it anyway starts to turn Versailles okay so if this is Susan Alice wins so this is true I haven't otherwise yes the Penguins tend now you can just one thing about I guess in this case we're never just afford to lose and then everything else would never pick so to all right let's go fact base principles oh man I'm yeah I don't know if I could prove this there are pockets don't stall I'm thinking like about parity and I think don't and that's why I have these two examples this that you could only change to parity if like they say you have a link and away oh yeah half a now maybe I'm just a little tired okay give an end link away well the default cases that you just pick alternating ones and then the last number gets picked and others went to achieve a number and pop into okay yeah so it's even palace wins okay but I think the thing I'm trying to think is well I mean this is not true okay but I'm thinking about like so in general game theory when you talk about like names numbers and stuff like that you essentially have civil states where or yes similar states where you're what they call max maximum X current number which is called Max and me expecially so those the other states for that it's all or when I mean it's explicitly given by the farm to be zero and the only way to kind change that is to change their parity but because all those states are losing states or winning state but there are ending states there is no way to change parity because the only way to change parity is something like one two three where you have odd-numbered lengths to where you have odd-numbered lengths to where you have odd-numbered lengths to get you from a winning state to a winning state and we have like one two three four you never lose it because yeah you never lose because it's even number and you will never choose to for you just choose anything else I can't be it right is there a way to have two sets of numbers that exhort is evil now despite the definition of how extra works to get to zero there's only one number that can make that zero and you just not choose that number and because just I feel like I also spend an hour the other day on a game 3d problem because and it was like three lines of code so yeah see if this works I received this works participants older sister also I'm I'll be very upset if this is the case this works even more so tended washing-machine qualms about so tended washing-machine qualms about so tended washing-machine qualms about this my god I guess it makes sense I just don't and even this part is just because it's given to us kind of directly I hate this part I mean maybe with some hints in an interview maybe that's okay but I would do a little bit more programming that this i think thats thing and i spent like half an hour and this way i don't know if i would have damaged you'd explain this better yeah it's I don't know it's too much math maybe and I love math I mean I think it's a fun part yeah to some degree just not necessarily I don't think I would like if I asked this on in to be a problem I would probably hear it from my manager the next day like what are you doing there and then like I don't forget justify that alone you know I could be like right oh well they'll be like I would definitely hear about it I did it they'll be like Larry the way to correct solution is five lines of code you said you know one with the interviewee for an hour and a half what were you doing very just about it but yeah I don't know I mean I guess my line to make sense is just one of those things were like how do you convince yourself of it and that's also part of doing like I think the other game freeform that I also spent like I would take his amount of time one it wasn't even coin cold hard it was like it was a nice it was great as easy I just felt a long time because I couldn't prove myself that is right but uh you system O'Keefe is a fairly a funny let me get an emoji so I have been using abandoned me okay but uh yeah I mean what else to say about his phone I feel like if you're still watching me talk about this problem you already have your opinion on it so I've magus anymore I mean this is it is what it is I mean I have some maybe intuition about this it's just that I don't know I not feeling very good right now so I thought I'm gonna say about this farm I mean I think like you could
Chalkboard XOR Game
valid-tic-tac-toe-state
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Array,String
Medium
348
1,288
hello so continuing on this beauty contest 15 second problem remove covered intervals says that given a list of intervals remove all intervals that are covered by another interval Andalus which means basically a B is considered covered by a by the interval C D if a is if C is smaller yeah that wording is a little bit hard to get but essentially here you can see a is bigger than C D is bigger than B so that means that the interval a B is inside the interval C D so it's covered by it especially if you look at the example here you can see 2 8 &amp; 3 at the example here you can see 2 8 &amp; 3 at the example here you can see 2 8 &amp; 3 6 is entirely inside 2 8 and so we 6 3 6 is entirely inside 2 8 and so we say that 3 6 is covered by 2 8 and why is that because let's say here abs cover if a is 2 and 8 is B so C you could see here C 3 is bigger than 2 but 8 is bigger than 6 right so that's essentially what it means and the goal here is to return the remaining intervals which means the interprets that are not covered by anything and here if you look at the constraint the length of the interval is 1000 and the interval range can be 10 to the power of 5 and all the intervals are don't have the all the intervals have different the start is different than the end and if we look at this example again 3 6 is completely covered by 2 8 so 3 6 is doesn't we remove it and so we are left with 1 4 since it's not covered by anything and - 8 cents also it's not by anything and - 8 cents also it's not by anything and - 8 cents also it's not covered by anything notice they still overlap there is nothing wrong / laughs it just we'll just remove those / laughs it just we'll just remove those / laughs it just we'll just remove those that are covered and so written end up returning those left which is 1 4 + 2 8 returning those left which is 1 4 + 2 8 returning those left which is 1 4 + 2 8 okay so the first simple way that we can solve this problem is okay let's just pick every interval and check if there is another interval that covers it if it there is then we should remove that interval if there isn't then we should continue and check the next interval right so basically the steps would be just for every interval just check if there is an interval that covers it so that would mean for every interval mean we need to go through let's say for the interval is a B and its index is I so with enumerate intervals right and then we'll start out with all the intervals remaining and we'll remove those that are covered right so remove it from the remaining if we found one if we find one that covers it that is then that means we'll remove it from the remaining intervals so very straightforward so here we go through the intervals and check we what we need to check here if there is an interval that covers interval I and so to do that let's just check all of them right so again we will check all the intervals CD here right and we need to make sure that of course it will be covered by itself and so we will need to prevent detecting that as cover advisor we need to check that is different than J which means their index is not the same here right and then we check if it's covered by it if CD covers a B how do we do that who uses the exact formula that the problem gives us so we want to check if a B is covered by interval C D so we can just use this formula and so and this so this happens that means a B is covered by it is covered by CD right and so that would mean well Abe we need to remove a B because we found an interval that covers it so we say remaining we subtract one because we find one interval that is already covered by something so it's not among the ones that we need to return but and once we find one interval that covers it and we removed it there is no need to check if there is another interval that covers it's or we know already that it's covered by one and that's all we need to remove it and so we can just break out of the slope so that we can check this another interval and see if we find another one that covers it and that's pretty much all there is to it and this one is simpler because there are no like indices to get around and so we could easily solve it with it okay so listen it okay so this passes the test cases okay so for the other method there is another way to solve this basically and so for that other way is we can notice something so if we solve the intervals by in ascending order which means basically it's by stars first and then if the stars are equal then we solve by ending always in ascending order right then we'll end up with only one case there are only two possible cases right or maybe three potentially but one case is we could have the first interval like this so this would be interval one what's called this one interval one then the second interval eight maybe is completely contained in it right maybe it's like this the other case that we can have is maybe the interval is like this since they are sorted by start so the first one the start has to be before the second one or maybe this is the first one and then it starts like this and ends after the end of it because so we would have because the starts has to be st. it has to be sorted right so maybe it's like this or the other potential case is that the intervals are like this so once this one ends after it maybe would have the second interval at some point right and so the only case where we need to not count the interval is this first case right so it's only this case right and so let's just give these the there a name right so let's say this is C and this is D and this is a and this is B so e to is contained in a 1 if basically see is less than or equal to a right and be it has to be less than or equal to D because y less than or equal because maybe it's like this they have the same values and at that point they are still abs contained in C D right and so with this case we know it's covered all the other case all the other cases the interval e to is not covered by e1 right and so this these cases here which is the else case right here it's not covered and so we should count them right and so this gives us the hint of what should we do now another thing is that well now once we say that e 2 is contained in a 1 what should happen for the next interval so let's say we have another interval may be contained like this maybe this is I 3 so what should we do them well I 3 we should compare it against a B check if it's contained in sorry I didn't mean this one because I 3 we can check so like a CD I may in this case for example we should the next one maybe is contained in E 2 which means here for us that we will need to update so this is CD a B so we will need to start checking once which we determined that it's not covered by CD we need to update our CD values so that C becomes here and D becomes here and this becomes a and this becomes B so that means that in the else case what we will need to do is we need to at least say CD is equal to the current interval so that for the next iteration we can use it and then we will need to of course increments I so that the next interval double bello cannot would be this one and here - only two would be this one and here - only two would be this one and here - only two and so our algorithm then will look like the following so if we define our method here for remove covered interval because we would have Weald first need to solve the intervals in ascending order so that just intervals dissolved and then after that we will define our CD as for the first interval so start out with them pointing to the first interval and then from there we will need to define some I value that we will initialize to the second interval if there is one right and then we'll do a while we haven't processed at all intervals so while I is less than the intervals and I'm just going to keep track of the contained intervals in a list or maybe just count them just count the covered intervals or scroll them cover at a step so let's count the coverage intervals so if we count the coverage intervals to get the remaining ones we can just take the length of the interval minus the covered ones right and so here let's say a B is going to be equal to the current interval right which is the one we are examining at each point and so it will be interval I and now we'll check if it's contained using the formula here that we said and so that this is basically in my case this is i2 and CD will keep always track of the a of the interval up to I one in this representation here and so we will check using this cover and check that the problem gives us if C is less than a and B is less than or equal to D right then that means it's covered so that means that who will need to increase coverage by one and then we will need to go examine the next interval otherwise it's not covered right so as I said we will make update a and B so that the when we go to the next interval we will compare it against the interval before it right so that would mean in the else we'll say C and D become intervals of I and then we'll increment I again and at the end Walnut return the remaining ones is just anything that wasn't covered so the length of intervals then - covered and length of intervals then - covered and length of intervals then - covered and that's pretty much all there is to it yeah so sorting makes this easier to do so let's write this Inlet code and make sure it passes the test cases okay so now let's write the what we just saw in the overview so I'm just actually going to copy it since we already wrote it so just sorting and then so this we said we are going to use a variable instead so cover it I guess initialize it to zero I to one and here we just need to say coverage plus 1 and subtract to get the remaining we just subtract the coverage from the length of the interval the rest is the exact same thing that we just saw in the overview and so let's submit this and make sure it passes okay so that passes the test cases and yeah you could see here we go through the interval only once right the elusive intervals only was so it's a woven in this portion here and it's the length of the intervals but the searching is opened by again so overall it's over again yeah so that's it pretty much for this problem thanks for watching
Remove Covered Intervals
maximum-subarray-sum-with-one-deletion
Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list. The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`. Return _the number of remaining intervals_. **Example 1:** **Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\] **Output:** 2 **Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed. **Example 2:** **Input:** intervals = \[\[1,4\],\[2,3\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 1000` * `intervals[i].length == 2` * `0 <= li < ri <= 105` * All the given intervals are **unique**.
How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm.
Array,Dynamic Programming
Medium
null
451
hello everyone this is sham Saar and I welcome you again in the next video of our YouTube channel uh this is the 7th of February problem and the name of the problem is sort characters by frequency it is a medium problem uh here they have given string s and we need to sort it in decreasing order based on the frequency of the characters so the frequency of character is the number of times it appears in the string and we need to return the sorted string if there are multiple answers and WR any of them so in the example first there is a tree it is a string and we need to return e r t because e appears twice while R and T both appears once so e must appear before both R and T and therefore e t R is also a valid answer here in the example two c a here a cc because both a c and a appears three times so both C this and these are valid answers note this is incorrect as the same characters must be together and in the third example a b a BB here this is also valid answer BB AA and this BBA AA is also a valid answer but a BB is incorrect note a and a are treated as two different characters because the S value of capital A is different from x value of small a so we need to return such string so how to approach this solution so we will Define a custom comparison function which will which I will explain further for what reasons I have come using this comparison function we will compare pairs of characters and their frequencies after that we will initialize a map MP to store the frequency of each character in the input string s so we have we will initialize a map to store count of each string each character and after that we will iterate through each character in the string s and we will update the frequency count in the map uh then we will initialize a vector of pairs WX to hold characters and their frequencies from the map MP then we will populate the vector WX with pairs of characters and their corresponding frequencies from the map after that we will sort the vector in non on non-increasing order of in non on non-increasing order of in non on non-increasing order of frequencies so for that reasons I have Ed I have used this comparison function so sort the function V in non increasing order for that we will use the comp custom comparison function and after that we will initialize an empty string St Str to store the sorted characters based on frequency and then we will iterate through each pair in the sorted w and append the character to the string s Str as many times as this frequency and at last we will return the sorted string which will contain the characters sorted based on their frequencies so this is the approach we will follow let's code this code the solution based on the approach and I will explain you in the code also and if you are new to the channel hit the like button and subscribe for more content so let's create a custom comparison function for what reasons I using this comparism function let's discuss first we will create map of character and in mp sorry then for every character in s we will populate the character and save their frequency in the map then we will create a vector of pair of character and in Vex now we will itate through the for Loop is in mp so Auto MP in map we will push back vex push back pushor back we will push M do First and M do second value and this and here we are soling vix do begin and vx. end and a comparison function so we need to sort and that's why we are using this comparison function so static P form and what we will do here we will initialize cost pair character and in and a and con pair of character and in and I'm sign B and we will return true if a do second is greater than b do second so we will compare this V according to the second value which means the second value is in the Vex so this the second value in the Vex is nothing but the frequency of that character so we are sorting according to the frequency of that characters so that's why we are using this custom comparative function and at last we will initialize a string and for auto Vex V inex for each element inex we will do a while statement and check if P do second is true if this is true then we will concatenate uh V do first in the string and after that we will decrement the count of w so w do second we are decrementing and at last we will return Str so this is how we will solve this solution so sorry solve this problem let's check the test cases okay yeah let's check for the hidden test cases so solution ran successfully here time complexity will be big of M log M because we are using some nested for loops and while loop for Loop and while loop so the time complexity will be B of M log M where m is the unique characters in the string and the time space complexity will be big of m + will be big of m + will be big of m + n so that's it if you are so that's it if you enjoyed the video or found it helpful don't forget to hit the like button and subscribe for more content stay tuned for upcoming L code problem on the day videos and exciting monack web development projects happy coding and let's make this year a fantastic one together thank you
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
279
hello everyone this is sham saari and I welcome you again in the next video of our YouTube channel so this problem came in 8th of February and we are discussing this medium level problem perfect squares here they have given an integer n and we need to return the least number of perfect squares square numbers that sum to n so a perfect square is an integer that is square of an integer in other words it is the product of some integer with itself for example 1 4 9 16 are perfect squares while 3 and 11 are not because 4 can be written as 2 into 2 9 can be written as 3 into 3 it is 4 into 4 and so on so they are perfect squares so in the example One n = to 12 squares so in the example One n = to 12 squares so in the example One n = to 12 and output will be 3 because we can add 4 3 times to get 12 and four is the perfect square so we need to return the least number of perfect square numbers that sum to n let's suppose for n = to 13 so we will let's suppose for n = to 13 so we will let's suppose for n = to 13 so we will add 4 and 9 because they are perfect squares and they are adding up to 13 so we need two perfect squares to do that so we will return two and we need to return the minimum number of perfect squares required to equal the m so how to approach this type of Sol uh problem let's discuss so it is a DP dynamic programming type solution we will use a DP array for that and we will store minimum perfect square counts here we will store minimum perfect square counts and let's suppose uh we will set base case for DP of 0 = uh we will set base case for DP of 0 = uh we will set base case for DP of 0 = to 0 then we will iterate from 1 to n for every iteration so for each I we will iterate through the perfect square candidates so J into J we will check for every 1 = 1 into 1 so 2 into 2 4 we will every 1 = 1 into 1 so 2 into 2 4 we will every 1 = 1 into 1 so 2 into 2 4 we will it through perfect square candidates only and then update DP of I by taking the minimum of current value and DP of I minus into J + minus into J + minus into J + 1 uh from this we will return DP of n which will represent the minimum perfect square count for n using this example using this uh formula we can achieve that so let's code for this solution before that if you are new to the channel hit the like button and subscribe for more content so we will initialize a vector of N and we will create a DP array of size n + n + n + 1 with every value as in maximum means infinity and then we will initialize d 0 = 0 after that we will iterate through = 0 after that we will iterate through = 0 after that we will iterate through the for Loop uh from one to n and we will increment I and again we will initialize a for Loop we will Implement a for Loop for in J = to J = to J = to 1 and J into J less than equal to I so we will just uh checking only for the perfect square number numbers so our J value will be we will acted through our J value only for the perfect square numbers which are between i j = 1 to I so we will check DP of I i j = 1 to I so we will check DP of I i j = 1 to I so we will check DP of I equals to we will take minimum of DP of current I value and DP of I minus J into J + 1 we will take the minimum of J + 1 we will take the minimum of J + 1 we will take the minimum of this and after that we will return DP of n by this we will calculate the minimum amount number of uh perfect square numbers we need to add to the solution and we will return the DP of n let's check the solution yeah the test cases unsuccessfully check for the hidden test cases yeah the solution the hiden test cases also run successfully talking about the time complexity so it will be we go of n into square root of n because we are in using two for Loops nested for loops and it is running in 1 2 N and it is going for the square root of N means overall time complexity will be bigger of n square root of N and the space complexity will be bigger of n because we are using this V Vector so that's it if you enjoyed the video or found it helpful don't forget to hit the like button and subscribe for more content and stay tuned for upcoming lead Cod problem of the day videos and ex writing monack web development projects happy coding and let's make this year a fantastic one together thank you
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
1,395
hey folks welcome back to another video today we'll be looking at question 1395 count number of teams um the way we'll be approaching the solution is by uh inspecting each and every element and looking at how many elements that are to the left of the current element which are less than and greater than the current element and to the right that are less than and greater than the current element so let's jump right in and we can i can explain the logic as we go let's initialize um the result that we're actually passing to be zero in the beginning uh n would be the size right so let's start off with the for loop for i is equal to zero i less than weighting dot length oh so we have since we have n let's just do that um and j is equal to zero j less than n so as we discussed we need to keep a track of the elements that are to the left that are less than and greater than the current element and the elements that are to the right that are greater than unless on the continent for which we need two integer areas so let's say a left and let's say you knew end of size two and in right which is our right two end of two so this area right here the left uh array will keep a track of in the zeroth index we'll keep a track of all of the elements that are less than uh the current element and at the left uh the first element is so the second element of the left area will keep a track of everything that's greater than other current element and the right will keep a track up and uh right of zero we'll keep a track of everything that's less than the current element but to the right and right of one will keep a track of everything that's greater than the current element to uh the right so for example if we take this example right here ctrl c these this is what the areas would look like so let's say this is left and this is right and we're looking at let's say let's take the middle element let's take three so just for that particular element in the number of elements that are less than uh less than three to the left are one the number of elements greater than three to the left are one as well and the elements that are less than three to the left are to the right are one which is just one and then the number of elements that are greater than uh three to the right is one as well so this is what the area would look like just for element three so we have to do this for each and every element in uh the given array so we have this and we'd say uh hey so if rating of i is greater than reading of j waiting of j uh what we would do is if i uh is greater than j you're asking and then it is greater than so you would say true a one and zero and one and then you would just do the same for right as well so if the rating of j is greater than reading rating of i and then uh and we do know that uh j is greater than i then what you would do is so it'd be one and zero and you would increment the white okay and after the for loop is done you would add the result so you would say left of zero multiplied by right of one so it's saying all of the elements that are less than a particular element multiply that by the number of elements that we have to the right that are greater than the current element so that would form uh this kind of a team right here that we see and then for this kind of a team which is uh decreasing he would do exactly the opposite so that would be a lot of left of zero multiplied by the right of one uh sorry yeah so after the for loop is done you would just return the result let's quickly compile this and see if it's okay the first test case passes or the test case pass as well so this question uh it's a little tricky and to understand this and visual it's better if you visualize it and try to understand it um understand the solution that way but if you have any questions about this solution please let me know in the comments below uh let's quickly talk about the time and the space complexity of the solution this time complexity of the solution is n square because of the two for loops that we have right here the space complexity is of one even though we're initializing uh two arrays they're relatively smaller in size and it doesn't grow um in size and that's the reason why we have often space complexity um so that's the solution as i said if you have any questions about the solution please let me know in the comments below if there are any other problems that you'd like me to solve please let me know in the comments below as well and don't forget to like share and subscribe i'll see you all in the next video peace
Count Number of Teams
minimum-time-visiting-all-points
There are `n` soldiers standing in a line. Each soldier is assigned a **unique** `rating` value. You have to form a team of 3 soldiers amongst them under the following rules: * Choose 3 soldiers with index (`i`, `j`, `k`) with rating (`rating[i]`, `rating[j]`, `rating[k]`). * A team is valid if: (`rating[i] < rating[j] < rating[k]`) or (`rating[i] > rating[j] > rating[k]`) where (`0 <= i < j < k < n`). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). **Example 1:** **Input:** rating = \[2,5,3,4,1\] **Output:** 3 **Explanation:** We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). **Example 2:** **Input:** rating = \[2,1,3\] **Output:** 0 **Explanation:** We can't form any team given the conditions. **Example 3:** **Input:** rating = \[1,2,3,4\] **Output:** 4 **Constraints:** * `n == rating.length` * `3 <= n <= 1000` * `1 <= rating[i] <= 105` * All the integers in `rating` are **unique**. In one second, you can either: - Move vertically by one unit, - Move horizontally by one unit, or - Move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in one second). You have to visit the points in the same order as they appear in the array. You are allowed to pass through points, but they do not count as visited unless you stop on them.
To walk from point A to point B there will be an optimal strategy to walk ? Advance in diagonal as possible then after that go in straight line. Repeat the process until visiting all the points.
Array,Math,Geometry
Easy
null
35
hey everybody this is larry this is me doing the co daily challenge number um day 26 happy thanksgiving sorry i'm like a little bit off uh happy thanksgiving doing day 26 of the november league day challenge hit the like button hit the subscriber and join me on discord let me know what you think about today's problem uh search insert position given assorted a way that return index of the target is found and now we turn the index where it would be if it was inserted in order uh okay um i just wanted to see if there was a duplicate thing but this is literally um you know in different languages decided lower bandwidth binary search or whatever so definitely you could do something like uh bisect that bisect left nums and target and that should actually be enough because that's literally the definition of bisect left and maybe even lower bound and stuff like that in different languages um yeah i mean i don't know that there's anything that much to it uh let's run it real quick just to make sure but um but today uh today i'm uh yeah well we'll just write out the binary side it's not that hard so yeah so n is equal to length of nums um so we have the left is equal to zero is equal to n minus one how do i choose these bounds well these i the way that i like to do is choose to be uh left right inclusive and what that means is that i can write my loop this way because if they're inclusive that means that when they are the same number we have one number in the range and thus that is our answer um an admit is just equal to let left let's write over two um okay so if num submit let's see what do we want it to be uh if nums if the number is and actually you can write this in any way you want because there's actually a couple of variations you can write this um so how you think about this really um like whichever like we how we fill out the rest of this depends on how you want to ask it right because you can ask just like you can have it here you could have it without the eco you could have it here you can have it there like all this of course will give a slightly different variation so it doesn't really matter which one so let's just say we want to do it this way um so if it's equal if it's bigger then what does that mean if the number is bigger right or you go to if the number is equal bigger than or you go two that means that the bigger half is going to be thrown away so that means that mid is equal to oh sorry whoops right is equal to mid because that means that we're forward right plus one and all these other numbers right uh else uh oops else uh we want it else num submit cannot be targeted so the mid is not the answer and then we have left is equal to mid plus one right um i might have messed up here to be honest hang on because i think here um when i usually when i do search i usually search something in the array but it might be that we have to insert after the last element and therefore this is actually n uh n so i actually spoke too soon earlier we'll see because there's a example here that should give us the wrong answer that's the case so yeah so confirming our um our uh situation so then we change that um because this we want if the number is bigger than the biggest number we want it to be n right and you can add an if statement if you like but that's how i want to think about it um okay so let's do give it a submit i just want to put uh the one element thing first just in case out there is a one element thing but uh let's do the other one where uh it's bigger than it okay so it looks good let's give it a submit apparently i did it um 605 about a year and a half ago i did that time i just went by actually oh i actually did write at that time too um that seems like i would still shake you but on this one on the if statement um they're not that big of a deal but anyway uh but yeah this is oops this is like um end time because we're doing a binary search on the n and that's pretty much it over one space obviously maybe but yeah um that's all i have for this one happy thanksgiving again have a long good weekend have a long weekend have a good long weekend i don't know if not just have a happy friday as well uh stay good stay healthy to good mental health and take care bye
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
191
hey everyone today we are going to solve the question number one bits okay so this question is very simple so let me explain with my solution code if you understand this you can solve this question so we have a constraint saying the input must be a binary string of ring 32 so we Loop 32 times at most and in the loop um look at this if statement so what is this part so uh in the loop we perform right bit shift so this means um we shift a bit I times to right so for example let's say our current number is 11 and we shift to the right just one time so in that case so 11 should be like Z One Z one and uh we shift uh to the right one time so that should be 1 Z 1 and uh we put Z into like a left space so 0 1 so this is 11 so this is a five so although um it's unrelated to the problem but the Performing right shift by one bit result in the value being H like from 11 to five and uh by two bits um result in the value being quoted so next should be like a one z0 0 so this means two right okay next so let me explain why we execute bit TSE and one so first of all look at this so I put o r and x o as a reference so regarding a bitwise and so we will get one as a result only when both inputs are one so otherwise um we get zero so we use this logic okay so let me explain why we execute bit twice and one so first of all look at this so I put o and x o as a reference so regarding a bitwise and so we will get one as a result only when both inputs are one otherwise zero we will get zero so we use this logic so bitwise and one means uh so0 0 one so um in the most right bit so we will get one so other um bit position is all zero so we can say except the rightmost bit um there's no way we get one as a result so because of we calculate result of so right shift and one so let me show you how we calculate okay so let's see one by one so first of all we iterate through 32 times so first value of I is zero right so in that case we don't shift to the right so we use input number itself so let's say input is like this so 0 1 and uh we calculate bit twice and operation and uh um we use one so that means 0 z one so this is input two so we calculate so one by one so first bit is one right one and one so one and one is one right but uh look at the uh other position so we have all zero right in input two so that means um we result should be all zero so 0 Z one that means one so in that case uh this uh if statement is true so that's why add plus one to result variable so now result is one and then move next so I value is one so we shift to the right one times so this is a original input number and then if we move to right one times we will get 0 z0 1 0 1 right and as I explained earlier we put zero into the left space so calculate this number and one so result should be so first bit is one and uh other than that all Zer right but uh we get one so um in the case that is true case so add one to result variable two and then move next so we do the same thing we shift twice um to the right so we will get one Z right and so one Z and 0 one should be all Z right so Z and one is zero and one and Z is zero and z and Z is zero so all zero so that means zero it's a false case so we don't update the result variable and then uh when I is three so we will get so 0 Z one and calculate um and one so one and one is one right so that's why we add plus one to result variable and then all we have to do is just return this three so original input is so has three ones right one two three so that's why uh this result is correct yeah so that is a basic idea to solve this question so without being said let's get into the code okay so let's write the code first of all ini result variable with zero and start looping so for I in range and uh we it 32 times and then if and so write shift and I bit Twi and one so if this is true so plus one two result variable and that's it so after that return less yeah so let me submit it yeah looks good and the time complexity of this soltion should be order of one so because we tell through 32 times so that is a order of 32 and we simplify order of 32 which is 01 and the space complexity is 01 so we don't use extra data structure just simple variable yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **Constraints:** * The input must be a **binary string** of length `32`. **Follow up:** If this function is called many times, how would you optimize it?
null
Bit Manipulation
Easy
190,231,338,401,461,693,767
1,184
hi what's up everybody and this is fisher cover here today we're going through a little problem 1184 it's called distance between bus stops and labeled as easy but I thought it's very interesting question okay before we dive into you the question please do me a favor and hit the like button that's going to help a lot with the YouTube algorithm to help spread this video and also don't hesitate to subscribe to our channel which is very dedicated to provide good LICO tutorials to help software engineers to prepare for coding interviews and land and great dream fan companies that's it with that said let's dive into this problem the problem goes like this a bus has n stops numbered from 0 to n minus 1 they form a circle look at this example it has a circle it's kind of a rectangle rectangular but that's funny makoy circle we know the distance between all pairs of neighboring stops where distance I is the distance between the stops numbered I and I plus 1 modular in what does that mean is that looking at this example visit bus stop zero this bus stop 1 this is bus stop - this is bus stop 3 the is bus stop - this is bus stop 3 the is bus stop - this is bus stop 3 the distance which is given denoted as an array and indeed array is showing as the distance between these two bus stops so from bestop zero to bus stop 1 but the distance is 1 from bus stop 1 - bus stop distance is 1 from bus stop 1 - bus stop distance is 1 from bus stop 1 - bus stop - the distance is 2 that's what it means - the distance is 2 that's what it means - the distance is 2 that's what it means the bus goes along both directions which means clockwise and huncle counterclockwise which means it can't go from 0 1 2 to 3 and also it can't go from 0 to 3 directly and then 3 to 2 to 1 to 0 that's what it means and the problem the question is asking us to return the shortest distance between a given start and destined and stops let's walk through this example distance is one two three four that's added as the site of this rectangular or this circle as the problem describes it is one two three four here and the stat bus stop is zero which starts from here and destination is one there are two routes to get to from point from bestop zero to pass top one which is either you go clockwise which is from zero to one directly and the distance is one or the other ways then you start from zero go to three first and then to two then two one counterclockwise the distance by going this round is four plus three plus two that is nine so it's asking us to return the shortest distance so one versus nine so the minimum is 1 so we're going to return 1 right the same goes for the second example the distance is given the same distance the simple stop the center in the same cycle the same circle and the status and zero and destination isn't too there are two ways clockwise and counter clockwise so come clockwise is going to be one plus two is three the counter clockwise 4 plus 3 is 7 so 3 or 7 min minus 3 it's best way marked as in red example 3 it's still the same circle 1 2 3 but start and stop destination changed again it's from 0 to 3 we if we go clockwise is going to be a 1 plus 2 Plus 3 is going to be 6 however if we go counterclockwise is going to be from 0 to 3 directly which is fallen the minimum of 4 &amp; 6 is 4 so in this case minimum of 4 &amp; 6 is 4 so in this case minimum of 4 &amp; 6 is 4 so in this case when we return for very interesting question and very straightforward that's what I feel and so the solution is going to be we're going to go basically we're going to count to calculate the distance for two routes and the minimum of the two that's it very straight for there is no tricking here but then it boys down to how do we calculate the two rounds the first round is the clock wise round is very straight flow we just start from the index from zero from the start up until destination we sum all of them up right that's it if you can see the distance for one how do we get one we start from index 0 that's where my status and reached destination but not hit destination we go up to destination that means less than this destination index that's it right the same goes for example to start from index 0 and then we go up to you index - but we don't hit we go up to you index - but we don't hit we go up to you index - but we don't hit it that means we sent the 1 and 0 which we get 3 the same goes for this from 0 to 3 we start from index 0 up to index 3 but we don't hit we don't end up index 3 that means 1 2 3 we add up we get 6 that's how we calculate the clockwise route we just start from the start index and go up to the destination index that's it and that's 4 that's the algorithm of how to calculate the clockwise route distance then we come down to how do we calculate the counterclockwise around distance what's to use these three examples to go through this still very straightforward but it takes a little bit check destination here is one and the destination here is one so we'll go well stand from index and one right well stand from index and one and then we'll go all the way until the end of the bus stop which is at index 3 was some all of them up right 2 3 &amp; 4 we sum all of them up right 2 3 &amp; 4 we sum all of them up right 2 3 &amp; 4 we sum all of them up and then we'll have to go back to index 0 but we don't hit it because this one is inexorable so we'll just ignore it that means we get the Sun to 9:00 for example one a we get the Sun to 9:00 for example one a we get the Sun to 9:00 for example one a more clear example is example two if we how do we calculate and compute counterclockwise route for example two is that here is the start and here is the destination we go from we start from start this way so destination is two let's look at index 2 0 1 2 is 3 right so 3 we go from 3 until the end of the array until the end of the bus stop so we add a 3 &amp; 4 we get 7 and then so we add a 3 &amp; 4 we get 7 and then so we add a 3 &amp; 4 we get 7 and then start index is 0 so we'll go all the way from the end of the array to the beginning of the rate but we don't hit it right then we get the count in the counterclockwise route distance which is salmon this is a the same goes by for the third example which is very straight forward as well and another thing to note is that one of the constraints it says start and test and destination these two indices both greater than 0 greater than or equal to zero but smaller than in it doesn't say that the relationship between start and destination that doesn't necessarily mean it could be it doesn't necessarily mean it's smaller than destination it could be bigger right which means destination is 0 and start is 3 it's totally possible so how do we count on dealing with that case very simple we're just swap well just to do the comparison in the very beginning of our algorithm and make us wha happen so we always make sure that is smaller than destination then our algorithm should work perfectly that's the algorithm now let's start I mean unicode this is the java api signature i hope all of that makes sense to you if it isn't let's look the code then you will make more sense hopefully in start let's do you if start is greater than destination let me copy this word is too long I don't want to make any typos in start and then testing with just a scientist emission so what we're doing this for loop is were swap start and destination if status greater than n destination right and then we'll have one way we just named it as one way to make the variable name shorter to save some typing time and it's this is going to denote the counterclockwise route distance and then as I just said how do we calculate man it's very straightforward just start from the standing legs go all the way up to destination and add all of them up which is going to give us the clockwise route distance that's it right if you are still unclear what I'm talking about let's go through this example game so start to destination 0 to 1 index 0 to 1 that means 0 that's it in this case the sum for the route distance for clockwise round distance is just 1 I said the second one is we're just quite other way which is standing for counterclockwise around distance here we'll have to follow 2 to calculate this but the time complexity is still will win because it's non that state will start from so counterclockwise let's take a look here counterclockwise which is that from destination here we go this way from start go this week all the way until here that means we will start from destination go until all the way until the end of this array they just said add all of them up distance that's going to give us the rest of this the Sun the some of the rest of the elements of the distance but still if the starting point is not a zero say if it's an one or two then we will need to add the beginning part which will start from zero and then we go all the way up to start in this case in this context this style is basically equals is equivalent to the destination in the clockwise context all of them gain as well that's it that's how we computed the counterclockwise around distance after that we'll just to retain the minimum of the two that's it now let's submit and see all right it's accepted 100% faster in terms of runtime accepted 100% faster in terms of runtime accepted 100% faster in terms of runtime and also 100% better and also 100% better and also 100% better one only present better in terms of memory usage this is very straightforward question but you just need to continue understand how the problem describes how the problem is described and how to really map all of the description into your code that's one of the core abilities or capabilities the coding and amuse and designed to engage candidates well if you like this video please do me a favor and hit the like button that's going to help along with the YouTube algorithm and don't forget to subscribe our channel which is a great resource for preparing new code in amuse and to for as the interviews that's going to be quick results if you have any comments questions please do me a favor and leave any comments questions feedback concern is down in the description below I really appreciate it I'll see you guys in the next video
Distance Between Bus Stops
car-pooling
A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given `start` and `destination` stops. **Example 1:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 1 **Output:** 1 **Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1. **Example 2:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 2 **Output:** 3 **Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3. **Example 3:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 3 **Output:** 4 **Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4. **Constraints:** * `1 <= n <= 10^4` * `distance.length == n` * `0 <= start, destination < n` * `0 <= distance[i] <= 10^4`
Sort the pickup and dropoff events by location, then process them in order.
Array,Sorting,Heap (Priority Queue),Simulation,Prefix Sum
Medium
253
128
hi everyone today solid quick question called longest consecutive sequence so given sort of intuition nouns want to change the length or longest consecutive element sequence and we must show the problem in one time which means it should be one pass okay now let's look example here so example one we're starting the one that we had two there was three and there were four and these are both consecutive integers right however when multiple 4 to 100 1.4 and however when multiple 4 to 100 1.4 and however when multiple 4 to 100 1.4 and 100 knots exactly individuals and also 100 and 200 unknown consecutive uterus therefore the longest consecutive sequence is one two three four and the length should be four okay now let's check example two here for example two we're starting at zero to eight right and you see here we have two zero means which means one zero it duplicates if that case we have to skip the duplicates because a double zero even you have one hundred zero in calculating longest consecutive sequence they are equivalent to one zero we are starting at the other way to eight and the length of longest conservative sequence should be nine right all right now let's think about how to solve this problem so actually in the problem we can use a combination between a sorting and sliding window and let me write it here okay let me write down here so first thing i should set the current lens the maximum length because it's a sliding window project and now they want to sort the rate from small to large once totally you want to traversary right and where traversing array the fundamental thing is to consider and to skip the duplicate and once skip the duplicates we have ensured okay it's already sorted from smallest to largest and then no duplicate they want to check if there's consecutive numbers are considered integers well for example we have one followed by two that's this means it's consent to integers you want to update the currentness of by adding this by one because we are gradually us expanding the current window right and after that we want to check okay if that is not consecutive they want to first update the maximum length which is maximizing the current length and maximum length and they want to reset the current length to 1 indicating we are studying uh adds a new sequence okay now let's use example one to help illustrate some algorithm so you see the first scene to initialize current length and maximum length are equal to uh one right so let me write down here so currently cl is one here the maximum length uh is ml is one okay now the second thing is to sort array we'll sort this array and cross it out by starting at one then we'll have two plus three we have uh four there are one hundred two hundred okay we just write it out here okay so the second step you finish now for the second step the next thing to skip duplicates double check is that duplicates in this array obviously no duplicates right so this step uh we don't need to do that just pass this step now things is that the next thing choose uh sync is that consent to introduce so let me use different columns here let's starting at uh here right and then we'll move to this number i want this number we want to check using number exact integer with previous number obviously since one plus one equals two uh these two integers are consecutive and therefore want to add the currents by one so one plus one and it should be true right so just write it down across it out and update it with true okay now we want to move the integer further so our pointer is moved to here i don't to check okay is this number consecutive with previous number obviously between two plus one is three these are consecutive integers you want to uh add current nets or further by one so two plus one and this one should be three change it here and it will do the same thing multiple four uh three and four are also consecutive integers right so add plus three by one negative four here okay and then we'll move uh four to one hundred i will check either before and one hundred uh because consent two at an individual is not right if that case want to first update the maximum length uh which is the maximum between the current and the maximum ends to update the max balance at four let's write it out here at four and then we reset the current to one and after that we moved uh this one to here right and found okay is 100 200 consecutive obviously not so we just keep it these uh since current length is a once before and there's no need to update coordinates so all these steps are finished here are because of our traversing let's read the entire array okay so finally we want to return oh let me use a different color here we want to return the maximum length which is a maximum between the final current length and the final maximum length and we see the maximum between this one and this four right so it should be four so we just returned resulted for an official explanation let's dive into the coding part okay so let me write the journal framework and can solve it easily and with less mistakes okay the first thing to consider in this array question is that if we get an empty array is that the case you get empty array then longest consecutive element sequence length i should be zero right okay now next thing since sliding window approach we need a current lens and also a max finance which are output initializes one and also one the lens array at l okay now next thing distorted array from value smallest so that's called this sorting function bison and if they want traverse entirely right you must increase okay from one to l the first thing would you consider the duplicates so let me switch it out here to balance okay now uh the next thing you could say okay is there two numbers consented if the consent you don't want to add the current one if only it's not consecutive you want to first update the main one is and send to reset currentness to one okay now physically comments let's write the reticle if numbers i equals to another segment one this means is duplicates so we just continue to next integer okay now if numbers i uh equals numbers i and so one plus one is exactly integer so we just add coordinates otherwise it's not consecutive i don't want to first update some exponents which is the maximum between uh maximum length and the current nets and they want to reset current as well if i return the max millions a maximum between maximum has coordinates and it should be done now estimate the cost works okay you see the time capacity member usage of this solution quite efficient right and overall i think the coding part is easy to understand if you like this video or please subscribe to my channel and i see you next time
Longest Consecutive Sequence
longest-consecutive-sequence
Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ You must write an algorithm that runs in `O(n)` time. **Example 1:** **Input:** nums = \[100,4,200,1,3,2\] **Output:** 4 **Explanation:** The longest consecutive elements sequence is `[1, 2, 3, 4]`. Therefore its length is 4. **Example 2:** **Input:** nums = \[0,3,7,2,5,8,4,6,0,1\] **Output:** 9 **Constraints:** * `0 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
null
Array,Hash Table,Union Find
Medium
298,2278
228
Hello everyone welcome back to my channel once again so here we are going to talk about today's daily problems of late code NDA question from hair code easy problem whose name is Summary Rangers so easy problem is okay so the question what did you say that you have Sorted Unique Wait Right Pay attention here, some thing is bold highlighted, so you need to pay attention to this thing, there is software and unique wait is main, all the integers, whatever errors there are, they all have become unique, will be different and sorted is also in a range. Defined Prince, what do we do that if we are A and B, if we are talking about the range, then the number starting from A is okay, till that, every number which is there will be present, okay, all the numbers which are natural numbers, all of them will come back, is this? When to withdraw, it is okay, the return you have to make should be smallest and should be sorted. The list of friends should be of the range in this manner. The list should be of the number exactly that D number. So what is being said here in this manner is that you Whatever range is to be provided, it is okay to provide the range by doing this, right, so you find out the range of this method, what will happen with this, Sir, it will be arranged, it should be done exactly, now what can you do for this type of ranges. Look at each one, now as we have the error given right here, we take zero one, four five, seven, now what we can do is that if there is only one, then we only take zero, okay tell me, this will not be wrong, right? If we remove the word smallest and keep sorted first, it is fine or remove sorted also, you can randomize it, dog will also be correct, if you calculate the range in this way, then it will be already sorted, so it does not have much impact here. But this is the smallest one, it has an impact, look at the total in this, in the list that you have returned, the total number of elements in it is 6, the total range is 6, you told it, what do I do now, I change it a little, zero then one again. I will do it, you will do it again, okay, if there is a hole in it, then it is not a story, it is smaller in comparison to what it is, if it is possible than this, if there is a range which would be smaller than this, then this will also not be the answer, how are these events happening? If not, then the one which will be the smallest, which will provide the smallest range, which will be the smallest list, that will be your answer. Yes, if we are talking about smallest, then you should include the maximum number of elements in each range in the range. Is with life condition, so here what is said in it should be done exactly, so you cannot do it as if you want, you will eat it or it is okay. 012 Its final answer, first I write zero, you are a range, after that your intake. This answer must have become final, okay, here it is three and this is yours, what is the problem, then you saw it, zero one, three, four, five, but what is said in it exactly what should happen, what is happening? Okay, so if any of its elements is not present in it or if any of its elements is not present in any range, then we will ignore such list here and will make it white, it will not be a part of our answer. The logic of the question is going to be that. We have discussed that this is what overlap is, the condition is not allowed here and any interior All you have to do is put one and you and three, so in this way you get returned as a vector in the form of string of vector. So now see exactly what is happening, how do we understand that there is zero here. You, a range is being formed, okay posture, today we have no lead support, we do not have anything right now, so we countered like this, we started an element, our element which is here is fine, it will end, it will move forward, that is a different thing, so we What did you understand like a thread, okay, we understood a thread, its first and you I kept that A, this is defining the range, this is your range, after the end of one range, on the second day, it is as if you are getting the range, how far will it go, where will it go now? We will go till where we have to go, we will keep B. Now here it is possible that the condition which is being created with the next element, the one with plus one, will not be created, so we will break here. In mains, our range has been defined, A and B and this We will be storing both the values. Now what do we have to do? So here we will compare the condition given by us that A and B are equal. Okay, if A and B are equal then we will just adjust A and change the vector. If A is not equal then B will be done in this way. This will be a complete string of your vector. Okay, now note that A is not equal to B, you can also do it in this way. We have taken account variable here which means range. How many number of elements are there in I kept it in the account and did it in this manner, we will see in the court, now one thing here which we discussed is that when I want to talk about smallest tense, then we have maximum number of elements in one region. If we want to be included in A, then we will start from A, okay, A is fixed, we are moving to B, so listen to Aaj Tak, our late proposal is going to Namsaf I, so what will happen if this is in this range. If it has to be included in then this number should be exactly equal. Just like I - 1 + 1 means just plus one of the previous element, I - 1 + 1 means just plus one of the previous element, I - 1 + 1 means just plus one of the previous element, this number should be then this current range which we are talking about starting from A, it will be included in the range. So here we will just do this, let's keep increasing for now, okay now our B will come here again and then it will change and become the current value and if it is no longer there then we will assign this A and B to our vector. After changing the string, it is okay, after changing the string, it is exactly right, then that part will be clear to you. We have tried to understand this question in a very easy and good way, let us see what is going to be your answer. I have kept it here because when I solved it, I noticed that Dum's Dot Length is up to 20, so this value is not surprising you much but that is why I said that starting from zero is fine. And for one, we will have to handle it because in this case we are understanding A and B separately, so you will not have a tap here, I had made this thing mine, I returned it, simple, after that our checking started, I started checking. Starting at A, I have placed the number zero counting our one. The number of element one has been added in this range. Okay now we are flooding ahead. The previous element is plus one. We set B to the current value and the counting is one flooding means. I have added this element in the current range, okay, so see what is the meaning of doing Abide, A is your first in point and B is your starting and ending in point, okay, I am setting it in this way if it is in the range. If it doesn't come, then a new range will start from here, but before starting the new range, we have to store the value and also the information of our previous range, we have to keep it, so I made a string tempo, if this is equal, you are one in mains one. This value must have come only on this side. Okay, this value must not have come in the range, so we have given it the proper format, we have changed the format and added it to the answer. Now what will happen, a new range has started from here, our counting has started. Changed one on the current number of elements and will continue to do the same thing from then on. So what will happen in it? Your counting, whatever will happen, will mean something or the other which will be a range which will not include you. The last one will be arranged. We will check it last. We will do it and we will add it here also and you have to simply return the answer, so this question was easy but I would say that it was a very good question, it was a good question in comparison, so let's end this video, in the rest of this video if anyone Doubt has gone back. If the dot has gone back in the question, then put it in the comment box below and it is given in the description box below the discord server. I will not speak about binary magic if it is a steel seat, but my entire blog has become a site here. We have already posted many blogs, so I would have posted this question also, but it is a very easy question and I have not seen many of its varieties, so if there is something like this, then I will post that here too. I am relieved that all the questions are on different concepts. If related, its link is in the description box below. Join and let me know. It's okay. See you in the next video. Play it bye.
Summary Ranges
summary-ranges
You are given a **sorted unique** integer array `nums`. A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive). Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`. Each range `[a,b]` in the list should be output as: * `"a->b "` if `a != b` * `"a "` if `a == b` **Example 1:** **Input:** nums = \[0,1,2,4,5,7\] **Output:** \[ "0->2 ", "4->5 ", "7 "\] **Explanation:** The ranges are: \[0,2\] --> "0->2 " \[4,5\] --> "4->5 " \[7,7\] --> "7 " **Example 2:** **Input:** nums = \[0,2,3,4,6,8,9\] **Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\] **Explanation:** The ranges are: \[0,0\] --> "0 " \[2,4\] --> "2->4 " \[6,6\] --> "6 " \[8,9\] --> "8->9 " **Constraints:** * `0 <= nums.length <= 20` * `-231 <= nums[i] <= 231 - 1` * All the values of `nums` are **unique**. * `nums` is sorted in ascending order.
null
Array
Easy
163,352
1,239
Maximum length of concated string's unique characters, so first Happy Diwali to all of you, vector is given string, okay, so what we have to do is, we have to make concated disting, okay, which candidate string has to be created by taking these strings which are inside this factor, so that the string I have included in it that the unique character of all the actors is fine, so if any other string is formed which will be a unique characteristic, then we have to retain it to the maximum possible length. Okay, let's see this example. Here I am given 'Hey', which means Here I am given 'Hey', which means Here I am given 'Hey', which means Doctor's. I have gone to UNI K U A. Okay, so which variety is possible if I have 2 spheres, I will tell you how to do it. Sir, I am getting this vector A. If I look at the first element, what should I do with the first one? Also, with what characters can I add so that I get the resulting string? Okay, so that I get the resulting string, what should be all the characters inside it? Unico, if I am taking these two strings, what will I get? C A R All Actors Suni Okay, so basically what I will do is, how many options does it have? The first string has three options. Okay, so if this is written R, then the netting is C is A. R is okay. Now C is R. Mani is okay till this point. Now when it will check after that, if I add it then it is possible, it will be possible only when I add it, then the length will basically increase but for me, it will be possible only when the characters which distinguish the result inside it are added and a concated string is formed. It is okay if there is no repeat of any character in it, but if I look carefully, it is C H R and if I am a candidate for ACP, then I will see it twice, then basically that will not be possible for me. Basically, what is the answer? Want friend, this is the maximum for now, so what is this case possible, that is, I cannot add this foot inside my system when I am taking R, okay when I will consider the arrow after adding it. To add, I cannot consider the next string which is C A T. Okay now if I can write what is next then basically this will not be possible because C is A R and okay if I add A R. After this, if I contribute after that, R will repeat twice, then this case is also not possible, okay, so basically, if I am doing R with C, then what is the maximum possible for me, 4, okay, CAG has it and which one? What other options are there? He checked with R that if I am adding R near Ch, otherwise if I add then what are the options required if I say C is near H? If I am adding ACD near Ch, that is possible. Okay, and if I have one more option from era, if I have one more option, how many I's, six's, how many zeros are there in this, okay, then what will be my maximum, six, then this should be my answer. Well, basically if I add this square, then my max pay possibility is six. Okay, now I have just started from where, basically I am adding A, this combination is possible with BF, this is the possible combination, this is basically so now I am DF, I will add this. Which 20 are possible from this, okay starting from R, which string can I add inside the string starting from R so that my result date is also of maximum length, this is possible when I started All the cases will be checked like this again, I will apply it again, if all the possible waste is coming out and the one which has maximum length, please return it, so I am showing it here basically, I have shown it completely here, okay, how do I drive, okay? So the code, we must have started, okay, I have to check that after adding, all the actors should be unique. I have to check this, so what am I doing for that? What am I doing for that? Clear the side, less is also there are always unique characters in the set, if multiple means what is the string on mere, let's say, what is the string on me, okay, if I add this, then how many values ​​will I get inside this. A will come inside how many values ​​will I get inside this. A will come inside how many values ​​will I get inside this. A will come inside once, all the unique letters will come, okay it will come like this and it will come like this, okay then what is the length of this set, within 1234566, if A is included inside all the characters and its length will be equal, what does the string mean in the set? The length will be equal, repeat here, the characters we have to return from there, how many possible indexes will I start from, so initially there is no index, the value is zero, okay, then I will start from zero index, let's see, now let me show you from where I will start from zero. I will run length given also battery will run till there ok what will I do what will be the initial value inside RAT for jitney string how much is the initial for interesting zero ok what will I do I will take Max Bheem I will call it again and will do it nearby Hey, I will pass, okay, and I will add it, meaning, basically, what am I doing here, I am continuing, what is the basic meaning of plus, what is the meaning of pressing the hosting, so right now initially MTS is okay, the value is A C H initial. I am doing zero value, okay and what special thing will I do here, I will go ahead and call the index, that is, for this, which options will be there for CHA, like I had shown you here in cricket, it is okay here, so this is it. What I am doing here is index one and passing it inside the bus okay so like here it will call remove function R so basically I am going to add C a chicken R Okay now what will it pass next time okay What is the value of I, how much will you pass? Hey, it will come again here, as I have shown you here, the same thing will work and I have shown you this by paying here, okay, then there will be a call again, yes, we will call, the value will be three. From there it will run till N - 1, then I will add RAD. run till N - 1, then I will add RAD. run till N - 1, then I will add RAD. After adding RAD, value the RAD, maximum, which means I will call again, okay, then I will pass next time Basically, what will happen here, if two workers are repeated. This condition will work, which false one is ok, then return is made zero, then again I will check if E-Ass is added to it, then again I will check if E-Ass is added to it, then again I will check if E-Ass is added to it, then again return is zero, if it is ok, then particular will come, for whom will the return come, for this, four returns will be ok. If so, I think this part will be clear, so if you drive like this then it will be completely clear to you, okay?
Maximum Length of a Concatenated String with Unique Characters
largest-1-bordered-square
You are given an array of strings `arr`. A string `s` is formed by the **concatenation** of a **subsequence** of `arr` that has **unique characters**. Return _the **maximum** possible length_ of `s`. A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. **Example 1:** **Input:** arr = \[ "un ", "iq ", "ue "\] **Output:** 4 **Explanation:** All the valid concatenations are: - " " - "un " - "iq " - "ue " - "uniq " ( "un " + "iq ") - "ique " ( "iq " + "ue ") Maximum length is 4. **Example 2:** **Input:** arr = \[ "cha ", "r ", "act ", "ers "\] **Output:** 6 **Explanation:** Possible longest valid concatenations are "chaers " ( "cha " + "ers ") and "acters " ( "act " + "ers "). **Example 3:** **Input:** arr = \[ "abcdefghijklmnopqrstuvwxyz "\] **Output:** 26 **Explanation:** The only string in arr has all 26 characters. **Constraints:** * `1 <= arr.length <= 16` * `1 <= arr[i].length <= 26` * `arr[i]` contains only lowercase English letters.
For each square, know how many ones are up, left, down, and right of this square. You can find it in O(N^2) using dynamic programming. Now for each square ( O(N^3) ), we can evaluate whether that square is 1-bordered in O(1).
Array,Dynamic Programming,Matrix
Medium
null
424
Hello friends today I'm going to solve liquid problem number 424 longest repeating character replacement so here we are given a string s which consists of uppercase English characters and an integer K and we are allowed to change any character of the string to another character and the maximum number of times we could perform this operation is K and while performing this operation our goal is to return the length of the longest substring that contains the same letter so for example here uh we have this string and our value of K is equals to 2 in this case which means that I can change maximum of two characters from this string to get the longest substring which has the same characters so what characters do you think we need to change in order to get the longest substring well of course we have an A here and then we have a b so if I change this B to an a then I'll get an A which we already have an A and then an A in the third position right and then I have a b here now right now I already changed a so now the possible the number of way um are operations that I could perform is now changed to one so I can only change one character now so if I change B to a here then the total number of um the length here becomes equals to four uh the length of the longest substring because now I have a and an A so my length is equals to four so this becomes my answer here now in this case in case of this string and my value of K is equals to 1 which means that I can only change one character from this whole string um and the resulting I should return the longest substring so I have a two a here so uh I'm looking for something which would make this string the substring long is right so I have two a's here and a here so in intuitively we would change this B to a right and this will give me a character substring of length for with the same characters now what if in case um I didn't change this B because I have a b and I have two B's here right so I could still change this A to B and I'll still get a length for right so here also I get got length four here also I got a length four and one more thing is that I could still perform this operation in uh different way that is if I change this P here now the maximum length of the substring right now is only equals to three so this is not the operation that we want to perform at this index we want to perform the operation such that we get the largest longest substring with the same characters which is here in this case is by replacing this character by a or by replacing a by B so now that we know what our result should be uh how can we actually perform these uh in an actual like coding so how could we actually solve this um so we could solve this by using sliding window operation so we will be um starting with the sliding window of length one so basically I will choose a left pointer and a right point and both of them will initially be pointing at index 0 so this my left pointer and right pointer both of them are here currently and then um the frequency because as you could see here I have we also kept in mind the frequency right at when we were um when we use this window of length for we since the frequency of a here was equals to 4 we choose chose not to change a but to change B right so that is what we are going to do we are going to keep track of the frequency of the characters within the window so right now my window is of length one so I'll keep track of the frequency of the character uh within the window which is a which has which is equals to one and um since um the length of my string and um and the frequency is equal I actually do not need to change anything here now when I increase my Windows size now I have a and another character which is B both of them have a frequency one and here my right pointer is pointing here so which character should I change uh to get is this the longest substring so far um with same characters no uh the longest substring uh would be if both of them were of same characters right so I could pick any one of those because both of them have the same frequency so um I change one of these and then at that point um my maximum length would be then if I change B to a then my maximum blend will be my uh length will be equals to two right two here in this case and then again actually not actually changing but keeping in mind the change now again I increase my slider here the frequency of a is equals to 2 now and B is still equals to 1 and how many changes can I make within these windows where I can make two changes right and since P has the least frequency it has the maximum frequency so I won't be changing a but I will be changing all the other characters within this window so the only one character within this window is it B which has a frequency of one and um I am allowed I am able to change character B to 1 because K is equals to 2 and the frequency of B is 1 Which is less than two so I'm allowed to change um in this case the length maximum length is equals to 3 here now again um I increment my counter so now my uh sorry I increment I expand my slider and now my slider is of length four and then here the length of B is equals to two and since both of them have the same frequency I can choose to change one of them so I choose to change B and um the character the number of changes in B that I need to make is equals to 2 which is equals to K right so since both of them are still equal that is I could perform the changes these two changes change them to a and then I'll get my maximum blend so this will be the answer that is equals to four so I'll return the length of the maximum the length the maximum length of the substring with the same characters here now let's see in this case here how could we solve for this string which is same so I start from my first index left and right so my sliding window is a flat zero and now right now my maximum length is equals to um zero now when I am at this point uh this is the maximum so far the maximum length of the substring right so this value becomes equals to one now then I increment my sliding window expand my sliding window which consists of two characters both of them are same characters so both of them are a which is the frequency of two I do not need to change anything because they are the same so now the length is um equals to two now I again increment my sliding window now it consists of BB has a frequency of one so two is here the max with the maximum number of frequency right so I just choose to change B and since B and the number of changes that I need to make for B is equals to 1 Which is less than or equals to the value of K so that is possible so I increment my counter again now I encounter a and then the frequency of a is equals to three which is again the maximum so I again change I can still in within this window I can I'm still able to make one changes so next I next time I increment my um sliding window expand my sliding window now the frequency of B is equals to 2 the frequency of a is still equals to 3 and b close to and we have the value of k equals to 1 right but here in order to make all of the um characters in this window same I need to um change either one of these right and the best choice is to change the one with the list frequencies um so when I choose to change B the there are two characters for B the frequency of B is 2 which is actually greater than K so I cannot actually make these changes so now what I do is I slide my uh I slide my window so now my window becomes uh a b so my um so here in this case my left pointer was here and my right pointer was here but now my window has slided and now my left pointer is here and my right pointer is here so this becomes my new window and here uh the frequency of a is equals to 2 and frequency of B is equals to 3 so now I choose to change a but then again the frequency of a is equals to 2 which is greater than case which is so I'm not allowed that's not possible so I then again slide my window so now my next window is uh from here to here so this becomes my new window and again I choose the frequency of Base 3 and a is two and still here I could not make any changes right so what will my resulting answer be my resulting answer will actually be right minus left the right pointer minus the left pointer because um when we found the maximum uh length um that was when um that was at this point right and then we incremented our uh we expanded our sliding window by one and that was when um our frequency when um we were not able to make any more changes uh to the window so we just keep sliding we didn't increment but we just lit it's like kept sliding our window so uh so this is this will be our answer here now let's dive into the code so what we need to do is we need a sliding window so we need a left pointer and a right pointer both initially pointing to zero and then we need a frequency mapper right so I'm going to use here a dictionary and now for from for the length we are gonna start not for I so we are going to start from right equals to zero right is less than as the length and right plus because what we are doing here is every time I am expanding my window right which is that I'm incrementing the value of my right pointer each time I'm only incrementing my value of left pointer when um I am not able to make changes when the value of K is less than the number of changes that I should make in the substring in the window to make it the longest substring so I am always incrementing R so that is what I'm doing here I am always incrementing R starting from 0 I always increment R but I'm only doing it after performing some operations so since now my left and right pointer is here I also need some to add these to my dictionary add all the characters within the window to my dictionary the frequency of these characters so right now um my frequency so this will be R which it'll be equals to so the frequency would be plus one if it already exists if not only one and then I check the bag for the value of K so I checked for the value of K if um okay so I also need the maximum count because I'm only changing those values which are different uh from the max count I won't be changing the max count at all only those characters which are different so max I'll let Max count equals to zero and then Max down we've got some met Max count oops count or the value of this dictionary and then if the land plant which is left minus right Plus minus right minus left plus one minus Max count which gives the number of characters that we need to change in this string if this is greater than K which is the maximum number of characters we could change in the string then we are gonna increment our left pointer but also here again while incrementing our left pointer we also need to uh we are actually removing an element from our sliding window right so we also need to update our dictionary because we only keep the frequency of those characters which are in the sliding windows so now dictionary I'm gonna update my dictionary and this will be reduced by one and then finally return right minus left so what I'm doing is I'm creating a left pointer and right pointer for my sliding window and we start from zero index and then we keep on increasing the expanding the sliding window and while we are expanding we are performing all these operations we keep track of the frequency within the sliding window frequency of all the characters and then um every time we calculate this maximum count so the max count is the number of frequencies of the characters um which have the maximum number of frequency within the sliding window so if that characters has the maximum number of frequency which means that we are not changing that character we are changing all the other characters within that window and this is the number of characters that will we need to change um so this is actually the length of the sliding window and we are subtracting the characters which we do not I want to change so length minus the characters we do not need to change equals to the characters we need to change and if this is greater than the characters we can change then actually we what are we doing is we are sliding our window so we um uh we are actually removing the left removing a character from our left and when we are removing uh we need to update the frequency so I'm we are reducing the frequency by one and then um changing the left pointer and then um while sliding I'm also we change the lift pointer we also change the right pointer and the maximum will be the right minus left because since we are here aiming to return uh length of the longest substring so um we choose only to increase the window so that once we have found the max we always are looking for a window if greater than the max value and um this will give us the window let's run our code and see if the result okay so something is wrong here and what is that okay so what I did here is I defined another R here which is not because of which the value of R here I'm getting is always equals to zero so that is what is giving me problem great so I have um let's submit this code now so the time complexity of this function is since we are going through for Loop once uh occurs through all this trillion uh to all the characters of this string so the time complexity is off and then um talking about the space complexity we are using a dictionary so the space complexity is also off and hope this solution was helpful thank you
Longest Repeating Character Replacement
longest-repeating-character-replacement
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times. Return _the length of the longest substring containing the same letter you can get after performing the above operations_. **Example 1:** **Input:** s = "ABAB ", k = 2 **Output:** 4 **Explanation:** Replace the two 'A's with two 'B's or vice versa. **Example 2:** **Input:** s = "AABABBA ", k = 1 **Output:** 4 **Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ". The substring "BBBB " has the longest repeating letters, which is 4. **Constraints:** * `1 <= s.length <= 105` * `s` consists of only uppercase English letters. * `0 <= k <= s.length`
null
Hash Table,String,Sliding Window
Medium
340,1046,2119,2134,2319
1,562
hi everyone it's albert here today let's solve the contest question find latest group of size m okay the question statement so given an array and its items are the permutation of numbers from 1 to n and n is the size of the array and we also have a binary string of size n that they are initially set of bits to zero so every element in the array means that uh the earned bit on in the binary string will be changed from zero to one so for example one the first element is three which means that the third bit in the binary string will be updated to one and in this binary string we will have a group of one and its length is 1. and in step 2 we will change the fifth bit from 0 to 1 and since these two ones in a binary string they are not con contiguous they are separated by zero so now we have a two group of one and their length are both one and except step three we will update the first bit to one and now the groups become three group one and their length are all one and at step four we will update the second bit to one but now we can see that there is one group of ones that the land is three and also one group of one island is one so now the groups become one and at the last step all the bit will be changed to one so group notes becomes a length of five of ones and the question also has another input of m which is the length of group of one and the question wants us to return what is the latest step at which there exists a group of ones that the length is exactly m so for example one the latest step that the groups has the group of land at the then equals to one is at step four and the intuition to solve this problem the algorithm is using an like a simplified version of union fine and the data structures we have to use are two arrays one is uh called the length at index the other one i call it the count of at length and let me show you what i mean by the code and my solution is inspired by the only code but i try to make the naming more explicit and easier to understand so first uh let's initialize the dent at index and the count of then arrays and the length index uh array its size has to be the length of array plus two and cut off length his size is land of array plus 1. and then we go through the arr array first is to get at each index gets its left neighbor's group of ones length and also its right neighbor uh the length of group of one and every time we will calculate what would be the new length of the group of one and then we update the length at index array at index minus left length and in the index plus right then or to the new length and finally we will update the count of length array at index level then he has to subtract 1 and add the index new then it has to add 1. so finally if we have m in the count of that array then we will update the result variable and you will be more clear to visualize this process in action so the real meaning of the array length at index is in a binary string at each step what is the length of the substring once at every index so for example at step one the third bit will be updated from zero to one so now we have one group of substring one which is at index three so we will update the length at index array the index three from zero to one and the meaning of count of length array is that its index is length of the substring once and the value in the array is how many groups do we have for each length so in this step we only have one of a substring one whose length is only one and since we have a substring one in the groups so we will update rest to one and next step update the fifth bit to one so groups now we have two substring of one so we update the length at index array at index five from zero to one and account of that now we have two groups of uh substring one and increment the rest by one now it becomes two and step three are pretty similar now we have uh then at index one 3 5 will be one and kind of land we have three groups of substring one okay and step four uh as you can see we will update the second bit to 1. so now the groups become a substring of 1 and a substring of 1. so basically a substring of then 3 and a substring of length 1. so what we need to do here at the index is that at index 2 which is like the second bit of the binary string now the length will become three we will also update the value of this left and right neighbor as well and to update the values we will calculate the new length which is the left length plus right length plus one and we use this new value to update the length index array okay and next is to update the count of length array since now we only have one substring one and one group of substring one so at index one you will become one at index three you will be updated from zero to one and the last step we will update the fourth bit to one so now uh the groups will only have the string of uh one so at the index length at index array we will update the fourth index value from zero to five and then we will update the count of that array now in the groups we don't have any substring of length uh that one but we have one group of substring whose length is five and if you notice here when we are updating the data and index will update the index 1 and index 5 at the same time and these are the left most and rightmost index of the current substring and the index between them they are not actually updated but it doesn't matter because we are not going to use this values anymore so this is a valid approach and to review so the algorithm behind this question is like a simplified version of a union find algorithm and the data structures we use here are two arrays is uh to use the length at index array and count of length array to keep track of how many groups of substring ones and their length to update the result and time complexity of this approach is linear time space is also linear and if you are using python i would highly recommend you to use the python debugger and the breakpoint function to keep track of what is happening every time in a for loop that would be easier to understand the process flow okay and that will be all for today i hope this video helped you to understand this question so if you like this video please give it a like and subscribe to my channel and i will see you in the next one
Find Latest Group of Size M
people-whose-list-of-favorite-companies-is-not-a-subset-of-another-list
Given an array `arr` that represents a permutation of numbers from `1` to `n`. You have a binary string of size `n` that initially has all its bits set to zero. At each step `i` (assuming both the binary string and `arr` are 1-indexed) from `1` to `n`, the bit at position `arr[i]` is set to `1`. You are also given an integer `m`. Find the latest step at which there exists a group of ones of length `m`. A group of ones is a contiguous substring of `1`'s such that it cannot be extended in either direction. Return _the latest step at which there exists a group of ones of length **exactly**_ `m`. _If no such group exists, return_ `-1`. **Example 1:** **Input:** arr = \[3,5,1,2,4\], m = 1 **Output:** 4 **Explanation:** Step 1: "00100 ", groups: \[ "1 "\] Step 2: "00101 ", groups: \[ "1 ", "1 "\] Step 3: "10101 ", groups: \[ "1 ", "1 ", "1 "\] Step 4: "11101 ", groups: \[ "111 ", "1 "\] Step 5: "11111 ", groups: \[ "11111 "\] The latest step at which there exists a group of size 1 is step 4. **Example 2:** **Input:** arr = \[3,1,5,4,2\], m = 2 **Output:** -1 **Explanation:** Step 1: "00100 ", groups: \[ "1 "\] Step 2: "10100 ", groups: \[ "1 ", "1 "\] Step 3: "10101 ", groups: \[ "1 ", "1 ", "1 "\] Step 4: "10111 ", groups: \[ "1 ", "111 "\] Step 5: "11111 ", groups: \[ "11111 "\] No group of size 2 exists during any step. **Constraints:** * `n == arr.length` * `1 <= m <= n <= 105` * `1 <= arr[i] <= n` * All integers in `arr` are **distinct**.
Use hashing to convert company names in numbers and then for each list check if this is a subset of any other list. In order to check if a list is a subset of another list, use two pointers technique to get a linear solution for this task. The total complexity will be O(n^2 * m) where n is the number of lists and m is the maximum number of elements in a list.
Array,Hash Table,String
Medium
null
1,352
welcome to my channel so in this video i'm going to go through this um uh specific question called product of the last k numbers and at the end of the video i'm going to go through the general steps we should follow in a real interview so let's get started before we start the real content for today i would really appreciate that if you can help subscribe this channel because it can help me to grow so thanks a lot let's resolve this problem implement the class product of numbers that support two messages add so the ad is going to add the number to the back of the current list of the number and get product it is going to return the product of the last k numbers in the current list and i can assume that always the current list has at least k numbers and at any time the product of any contiguous sequence of the numbers will fade into a in 32 without overflowing okay so let's take a look at this case we add a couple numbers and we get product of the last k numbers return that okay so let's see there are at most 4 000 up for okay forty thousand operations considering add in product get products so the number is between zero to one hundred and k is between one to forty k so the special thing is um if there is a there is zero uh i would say that could be so if we had zero that could be some special case um considering what is a general approach you're trying to implement using so currently um the thing i can think of is to use to store the prefix product and then um for to store the prefix product the add and the get product operation both going to be all of one so let's see how this piece of code is implemented so essentially we keep add index product map which is the prefix product and also the last zero index uh the last the index of the last zero which is pretty special and the count like how many uh numbers we have already added so here um we use big integer because there is some overflow stuff in the test case so i use big integer here uh so we initialize hash map and we put a zero one here um so count is equal so zero one means uh when there are zero numbers then the product we keep it as one intentionally uh which is for simple uh computation for get product so content is equal to zero there are zero numbers uh already so the last year index is minus one so essentially initially uh when we call the add we are going to plus one account because we add a new number into it and the last zero index is equal account if the current number is zero then we put if the number is zero then we just don't compute the prefix product with this number but instead we directly put the last prefix we have already computed into the last into the map otherwise if it's not zero then we put uh the count as the index which is the key and value is uh the previous prefix product times the current number so when we call the get product we just need to see so first of all we need to see whether the lassen zero index is after the count minus k so if the last k number included zero then we just directly return zero otherwise we will do a computation which is to get the prefix product of every number entail every number divided by uh the prefix product of uh all the numbers from the start to count minus k and then we are going to return the ink value because we are using the baking so uh that's pretty much it um so regardless of the api call for the big integer so the island and the get product is going to be all the one but for the big integer operation there could be some additional complexity so in a real interview i usually start to understand the problem um so don't jump into the coding part too quickly so that's a big red flag so you start understanding the problem and if there's anything unclear bring up the question and also think about smash cases and the next part is going to be about like think about the solution talk with the interior do some run times based analysis uh try to justify the efficiency and also at the same time you will need to get an agreement with your interviewer so after that you will need to do some coding work so for coding take care about the readability the correctness and uh don't be too slow and at the end also don't forget to do some testing because many people forget to do testing they just put the code there and they see it done but it's not done so you still need to do some testing to make sure about that piece of code is about so that's it for uh this uh coding question so if you have any questions about the solution or whatever feel free to leave some comments below if you like this video please help support this channel i'll see you next time thanks for watching
Product of the Last K Numbers
maximum-profit-in-job-scheduling
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. Implement the `ProductOfNumbers` class: * `ProductOfNumbers()` Initializes the object with an empty stream. * `void add(int num)` Appends the integer `num` to the stream. * `int getProduct(int k)` Returns the product of the last `k` numbers in the current list. You can assume that always the current list has at least `k` numbers. The test cases are generated so that, at any time, the product of any contiguous sequence of numbers will fit into a single 32-bit integer without overflowing. **Example:** **Input** \[ "ProductOfNumbers ", "add ", "add ", "add ", "add ", "add ", "getProduct ", "getProduct ", "getProduct ", "add ", "getProduct "\] \[\[\],\[3\],\[0\],\[2\],\[5\],\[4\],\[2\],\[3\],\[4\],\[8\],\[2\]\] **Output** \[null,null,null,null,null,null,20,40,0,null,32\] **Explanation** ProductOfNumbers productOfNumbers = new ProductOfNumbers(); productOfNumbers.add(3); // \[3\] productOfNumbers.add(0); // \[3,0\] productOfNumbers.add(2); // \[3,0,2\] productOfNumbers.add(5); // \[3,0,2,5\] productOfNumbers.add(4); // \[3,0,2,5,4\] productOfNumbers.getProduct(2); // return 20. The product of the last 2 numbers is 5 \* 4 = 20 productOfNumbers.getProduct(3); // return 40. The product of the last 3 numbers is 2 \* 5 \* 4 = 40 productOfNumbers.getProduct(4); // return 0. The product of the last 4 numbers is 0 \* 2 \* 5 \* 4 = 0 productOfNumbers.add(8); // \[3,0,2,5,4,8\] productOfNumbers.getProduct(2); // return 32. The product of the last 2 numbers is 4 \* 8 = 32 **Constraints:** * `0 <= num <= 100` * `1 <= k <= 4 * 104` * At most `4 * 104` calls will be made to `add` and `getProduct`. * The product of the stream at any point in time will fit in a **32-bit** integer.
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
Array,Binary Search,Dynamic Programming,Sorting
Hard
2118,2164
973
Jhaal Hello Everyone Welcome and Welcome Back to my Channel Today Were Going to Solve Na the Problem Is Cake This Point to Reject So in this Problem Will Be Given a Good Points Where Points of It Ads Index and Point Se Loan Rate Will Be For Paririt sweetness together sexual representatives point n K Point Quality Point To The Return From This Point Idea Give Winners To Retail Pack Case Close K People Is Point Hai To The Distance Between Two Points To Explain Your Kids And Distant Lands Which Can Calculate Between Two Point Se Zind Isko Mixing Unit And Answer In Hotel Taj Nagari Twink Hain To Is Machine 10 Cup Input If 2.3 120 Hain To Is Machine 10 Cup Input If 2.3 120 Hain To Is Machine 10 Cup Input If 2.3 120 Mintu Return The First Class Ninth K Project For This Point To Will Find The Distance Between One To Come Into And Origin Is This And Distance Between - To Come Origin Is This And Distance Between - To Come Origin Is This And Distance Between - To Come Into And Origin Is This Sui A Square Root Of At Welcome Village Sir 202 - You Come Into It's Moral Of The Story 202 - You Come Into It's Moral Of The Story 202 - You Come Into It's Moral Of The Story And Sciences - To Come Into Equal Winters And Sciences - To Come Into Equal Winters And Sciences - To Come Into Equal Winters Ne Twitter The Ke Point Like One Point Soane Iss Input Nau Let's Salute Sudarshan Ke 122 Ki Lavvanshi Edison Freedom Fighter Also a distance from last section - distance from last section - distance from last section - edifice youth minus one to square that anirudh life even in the question on the other hand giving proper examination this point which women from this is the distance between this point to 10 you will get active and railway road where you will also Give me one plus one day you will be a 209 learner how will approach in software to this problem a specific way I will be using s-cross definition s-cross definition s-cross definition noting that Android call with different matter with me to know which has greater distance of which left For things which women tourists can calculate distance between madurai and rich in omega-3 fatty acids and bases omega-3 fatty acids and bases omega-3 fatty acids and bases for this point and then they can reduce are using distance values that you can reduce and points have torch light episode 20 point using district distance first Golden approach button drafting footwear login slide arm hole activity login which can do is so humble in the problem is the largest language of wheat classes we can think of using a which x square Plus youth receiver Edison to Aishwarya Rai nahi ki points 198 kar do hu is this means whenever VHP's smallest night like a small this day views marksheet from this point molesters willow-tree willow-tree willow-tree 's largest 's largest 's largest is that military policy that Redmi Note 4 virus attacks On Ki Noida How To Use An Activist Problem Like And You Can Also Us Nail But Why They Should You May Feel Select Right 116 See A Love Scene Shoot Me To Front K Project Means What We Will Do Is Merger Se Eclipse Vitamin E Lab Technician Because They Need To Find True Understand Pure Devotion And Addiction 510 Mini And Definition Of Mountain Dew Later Dated 2nd Siddhi I'm To Ring This Point Like And Sorry For The Point Down The Distance Of Distance And Life To Dirty Meeting Appear A Bit Torrent Like Share So in the first president and the second one will be the foot second foot sweet like share and on this site of interior designing year waist foot of preparing district that in comment this life is it is the thing which aims toe ring clip 121 coma Antoine okay Maji Daina Dr To Comedy 15 - One And Doing So Like And Tourism And Finding The 15 - One And Doing So Like And Tourism And Finding The 15 - One And Doing So Like And Tourism And Finding The Distances And Story Present This Point Is Intermediate So You After Add Top-15 So You After Add Top-15 So You After Add Top-15 Withdrawal Points To Pune Just Because Of Haze 14 Lowest Value Will Be The Top 100 Item India Project Points The Top's Users Points Will Give Me Answer Top 10 Richest Man In His Approach To [ 10 Richest Man In His Approach To [ 10 Richest Man In His Approach To Give All Points The Whole Point And Jerry's Reward Point Flash Light Call Me To Find The Minimum Anand Swami's Minimum So They Need To Know Where To solve all the volume minimum welcome edit automatically beautiful space wear using more in themnegi minute's space is more which soon disadvantage of curing minute in this problem will have to front check list improvement or opposite mexico red active opposite gender left boil facewill Ahmed aur hai to again maxi vittori like this only is so let's take a massive maximum ninth see what will be besto will be easy for time will be having points induced not more than that call me to front this play list is morning wing From point K to time andar maximum to maximum solar plate start laptop JCB and written so let's find the distance and distances from this point from religion will be B C square plus B square which will win 10 torch light in the morning storing Paytm to M K A Thi Ko Is forced on which bhaiya storing sudhir and directly from teacher and a foot other foot of in dormant in comment and a sonavane to give this tool which gives no it na the rise of the apps limit cake was the fifth adding in the match cp anil size mist And this laddu's right down will go to the second point will find a distant improved distance from this point will be square plus once - cross website will come on 26th once - cross website will come on 26th once - cross website will come on 26th alarm set source 1526 to m the five to - 1m to - 1m to - 1m a right to know the Size Store Of Maximum It Is Equal To K Video K To Normal Note 8 More Points In The Mix It Back To Switch Pointer Time Yaad Chor K Point For Gionee Maximum Kar Twitter K Tourist Light Sun What Will U Will Come When Will The Size Of The World's Elections What We Do The Distance From This Point Subscribe Now To Be The Four Sorry - Up Be The Four Sorry - Up Be The Four Sorry - Up A Plus Form Ko Yashoda Morning Twenty20 Torch Light 21 Will Take Good Weather Top Element CEO And Sewerage System You Morning Maximum Distance Point Maximum Distance Between The Top 100 So Withdraw Station An Answer Love You To Front Closets Of 9 News One Will See Is The Current Point Vihar Phase More Valuable To Withdraw Cases Against What Will U Will Like This So How Is The Distance Between Is This Is The Current Special Stop this a research remove the thing with your needs and so will and Arvind ko m hai - jo kam for this point hai to hai - jo kam for this point hai to hai - jo kam for this point hai to english me vriddhi ne will be repeated December army response either aap time to maximum delay ho ki sorry display ko comment To give me all the point of view of this they will talk with our current point top distance and replaced the a record in neglected everytime the maximum reduce appointment commented on a co tight ones student approach should you Sachin for using hit the time table b.a. b.a. b.a. Torch light and press person overalls a plate here dear one who decorates rally sample jis accused answer vector that and veer viewers pinpoint says beating in this life is maths shift inside this which * units point wedding inside this which * units point wedding inside this which * units point wedding distance to you will not the android developed Darshan Adheen The Will Check Imperative Sizing Ki Sleep Witch Can Simply Hello And The Point Aaj Long Size Dhan Ke Just Incredible Return Ki Jhalar Is The Size Se Zinc Din What Will U Will Compare Distance Current Point Distance With Top Raipur Distance Top Bhatevar It Is The Top Will Compare That Survey Complete Distance With The Current Of Disease And Share Na Soe Details Loosening The Current President Has Stopped Qualities And The Top Of The Practice Your Interest And The Current Point Tonight Largest Eggless Vanilla Done With The Whole Performance Be Impractical This Points In The Blanks Itself Will Just For Them And Pushpender Chauhan Answer Selector Ki Suji Book Ko Drive Understand Platform Ad Shravan Ko Switch Cutting Accepted To Aaye Homeowners Toll Problem Beneficial Patience Video Favorite Halki subscribe To My Channel Highway Motivate Insurance etc. Many topics
K Closest Points to Origin
stamping-the-sequence
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in). **Example 1:** **Input:** points = \[\[1,3\],\[-2,2\]\], k = 1 **Output:** \[\[-2,2\]\] **Explanation:** The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\]. **Example 2:** **Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2 **Output:** \[\[3,3\],\[-2,4\]\] **Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted. **Constraints:** * `1 <= k <= points.length <= 104` * `-104 < xi, yi < 104`
null
String,Stack,Greedy,Queue
Hard
null
791
welcome to july's leeco challenge today's problem is custom sort string order and str are strings composed of lowercase letters in order no letter occurs more than once so everything's distinct now order was sorted in some custom order previously we want to permute the characters of str so that they match the order that order was sorted more specifically if x occurs before y in order then x should occur before y in the return string now return any permutation of string that satisfies this property so we can see we have our order cba we can imagine that uh this kind of maps into like abc here or i should say more like one two three and if we took our string and sorted it in this order we would take c first then the b then the a and then uh well what about d well since d does not appear in order it can be in any position in the return string it can be like in front or it can be in the back uh it doesn't matter we just need to make sure that everything inside order is sorted inside of string properly so okay well at first it looked pretty complicated but then you quickly realize we could just use a lookup to map each one of these characters to some integer we'll just start with zero each time we see a new one we're going to increase our iterator and make a map and then just sort this using the lambda function by uh entering the character into our map here so uh let's see all we have to do is create some sort of lookup i'm going to say default dict with integers also start with an iterator so let's move through every single character in order and add to our lookup uh or not add to it just make i each character in order since it's already in the order that we want then we're going to increase our iterator each time so now c equals zero b equals one a equals two so on and so forth after that all we have to do is sort our string here but we want to use a lambda function so key equals lambda x and we're going to enter this x into our lookup like this so this would return a sorted string but we want to make sure that we return i'm sorry a sorted list but we want to return a string so we're going to do a string join like this so we just return this now one thing to note though is what about that d uh this i think is going to actually air out well maybe more let's see here like we can see okay c b a that's sorted in the order that we want but d is kind of like in the middle uh so i'm not sure if this will work let's see oh it still works um okay well it works there uh originally i was going to do like get i was going to use the get function instead we'll use a get and enter in the x and then make some large number as the default in case it wasn't in there but i guess that's not necessary if we did this though we would ensure that everything that wasn't inside our order gets put at the very end here in the original order inside the string and this will work too so i expose it's up to you all right uh that's it so pretty easy one thanks for watching my channel remember do not trust me i know nothing
Custom Sort String
split-bst
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously. Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string. Return _any permutation of_ `s` _that satisfies this property_. **Example 1:** **Input:** order = "cba ", s = "abcd " **Output:** "cbad " **Explanation:** "a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ". Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs. **Example 2:** **Input:** order = "cbafg ", s = "abcd " **Output:** "cbad " **Constraints:** * `1 <= order.length <= 26` * `1 <= s.length <= 200` * `order` and `s` consist of lowercase English letters. * All the characters of `order` are **unique**.
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
Tree,Binary Search Tree,Recursion,Binary Tree
Medium
450
1,222
lead code 122 I took the solution from this um Nick white code look at it in here and this is the no this is the problems so if you are given a king in here what are the queens that can attack you which means like this one got blocked not even blocked it doesn't happen she doesn't even have any path and this one gets blocked by this queen so that's basically the problem and I already copied the code uh this is the first test unit where the king coordinate I would say this a coordinate right now we are from zero until index seven so this is coordinate three so when the king is here what are the quiz that can attack him I want to say anything beyond that um let's try to debug this and yeah I also put the I should stop my hand I also put the break line break in here so I know what do I start in the beginning I start with the list of the coordinate of the queen zero one two and so on so forth and that is the one that's in here zero one two three four three five four five and it's stated in here and the king is at the coordinate of index three so those are the index in here next we create a Boolean of the double array and it the size is like eight times eight so we got 64 which is like the equivalent of the size of the chess board in here Max we go to for Loop so for the integer of an array of the queen in Queens what are the Queens are here and these are the values so for each of this value we Mark that as true what is true so we created the new Boolean the Boolean that we have just created is in here so we got like all of them are false starting from zero until eight and then from this iteration we go to each of the queen which is like zero for the first example in here and we convert that into true so let's see so this is my keyboard This is the zero and then we right now in the iteration and it's already uh true in here I'll miss that let's move on for the one so this is still false and if I hit another step over f8 in here it will convert into true voila it's true and next if I also hit the step over it will shift the 2.2 which is here into true 2.2 which is here into true 2.2 which is here into true one more yeah that's true and then um we are in this line and if I click it once and it will go to the iteration because it hasn't stopped since like we still have the integer from the Queens in here so we are right now at the three four should be in 2 3 4 should be in here because this is the King location so if I click the step over it will convert into true after three four we get three five is in here yep and then we get four which is here and then four five so those are the queen we already mapped that in the double array outside the double array check the naming convention for that I would say right now double right you know what I mean so all the true and the false is in here and then we're done with that so right now we want to have an enum I would say this is an array of the direction of the minus one zero and plus one so we have we both have X and Y when is x coordinate minus one you are going to the left here I will try it yeah so in here this is our coordinate right let's start from 0 in here and if we go to positive we go down if in the normal coordinate we get 0 comma zero in here and this is one comma zero if we go up it's mean the positive it's not happening because in here because like this is what we have so when the x is positive we are going to the right it's the same this is X and this is positive and this is negative however with the Y when we go positive we go down so this is positive and we go up that is negative so that is what explain and this one we'll look at that in a second so next um we did that array and right now Loop through the X Loop through the Y if x d x and d y represent the amount of the movement which is like the integer of either minus one zero and one the difference is always one that's the movement with the direction that I have explained before if DX the movement of x is 0 and the Y movement is also zero we don't go anywhere and like we don't want that we just want to move so we continue we skip that Loop actually and right now we took the coordinate of the king which is like three and three the x is three and the Y is three so we have the result of King in here three and also it will be repression also in X and Y in here okay cool right now we have the boundary check in here let's move set this one this is the boundary check why because when X Plus DX should be greater than equal to zero we have our board in here and start from zero until seven zero this is seven yeah this is zero comma seven this is seven comma seven if X Plus DX let's say the DX is negative one and X is zero we are not going to check in here no we don't want to check in here so this is the boundaries if we go beyond of the left boundaries it will return false it will the statement is false and we will not execute this statement so this is what do you do in this one and then this is when X Plus DX let's say DX is 1 right and how can I write one ah all right did it is DX is 1 and X is already seven plus one is eight and eight is equal to eight not less than so we want to check an area in here which is like we don't have that's outside of the board so this is the boundary checking why goes go up and um this is y plus d y should be greater than equal of what the number in here is zero so we want to know if let's say the Y is 0 and the Y is negative one we will check the negative one which is area in here we don't want that ends the same this one y equals d y if Y is already 7 and plus d y is one we want to check the area of the coordinate of the eight it's not going to happen so make sure we only check inside the boundaries if you're a bit confused about that's just what does it do in here if you do more problem you understand more because like this boundary checks happen a lot now let's get back to the code in here so check right now what is our x right now at the coordinate of three what's our DX minus one three minus 1 is 2 greater than zero cool X Plus DX less than eight which is like uh two is less than eight cool and Y also two because three minus one y is three d y is oh and there's something in here I forget and d y is minus one three plus minus one is two and it's also greater than equal to zero okay y plus d y 3 plus minus 1 is less than eight two is less than minus eight so boundary check we are inside the board and right now we want to move X according X and Y according to the iteration that we have in here so that iteration goes like this is still at this delete this so this is X I would say this is y so we have minus 1 0 and 1 in here and from that minus one X we will check y also minus 1 which is where we are at right now and also zero and also plus one or positive one and then we take minus one we check zero we check plus one and when we all right this first this is minus one this is zero this is one and when we are at this point we will not check it because we are not going to move anywhere now check cool back to the code um so now X plus my X Plus not minus X Plus equal the X from 3 it will become two three plus negative 1 is 2 and then y also will become two now do we check do we have a queen at the coordinate of two and two do have the queen at the coordinate two of two or we can that see that in here yes we have a query in here if we have Queen there we will add that list coordinate into the result see we have one result right now and that is the size of the coordinate of the two and we break the loop we return so we are finished with the we are finished let me write so right now we are checking two comma two and here and we are checking this one we will not check Beyond this point so if we continue the loop let's say we don't have the queen for that right now X is 2. y equal 2 and then plus minus 1 plus minus one for the next iteration then the next generation is plus minus one it will become x equals one and y equal one so we are going to check in here since we have Queen here but it already blocked by this queen like we don't care about this queen like you will not have a chance at all because he already blocked you this also goes the same with the what is my cursor huh ah this one and that also goes the same with the zero because after this it will become zero and zero has no chance also um I'm stumbling right now so uh no check for one and zero comma zero because it's already blocked by two so we are done with this Loop right now we go to the next Loop in here notice right now DX is -1 still and d y notice right now DX is -1 still and d y notice right now DX is -1 still and d y is zero so what does it mean is that when you look at the table in here and I will erase this our path right now is moving with the Y is 0 and x is negative so we are going to this direction there will be no query in here so we should expect to see on a debugging the coordinate of from the three into the two three and then one column yes this is correct zero three so we should expect to see this coordinate in here let's see um right now we are at the 3-3 and then um right now we are at the 3-3 and then um right now we are at the 3-3 and then we from this line DX is not equal to zero yes we continue and we check again the king and then check the boundaries are inside the boundaries or not yes we are inside the boundaries and three plus minus one is two Y is zero Y is three plus zero is also three so we check the coordinate of two three just like what we expect to see in here two three so we check goes to this direction um nope we don't have any Queen so we kept going so right now from the 2 3 it will add one more negative one of the X it will shift from two into one see we got one in here and the Y remain at 3 because the value is zero and then we're doing that for the zero and three so we don't see any Queen and right now our DX is -1 and X is zero we are going our DX is -1 and X is zero we are going our DX is -1 and X is zero we are going to evaluate outside of the board and we are not going to do that's what is that's why the statement is false when it's false we are out of the loop so we are done with the second iteration a loop for this one and we are now going to be in here let me delete this first so I'm not confused yeah so this is where we are right now okay so start from three goes every iteration where X is negative one and Y is plus one so it will become 3 minus one and then three plus one so it's become two and four from Two and fours become one and five and become 0 and 6. that what should we expect from this code let's see about that yep we got the three first and the x is -1 the Y is plus one so we check x is -1 the Y is plus one so we check x is -1 the Y is plus one so we check are we still inside the boundaries yes we still inside the boundaries and then three will become two and Y become four two four where is that two four two and four yeah we're going here to four into one five and then zero six so we are going to this direction is there any Queen there no there is no Queen in this direction so it will just keep looping right from right now we are at the two four two minus one is become one and four plus one become five one five do we see any Queen let's check that in here no there is no Queen we move forward and then from that we just shift into zero and then six there is no Queen at the zero six okay so we are done with the first iteration of the x with all of the Y in here right now we are moving into this iteration yep x is 0 and Y is -1 so when x is 0 yep x is 0 and Y is -1 so when x is 0 yep x is 0 and Y is -1 so when x is 0 and Y is minus one we still are starting from three it will become three and three will become keep three and it will become two so we are checking for the three comma two three comma one and then three comma zero so where is that in here three this one I'm sorry this one I'm still confused Row in the column sometimes so we are going to traversing for this direction so previously we are diagonaling here right now we are just horizontal to this one and we are we don't see any Queen either so which is Loop without adding any a value on the result see result right now is still one that is two comma two index coordinate and we haven't had anything so let's check that we continue is it cut this is cut oh no now you can see it um three two minus one two plus minus one is become one becomes one yeah and then three zero and three zero in here and we get McQueen so we are done with the zero and minus one next we are checking for zero see here it says it's true because if we keep looping this it will come infinite Loop we don't want that so we just keep it or in the programming word says continue um right now we are at the zero and one for the zero and one with the same pattern I'll do this quickly because like we already know about this so for this one we are going to check of 3 comma 4 3 comma 5 3 comma six three comma seven and then three comma eight notice that we have the queen at the three four so we have the Queen in here right so this will add into the result and we are not going to check for this one because like 3 comma five in here is also Queen and this queen cannot attack a king because it gets blocked by the queen of three comma four but to give me and you I don't know 34 like the intuition like with this kind of the loop we can check the whole board so let's continue so right now we are at the 3-3 where the X is zero and Y is one and we three plus zero remains three plus one becomes four and at four do we see the queen yes we see the queen and right now the result will be added to the size of two right so we got the first one is for the 2-2 Pro 2 column row index two column 2-2 Pro 2 column row index two column 2-2 Pro 2 column row index two column index two and like row index three column index four and then so we are done with the with one so our next iteration will be this one so we are going to look for all of this I'm going to do it quickly because like if you watch it you should understand it um if not you I'm more than happy you keep repeating it on Loop for my video um right now when X is one and then Y is negative one so let's note that in here when X is one y is negative one so we will be going to the four and two five and one and then six and zero four and two five and one six and zero so we are going to this diagonal in here no Queen so we'll just keep looping without adding any result so that's three we'll go to the four two five one six zero we don't see any Queen and we end the loop for the X1 and Y negative one when you go to the next Loop which is like when the X1 and Y is zero when the X one and the Y is zero so it will be 4 3 5 3 6 3 7 3 and 8 3. is there any Queen in here do we have Queen at given Direction so this is when the row keep adding but still at the column three so it will be this direction I should not go to 8 because it's only index 7. yep so there's also no Queen in this direction so we just keep looping three four three see this one five three I'll just put my mouse in here and click it ha this is six three seven and we're done with the loop next we are going to the one and one so one and one when X is one and the Y is also one so this will be four five six seven yep we have Queen in here so we are not going to check any point beyond that because if there is a queen in here she cannot attack that you know it already uh oh so X is three right now we take the according of the king and then it goes into four three sin is false and you can see also whether we have queen or not if you don't see the board see in here the value is false and we continue 4 is true you can see the value in here that is true which means that we execute this code add array as list of coordinate for four so right now our result shift from 2 into 3 and we have two three four and four done so we are we done with the while loop yes we're done because like we were at one here and we are done with this so we are we done with the X Loop yes and then we return the result so the result is three and we should return the list off here yeah we already have that's like the data structure of the list of integer that's what we return and it's this is the actual as the expected and boom why um yeah try it for the zero to skip pushing the step over and see what would be the result
Queens That Can Attack the King
remove-covered-intervals
On a **0-indexed** `8 x 8` chessboard, there can be multiple black queens ad one white king. You are given a 2D integer array `queens` where `queens[i] = [xQueeni, yQueeni]` represents the position of the `ith` black queen on the chessboard. You are also given an integer array `king` of length `2` where `king = [xKing, yKing]` represents the position of the white king. Return _the coordinates of the black queens that can directly attack the king_. You may return the answer in **any order**. **Example 1:** **Input:** queens = \[\[0,1\],\[1,0\],\[4,0\],\[0,4\],\[3,3\],\[2,4\]\], king = \[0,0\] **Output:** \[\[0,1\],\[1,0\],\[3,3\]\] **Explanation:** The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes). **Example 2:** **Input:** queens = \[\[0,0\],\[1,1\],\[2,2\],\[3,4\],\[3,5\],\[4,4\],\[4,5\]\], king = \[3,3\] **Output:** \[\[2,2\],\[3,4\],\[4,4\]\] **Explanation:** The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes). **Constraints:** * `1 <= queens.length < 64` * `queens[i].length == king.length == 2` * `0 <= xQueeni, yQueeni, xKing, yKing < 8` * All the given positions are **unique**.
How to check if an interval is covered by another? Compare each interval to all others and check if it is covered by any interval.
Array,Sorting
Medium
null
1,780
hello everyone welcome to coderscam and today we are going to cover check if number is a sum of powers of three so given here is an integer value and we have to return true if it is possible to represent the given number as a sum of distinct powers of 3 otherwise written false so consider the first example that is n is equal to 12 it can be represented as 3 power 1 plus 3 square same way 91 can be represented as 3 power 0 3 power 2 and 3 power 4 so we are going to return true and 21 cannot be represented as power of 3 so we are returning false so how are we going to approach this so if a number can be represented to the power of 3 then it also can be divided by 3 that is any number that is giving reminder 0 can be represented by the powers of 3 but there are special cases that numbers can be represented at 3 power 0 in that case n minus 1 can be divided by 3 or otherwise n modulo 3 gives us reminder 1. so any number whose modulo with 3 can give us 0 or 1 can be represented in the powers of 3 otherwise if it gives reminder of 2 then it cannot be represented in the power of 3 by using this technique we are going to divide the number every time by 3 and if we get the reminder 2 then we are going to return false otherwise we are going to return to true until the number becomes zero so let's see how are we going to code it so we want to move the number until the number becomes 0 so every time we are going to check if the number gives the remainder by dividing by 3 is equal to 2 then the number cannot be represented in the form of powers of three so written false if not divide the number by three and iterate until it becomes 0 so finally if the loop completes without finding a reminder 2 then that case return true let's run yes let's submit yes a solution is accepted and it run faster than any solution submitted so thanks for watching the video if you like the video hit like and subscribe
Check if Number is a Sum of Powers of Three
lowest-common-ancestor-of-a-binary-tree-ii
Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`. An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`. **Example 1:** **Input:** n = 12 **Output:** true **Explanation:** 12 = 31 + 32 **Example 2:** **Input:** n = 91 **Output:** true **Explanation:** 91 = 30 + 32 + 34 **Example 3:** **Input:** n = 21 **Output:** false **Constraints:** * `1 <= n <= 107`
Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path
Tree,Depth-First Search,Binary Tree
Medium
235,236,1790,1816
5
hello this is kevin i'm a software engineer at google and a graduate of the es program at uc berkeley go bears and today i want to talk about lee code problem number five longest palindromic substring this is a medium difficulty problem and cool so basically the problem says like you are given a string and you want to find what is the longest you know substring or like a portion of the string that is a palindrome and a palindrome is a string that is dispelled the same forwards and backwards so bab right if you reverse this it's still bab so um you know for example like race car very popular palindrome right if you flip this around it's still a race car you add a z to it now it becomes not a palindrome right this backwards is now this so that's what a palindrome is cool so i think um you know it's pretty simple um how the problem works um all right and i was taking a look at also uh some of the solutions here and i just want to like i see that there's a lot of kind of complicated ways of going about this like this first solution has you know s prime all this like you know weird corner cases and it's dynamic programming this brute force one is n cube time complexity so it's not even it's pretty slow this one is n squared and n squared space uh the dynamic programming one and squared time and space um but this one right here the expanded round center this one is n squared time and space complexity is one so it's basically got the best complexity analysis and in my opinion this is the easiest to understand of the four so i don't know why you would even go for one of the other ones like this is runs the fastest least amount of space and is easier to understand so we're gonna go with this one i'm only gonna explain this expand around center one um approach number four um there are other problems for dp dynamic programming that are in my opinion a better fit for dp so you know there's other videos in my channel that you can check out or eventually i'll put up that are about dp that um would be a better fit for that different problems that would be a better fit for that but i think for this problem this expanded round center is the most intuitive approach before i dive into this though also they also provide a manager's algorithm they say which is a time complexity of o n which is actually really good for something like this if you were to look at the problem intuitively it wouldn't be very obvious like oh if there's actually even an o n approach to this i took a look at what this is it's very complicated and so i would not recommend um wasting time i don't say wasting time but um i don't think it's worth the effort to learn this right now and let me explain what i mean by that so i think the first thing we're talking about is which approach to use right dp um intuitive expand around the center and then managers and this is a big o of n squared and this guy is big o of n squared as well but better time better space complexity in this one's big o and in terms of time all right so for probably for a lot of people out there the goal of doing lead code is to be ready for an algorithm interview and ultimately to get the job at a big tech company get paid so usually how that works is you probably have something like a phone screen first generally on the phone screen you'll be asked the question let's talk about the process for a second um interviewing you're gonna start with a phone screen and then after if you pass the phone screen you do an on-site screen you do an on-site screen you do an on-site and the phone screen is going to be usually just one question and it's going to be moderate difficulty and so for the phone screen if you do end up getting this problem i think it's chances of you them expecting you to do manager's algorithm it's just overkill it's just too complicated and it's actually really high risk for you to use that algorithm in the phone screen because there's a pretty big chance you'll make an error or you won't remember it that well or like it's gonna be too complicated um and so if you make so the phone screen is a really binary thing it's really just to say yes no should we pers invite this person on site and so you don't even really need to blow it out of the park you just need to just not make any mistakes that's what it's really about so if you take this manager's algorithm and do it in the phone screen you're like it's really risky because it's easy to make a mistake it's just a hard problem so i guess that's probably a hard approach so that's basically the main thing about it so i wouldn't recommend manager's algorithm for the phone screen now for the on-site it's usually you now for the on-site it's usually you now for the on-site it's usually you know multiple algorithm coding sessions it could be you know two to three to four to five just depending on the company you're interviewing with and then how they would look at that at the end of the day is okay well this person did four algorithms uh out of the four algorithms they did great on two and they did okay on the other two for example that could be one analysis or it could be oh on the four they did really great on one and okay on two and the last one they just bombed it and you know in preparing for the onsite you're going to get a broad distribution of types of algorithm questions like the company wants to find out do you have the breadth to the breath of knowledge and have approached different types of questions um and so deep diving into one approach too much could actually mean that you end up not spending enough time prepping other topics it's better to have more breath here and so that's why again i don't think that manager's algorithm is really great for interviews just because it's too complicated the amount of effort you put in it's actually i think the time is better spent prepping and learning more breath or getting better at you know knowing this type of algorithm the expand around center approach a little bit better and be able to explain it more clearly so that's kind of my rationale why for now i'm not going to really go into this manager's algorithm but if you feel struggling about it leave me some comments and i'm happy to make um a follow-up video happy to make um a follow-up video happy to make um a follow-up video talking about that and i can also and dp as well if people are interested in dp i'm happy to make a video about dp i probably use a different problem though this isn't a good in my opinion a great example for dp um okay cool so we're going to do this expand around center approach and this approach is actually pretty intuitive i really like it so basically what the approach is like so number three our approach um basically how it works is we're just gonna let's say we have this string the bad it's just gonna um given a string to find um the longest substring that's inside of it you can actually just start from some center point and expand out until your substring is no longer a palindrome so for example b by itself is a palindrome and then you go out to one letter on each side a b a and again that's a palindrome and then you expand again to add one more letter on each side b a d okay well b and d are not the same so that is no longer a palindrome so we can stop expanding out and so for each center point you can basically find the biggest palindrome just by expanding out from that middle section right that's pretty simple and you would basically expand out until the so what are some conditions so okay so here's going to be our approach so expand out from a middle letter and when will we stop when uh we hit when two letters are not the same right like we saw b and d are no longer the same or we would stop when we hit the edge of the string there's no more letters like let's say we were here a we expand out to a b then we expand oh we can't go to the next one so b a b is the longest if a was the center and that's basically all there is to it's pretty simple you just expand that from a middle letter until the letters are not the same or you hit the edge of the string and then here they give you another um example just to help illustrate c b d and this one we could um if you actually start from each individual letter you expand out you actually would only get a bunch that are only one you can't expand out and find one but uh palindromes could actually have the center point which is let's so if we stand out from a single letter we're only getting the odd num letter the palindromes with an odd number of characters so we can also start from having two letters in the middle and this would cover all the palindromes with an even number of characters so vb so actually let's uh kind of show this a little bit um odd even right um if we start so basically what we could do is we could have two pointers a left and a right starting on b and then they would expand outward okay we already hit the edge so the biggest substring is one for even this one doesn't actually basically would start with our pointers on l and r right and oh they're already different so the substring is going to be zero and okay and then for then we'd move on to the next letter a and we would have both of our pointers left and right here okay it's fine a is the same as a and then we move the l over to here the r over to here right now that now they're the same as well so again uh we're good so now we're up to a pound term of three and then we move the l over to the end oh look we're off the end of the string so we can't check anymore so three and so we can kind of like fill out this table the same way this one would be three this one would be oops this one would be one and so then from each middle section we can find the best the longest palindrome with that is an odd number of characters and the longest power drum which is an even number of characters which is actually zero in every case in this one and then from there we just find the global maximum three in that case and output that so pretty straightforward and then for um this case um now this one the odd case is actually going to just be one for every case because there's no actual odd middle palindrome but for the even it becomes a little more interesting so even our pointers are going to be on l and um our left and right are going to be on c okay um all right i'm sorry actually c and b oh nope that's not one okay have our middle pointers beyond l and r okay they're the same so that's at least two and we expand this out oops oh goes to here r goes to here um oh c and d are not the same so two is the biggest and so we can kind of fill the rest of this out like that all right so and then again our global maximum is two so this one is there's a sub challenge on a two which covers the whole thing so that's basically the main gist of how would we um expand out from a center point and as our algorithm so why don't i go ahead and code this up um make it a little more concrete for you this might be too abstract and hard to follow along if let's see some code all right so how will this work okay so let's start with um i'm gonna have a little helper function here called longest at index and it's going to be passed in the initial starting string s so basically our thing just has s here right the string and a left and a right index that i was kind of showing earlier and what we'll do is while something we're going to keep expanding out so the left index goes to the left the right index goes to the right and they're going to the l and r going to be initialized that's the middle point and then we're gonna return something all right so when will we stop expanding one is if well the character at the left index and the character at the right index they have to stay the same so if they're not the same then would break out a loop so while they're the same we keep expanding right and that's this so this is to say when we stop so we would keep going if they are the same so if they're the same we keep going another reason we would stop is if we hit the edge of the string so if we don't hit the edge of the string we keep going so that's basically l is uh greater or equal to zero which is the bottom edge of the string and then r will have to be less than length of the string okay and so that's just saying okay well the left index as it keeps going to the left as long as it stays within you know this is the zero index it doesn't go any further you're good and if you're going to the right can go off the end of the string as well and we have to do this part actually first before we do the character checking this is just like because if we go off the end of the string then we do s at a specific index we would get an error so this also protects us from pulling characters that are off the end of the string and we won't have any errors if we do a check first and so as we expand out like this um let's just take an example again a b a for example so you know l and r both on b right and then they expand out to here and okay that a and a are the same and then they expand out again right then we minus one from l and we plus one from r and then we're off the end now so this while loop will break but our string actually is from one l that's previous to that and one r that's um previous to that so we'd actually after we finish our loop we would then just add one back to r and minus one from or add one to l minus one from r to get us this l goes back in to here so they actually represent the ends of our string and that may um believe me i thought about this for a while and try to see like how can we make this more clean i think this is the cleanest way to represent it and it's the most intuitive way so um that's how it is and now um ultimately we're gonna um now we want to return these um these indexes so and actually we also want to i think it's also good to have the length itself because we want to compare the maximum length against the global maximum so let's get let's do it this way we're going to have return your length left index and then left index right index like that so i'll create a tuple and return all three of those so it's going to be what is the length it's going to be r minus l and these are actually let's say it's this string right here r would be two l would be one it would be a length of two it's actually three so just add one to that because it's just the way the math works out this actually isn't really that important because we just need to know if this is bigger than some other one we checked so if we calculated the same way with or without this one it doesn't really matter but just for the sake of understanding what's going on we'll add the one in there and then we give the left and right indexes which we you know we got the right indexes from this so this is our little helper so from basically what this does is that any middle index if you expand out it'll give you the best string palindrome string the longest palindrome string and give the indexes of it won't actually give you the string itself and i think it's better to pass the indexes the reason why i passed the indexes here is because you actually take the string and you know pull the substring out that's actually another end time operation so you don't want to do that you just want to pass these indexes this is a constant time operation just getting the indexes and then at the very end we can pull the string out all right now let's uh we have to just iterate through the whole string so for i in exchange um length l r right our length our left index our right index equal to longest at index of s our starting string and the left and um so i is basically going to iterate through each index and then we're going to use that as your starting left and right strings and then if length oh okay so let's also keep a longest our longest we've seen globally our left index uh right index actually let's make this minus one uh i'll explain why later um so if the length that we are seeing locally is greater than our longest length then we do longest now equals this length left equals l right equals r cool and then for this situation we're just basically taking i and we are using it for both the left and the right index so this is saying we're going to be starting on the same character and expanding out from the same character so this is really the odd case right this will only find the number of palindromes that are have an odd number of characters now let's also make sure we do it for um i plus one oops why does it always do that okay i plus one length is longest oh we can just copy this whole part down actually so this is the same all right and this will be the even case and that's basically saying okay we'll have l start on one letter and then r start on the letter after it and we have all of our error checking to make sure we don't go off the end of a string so we're fine if we just you know let's say we're at the last index of i we go off the end it's fine this will still catch it and that's basically it and then after we finish this for loop we should return we're going to be left with a our indexes our left and right indexes should be the index of our longest string so then we can just go ahead and return s from left to right plus one and let's go ahead and try that all right cool so it looks like it worked let me just submit this make sure it works yay okay it worked um let's see here one thing let's see what i was gonna call out oh okay this right talked about this the right minus one thing um let's just think about what would happen if you were to be given a test case that is an empty string so you would essentially um uh you would get to here you would actually not even enter this right because len s would be zero so you would not enter this for loop and then you return s from left from zero to right and so if this was zero would do zero plus one would be from zero to one oh that might actually still be okay that's probably actually fine it doesn't really matter i just wanted to highlight the case that in the interview you should just make sure to test this corner case if you are given an input of an empty string what does it return in our case it returns empty so that's fine so good um cool and i guess uh this is a super minor but these two parts are basically exactly the same so you can actually even factor this a little bit more and just say for j in x range 2. python this is just going to go up to 2 0 and 1 and exclude 2. so that's what this is and then we'll take this all right move everything over and this will be i plus j right that's the only difference so it's a little bit cleaner i guess it's just saying like okay for each middle index you will test it with um or left and right are both i and j can be zero or one so they're a bit the same and then when j is one then it'll be that character plus the character to the right of it will be the middle point and then we'll do the this thing so let's just i'll just submit that make sure it works cool that looks like it's working um cool so let's uh this is basically you know if you get to this you explained everything clearly i think this is um you should be fine for this type of uh for this question oh actually let's see one other point i was going to cover in this example it says you get bab or aba is valid i mean this is a small curveball but they could potentially throw us to you like how can you get your code to output bab or aba and so what this is really asking is bab is the first time you see the longest one aba is the last time right so let's actually just take this guy um and right now we have it and that's really controlled by this whenever our length is greater than the longest that means each time we see one that is actually bigger than the last one we saw then we would replace our global maximum so this will give us the first one the first instance of the longest one so that would be bab in this case so let's show that and if we just change this to greater or equal to then each time we see one that is greater than or equal to so as long as the longest one we've seen then we will output that so this will give us the last time we see the longest count the long last time we see the longest um palindromic substring so that would be aba in this case this is basically just we keep on seeing ones that are length of three long and so the last one we see that is length of 3 long will be the output so i'll just show that this will give us a b a cool um which one's better i mean i think probably this is better less operations um but and just so you just understand like that you can kind of control that so if the interviewer asks you then that's how you control that and let's talk about space and time complexity so time uh for this one essentially what you would do is you're iterating through right you're gonna do this for loop one two one operation through here through each character and actually there's two operations so that's going to be 2n well drop the constant it's n and then here we do this expanding thing and this expanding thing can actually take up the entire um you can expand out through the entire uh string so this is again another end time operation so this ends up being 2n for this part and this one is n so that's 2n squared which is n squared drop the constant space right we don't actually use any other data structures we just update these three variables it's constant there's nothing is growing with the size of the input so space is constant space cool so that's basically the solution here's the code here's our kind of overview of the stuff here's our time and space complexity hopefully that was helpful if you have any follow-up questions or a particular follow-up questions or a particular follow-up questions or a particular topic that you'd want me to cover in more detail leave me some comments and i'll go ahead and cover those in a follow-up video and cover those in a follow-up video and cover those in a follow-up video or if there's a specific question on lee code that you want me to cover again feel free to leave some comments and i can follow up with a new video on those questions all right thanks so much for watching and best of luck in the interviews
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
1,626
hey everyone welcome back and let's write some more neat code today so today let's solve the problem best team with no conflicts before we start I will say that this is very similar to the problem longest increasing subsequence which we've solved on this channel this problem is actually even harder than that problem so if you struggle with this one I definitely recommend checking out that explanation I think it's one of my better explanation videos but the context is that we're trying to maximize a score we're given two arrays one is the scores array and one is the ages array and we want to maximize the sum of scores but there's a restriction on which scores we can pick and the longest increasing subsequence problem that restriction is that we have to choose values in an increasing order we're given an array and we can only choose values that are in an increasing order so maybe these two values would be in increasing order well with this problem it's slightly different and it's more difficult because there's actually two conditions that we have to check for one is that if we have two scores such as 5 and 15 these are our scores we can only choose both of these scores if the age of the player with the larger score is greater than or equal to the age of the player with the smaller score in other words we have a contradiction we can't include both of these scores if a player that is younger has a higher score than a player that is older I know that's pretty confusing which is probably what makes this problem hard that this isn't like a straightforward Condition it's hard to kind of wrap your mind around it and it turns out that the time complexity to solve this problem the way I'm gonna do it is going to be N squared which is hinting that sorting the arrays is going to be pretty necessary and is going to make our life a lot easier so let's sort the scores already that's how I'm gonna handle it but you could sort base based on the age as well but I'm going to sort based on scores and in this case the scores are already sorted for us so this makes it easier because now we don't have to compare every pair of values with each other we don't have to compare this one with this guy and this guy with this guy we are already going in increasing order we already know our scores are going to be in increasing order so now the only thing we have to check is every time we add a new value so suppose we're here and we're trying to add this next value the only thing we have to check is that this player with a higher score does not have an age that is lower than the player with a lower score that's the only thing we have to check one way to solve this problem is to do it recursively we can try to generate every single combination of scores every combination of valid scores and see which one leads to the maximum so recursively we would go through every value so for one we would choose to include one or not include one we'd skip it and then here we would choose to either include three or not include three skip it now in some cases we won't be able to include a value at all if we don't satisfy that age condition like the ages are not in increasing order because we already know our scores are so therefore our ages should also be in increasing order if they're not then we have a contradiction doing it this way will generate every possibility and we'll be able to maximize the result this though is going to be 2 to the power of n in terms of Big O time complexity though the way you can code this up you can call it DFS where we have two parameters one parameter is i that's going to tell us what index we're currently at we'll have a second parameter J though which is going to tell us what is the largest age of a player we have seen so far in other words this J is going to point at the pair of values the pair of score age values that tells us what is the max age we have seen so far the reason this is necessary is because we don't want to check when we're here at 10 yes we know that the scores are sorted so when we're at 10 for example we know that 10 is going to be greater than or equal to all the previous scores but we don't know the same thing about the ages could be completely random this could have an age of seven this could have an age of three this could have an age of four so from here we don't want to iterate through every previous value so we just save the max age we have seen so far this saves us some work and not only that but this allows us to do DP dynamic programming because we have two parameters I and J we can Implement caching on these two parameters what is the total number of combinations for I and J that we could pass in well since each of them is just going to be an index for the input array each one could have a possible value of n so we have n times n that's the total number of combinations we could pass into that recursive function so the time complexity would be N squared let me quickly show you the code for that but then we're going to get to the true dynamic programming solution because for some reason this recursive solution does not pass on leak code at least when you're using the Python language so very quickly this is the recursive dynamic programming solution maybe I have a bug or something but at least for me this is not passing on leak code you can see this is one of the base cases where we go out of bounds of the array then we return zero this is our caching case where we've already this is our cash hit case where we have already seen this value before then we can return it immediately otherwise we will have to calculate the score we have two cases we can either add the current score or skip the current score but remember we can only add the current score if the current age is less than the max age that we have seen so far I think this condition is actually not necessary since we sorted our pairs based on the score we created a array of pairs where the first value in the pair is score and the second value is the age and we sorted it like that so I'm pretty sure this is actually not necessary but this does not pass on leak code for me at least I'm also going to add the ages but I'm going to switch this up slightly to make this more interesting because in this example we're just adding all of the scores but I want to make this a bit more interesting so let's give this a age of five let's give this one an age of three building Upon Our caching solution and this is the part where you might need to have a good understanding of the longest increasing subsequence problem but the idea is this for every score let's try to find the maximum possible score that we can have if this guy was our Max score so if one was our Max score what is the possible maximum score that we could have given these conditions well in this case it would probably just be one because we can't add any more scores this is the smallest one and we're assuming that this is the largest score moving to the next position what is the maximum score we could have if three was our maximum score well we can't again iterate through any values to the right but we can start all the way at the left over here and try to find the maximum well for this value we have to check does it have an age that is less than or equal to the age of three that's important because if it's not the case then we're not allowed to add this value to 3. but in this case it is so what we say is the maximum possible score we could have if three was our maximum score like the maximum total sum score we could have if three was our maximum score would be four because we can add these two together there's no contradiction here and not only that we're going to actually put that 4 here now so we're going to put a 4 value over here this is so that we don't have to do additional repeated work because that was the idea behind caching and this is a similar idea behind dynamic programming so now you're going to see why this is useful in this next position five we want to know what's the maximum total score we could have if 5 was our maximum score so let's iterate through all values to the left of it because we of course can't add these guys they're bigger than it so we look at one does one have a smaller score than five yes it does so the maximum so far we have found is five plus one so we would put that here which is six then we're gonna go over here at four does the value here have an age that's smaller than the age of six yes two is less than five so now we found a new maximum four plus six so we would put 10 in this position notice how from here we already knew that if we were able to create four then we only added values from the left of it that had a smaller age than the value here so if the age of this is smaller than five of course all of the ages from here that we added to this position were also less so that's why we're allowed to do this is where the repeated work comes in handy now next in this position we're going to do the same thing we're going to look at the left C1 it has an age of one that's less than ten we add these two together that gives us 11 so that's our Max so far then we do the same thing over here 4 has an H of 2 that's less than four so we have four plus ten that's a new maximum of 14. now finally we get to the last value here it has a value of 10 that's really big but the problem here is that 5 does not have an age that is smaller than four so we can't add it to ten so we say our maximum so far is 14 and that's the maximum we can get with a max value of ten and then finally we get to 15. we're going to do the same thing 1 plus 15 we're allowed to do that so we'd have 16 we'll have 4 plus 15 we're allowed to do that because 2 is less than 3 so now our maximum so far is 19 but these guys have an age that is larger than three so we can't add them here unfortunately so we say our Max score if our Max score was 15 our Max total score would be 19 and these are all the possible result cases so we just take the maximum of all these five which is 19 and that's going to be our result that we return notice how we just had two nested for Loops to iterate through this array so that means the time complexity is Big O of N squared the memory complexity is Big O of n we didn't even have to create a two-dimensional Matrix or anything like two-dimensional Matrix or anything like two-dimensional Matrix or anything like that so now let's code it up so to save us a bit of time I'm just going to copy and paste a few lines one we're doing is creating that list of pairs since we know the scores and ages arrays are of the same length we are creating a pair where the first value is the score the second value is the age and we'll have a list of each pair and then we're going to sort the pairs by default this is going to sort based on the first key value so this is going to sort based on the scores if there's a tie it's going to sort based on the ages but that's not really important in this case so we know our scores are going to be in ascending order that's what's important our DP array is going to just be initialized with the scores since we know the first value in that pair is the score so just like in the drawing that I showed we'll have the scores sorted in ascending order in our DP array then we're going to have a couple nested for Loops we know our I pointer is going to be the first pointer we're going to iterate through every single position in pairs so we're considering if this was the maximum value the value at index I what's the max total score we could get so we can only iterate through values to the left of it so we're going to have a j pointer and it's going to go from zero all the way up until I and the easiest way to do that in Python is just like this so for J and range up until I now before I even do that I'm going to create a couple variables this isn't necessary but I think it makes it more readable at least for me remember we're considering if this was the max score so I'm going to say pairs at index I is going to give us these two variables Max score and the age of that Max score which I'm just going to call Max age even though it's not really the max age and then we're for every J value for every value to the left of I we need to check that the condition is satisfied since we know the pairs are already sorted in ascending order we don't have to check that the scores are in ascending order but we do have to check that the age at index J which let's put those in a couple variables as well score and age we can get with pairs at index J if the age of the person with the higher score is greater than or equal to the age of the person with the lower or equal score then we know we are allowed to add the value so what we say is d P at index I because that's ultimately what we're trying to determine what's the max total score we could have with this Max score is going to be the max of itself just like I showed in the drawing or possibly the max score plus the DP value that we have stored at index J which is the max score we could have where this is the maximum score and we have made sure that the age condition is satisfied though if the age condition was not satisfied then we would just skip it we don't have to do anything here we don't need an else condition here because we're not going to do anything in that case but when all of this is over we know our DP array will have all the possible result candidates we just have to return the maximum from those candidates and then we're good to go so let's run this code to make sure that it works and as you can see yes it does and it's pretty efficient if this was helpful please like And subscribe if you're preparing for coding interviews check out neatco.io it has a ton of free resources neatco.io it has a ton of free resources neatco.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Best Team With No Conflicts
can-make-arithmetic-progression-from-sequence
You are the manager of a basketball team. For the upcoming tournament, you want to choose the team with the highest overall score. The score of the team is the **sum** of scores of all the players in the team. However, the basketball team is not allowed to have **conflicts**. A **conflict** exists if a younger player has a **strictly higher** score than an older player. A conflict does **not** occur between players of the same age. Given two lists, `scores` and `ages`, where each `scores[i]` and `ages[i]` represents the score and age of the `ith` player, respectively, return _the highest overall score of all possible basketball teams_. **Example 1:** **Input:** scores = \[1,3,5,10,15\], ages = \[1,2,3,4,5\] **Output:** 34 **Explanation:** You can choose all the players. **Example 2:** **Input:** scores = \[4,5,6,5\], ages = \[2,1,2,1\] **Output:** 16 **Explanation:** It is best to choose the last 3 players. Notice that you are allowed to choose multiple people of the same age. **Example 3:** **Input:** scores = \[1,2,3,5\], ages = \[8,9,10,1\] **Output:** 6 **Explanation:** It is best to choose the first 3 players. **Constraints:** * `1 <= scores.length, ages.length <= 1000` * `scores.length == ages.length` * `1 <= scores[i] <= 106` * `1 <= ages[i] <= 1000`
Consider that any valid arithmetic progression will be in sorted order. Sort the array, then check if the differences of all consecutive elements are equal.
Array,Sorting
Easy
1752
561
hey everyone welcome back and today we'll be doing another lead chord array partition an easy one given integer array nums of an integers group these integers to and Pairs and such that the sum of Min a b and so all the maximize return the maximize some so we are given an array in which there are you can say our pairs so one is paired with fourth and three two so we have to find the minimum you can say like if we have an array we are going to sort our array because this will just help us to get the first character not the first character the element so if we have it like this so we are adding one with three by skipping two uh by skipping the element so if there are they are in pairs you can say so this is how we are going to do and in an example you can say like if we add one two three we are going to get four and now we if we have assorted you can say like one 2 and the fifth element is 5 and 6 oh 6 and 6 okay six and now if we have like one skipping two and three then it will going to be returning nine in that case so this is how we are going to return this whole sum so first of all making a sum which will be zero so let's not use sum so because it is built in you can say so um in is also sums yes sums is okay so for I in the range of starting from 0 to the length of s and skipping two characters at a time to uh taking two steps at the time so uh the sum will be the sums plus the num nums at so it is nums okay so that's this and I and after doing that we can just return the sums but not yet because we didn't sort our arrays so let's do nums and sort and short and done
Array Partition
array-partition-i
Given an integer array `nums` of `2n` integers, group these integers into `n` pairs `(a1, b1), (a2, b2), ..., (an, bn)` such that the sum of `min(ai, bi)` for all `i` is **maximized**. Return _the maximized sum_. **Example 1:** **Input:** nums = \[1,4,3,2\] **Output:** 4 **Explanation:** All possible pairings (ignoring the ordering of elements) are: 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 So the maximum possible sum is 4. **Example 2:** **Input:** nums = \[6,2,6,5,1,2\] **Output:** 9 **Explanation:** The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9. **Constraints:** * `1 <= n <= 104` * `nums.length == 2 * n` * `-104 <= nums[i] <= 104`
Obviously, brute force won't help here. Think of something else, take some example like 1,2,3,4. How will you make pairs to get the result? There must be some pattern. Did you observe that- Minimum element gets add into the result in sacrifice of maximum element. Still won't able to find pairs? Sort the array and try to find the pattern.
Array,Greedy,Sorting,Counting Sort
Easy
2112,2248,2261
1,099
welcome to problem 1099 two sum less than k we'll read the problem real quick given an array a of integers and integer k we turn the maximum as such that there exists i is less than j with element i plus element j equals s and s is less than k if no i and j exists satisfying this equation return negative one so that was a mouthful to basically say find two elements in this array which maximum sum has to be less than k so here's an example right we have a array of a bunch of elements and the k is 60 so the maximum sum of two elements in this array that is less than 60 is 58 meaning that there is no sum that exists in this array that is less than 60 and greater than 58 so 58 is the max now how could we go about solving a problem like this so the very first thing i would think about is brute force right so what is the most you know simple way you can think about this on top of your head to solve this right the brute force is what we call it now what comes to mind is let's compare every element except to itself right that way we can get you know up all possible sums so doing so if we can get all possible sums we know that in one of those sums there exists a sum that is the maximum of less than 60 and if in the case that there isn't then we could return negative one meaning that there is no possible sum that is less than k and how can we go about doing that right a brute force that comes to mind is having two pointers i and j where i we start off at zero and j is we always start where is i plus one so the reason why i would start it this way is because we can get every possible sum except the sums that you compare the same element twice which we won't do in the scenario we would do something like this we'd keep i anchored and we would move j to the right until we hit the end of the array so we go and let's have another variable here for demonstration purposes called max so we'll do i plus j so in this scenario 34 plus 23 is 57 and then we move j over so then we go 34 plus 1 is 35 well 35 is not bigger than our current max of 57 so we move we keep going and we go 34 plus 24 well that's 58 that's definitely bigger than our current max so we update our max and we keep going and we're going to keep going all the way till we hit the end of the array and then we're going to reset i where we increase i to the next number and then we compare 20 we add 23 to every possible number to the right of it to 1 to 24 275 to 33 and then we keep doing that right and we're always checking to at every iteration we're checking if that sum is greater than our current max in doing so you're would have compared every possible number until you got until j hit the end of the array when j hits the end of the array this is where we exit out of the for loops and we return the max and in this scenario be 58 and 58 indeed is less than 60. so what kind of pseudo code would this be right so we have i and j um so we would have to have one for loop that controls i and we have to have another for loop that's nested which controls j this type of setup would be a running time of n squared so we can all there's always somewhere out there's always a better solution but given this particular problem i think n squared is suffice so let's code this up and see if we pass all the test cases and how we compare to the other submissions so let's do that now cool so let's get to coding dope so the very first thing i'm gonna start with is the max right this part if we can't find it return negative 1. so we'll start off max at we'll do lat max equals negative 1 meaning if we can't find a max that is less than k then let's just return max which will be negative 1 in this scenario so here's where we start with the iteration right how do we set up our pointers of i and j so we do a for loop where let i equals zero right we're always started i in the beginning um for demonstrational purposes get this back in here so we want to start i right here so zero cool so then we'll do i is less than um a dot length uh let's do yeah a dot length and then we'll do i plus oops and then we now want to set up our j so for let so we said we our j is always going to be it's going to start at next to i so we can do this we could do let j equals i plus one meaning j would always be one ahead of i and we're gonna do while j is less than a dot length j plus very cool so here comes the part where reading the point the problem is very important right so the problem is saying that in order for us to update the max we have to satisfy where the sum is less than k right k and for this example k is 60. so we can get the sum the current sum by doing something like this let's do curse sum equals a element at i position plus the element at the j position so now we would do if the current sum is less than k right satisfies what they're asking in this scenario and max and current sum is greater than max which we really need both of these parts because we wanted to satisfy that is less than k but we also want to make sure that we're updating our max every time right so if this if both of these are true we're going to update our max so max equals current sum then once this is all over we can return max so again going back to this example we're saying if there is no sum that is less than k then we could return negative one right but because we're setting up max to be negative one anyway we could just return it so let's kind of go over this real quick so we're going to compare 34 and 23 and that's 57 so we're going to update and that's true right 57 is less than k and 57 is greater than our current max which is negative one so we update our max to be 57 and then we keep going and once we get to 24 that's when we would basically say is 58 is 34 plus 24 which is 58 less than k yes is 58 greater than our max which is 57 yes so then we would set that up we go through every one and find out that yes max our current max for this specific example is 60. it's 58 sorry so then we return that uh and i think we're i think this solves a problem let's see if we pass all the test cases let's hit submit awesome and just like that we have a runtime of 60 milliseconds which is faster than point 78.60.65 four percent of point 78.60.65 four percent of point 78.60.65 four percent of javascript online submissions that's awesome so um i hope you guys liked it and i'll see you guys at the next problem
Two Sum Less Than K
path-with-maximum-minimum-value
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`. **Example 1:** **Input:** nums = \[34,23,1,24,75,33,54,8\], k = 60 **Output:** 58 **Explanation:** We can use 34 and 24 to sum 58 which is less than 60. **Example 2:** **Input:** nums = \[10,20,30\], k = 15 **Output:** -1 **Explanation:** In this case it is not possible to get a pair sum less that 15. **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 1000` * `1 <= k <= 2000`
What if we sort each cell of the matrix by the value? Don't include small values in your path if you can only include large values. Let's keep adding a possible cell to use in the path incrementally with decreasing values. If the start and end cells are connected then we don't need to add more cells. Use union-find data structure to check connectivity and return as answer the value of the given cell that makes start and end cells connected.
Array,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
Medium
1753
187
Jhaal Hello Hi Guys Welcome To Dad Today's Question Is Repeated DNA Sequence In This Question In The Given To See All The Ne Is Composed Series Follow This Zee Tv For Example ACG Ek TCG Midning DNA Test Subscribe Video Function Latest Song Sequence Aa Jaaye Aksar More Than bansi dna molecule shop word in this question in portal clove sequence scripters nor in this point to point 20 clove subscribe more than one day egg white and 5c and 5s and 5c this cream and with oo a part-time 0.2 time hair phase 2nd T20 World Cup I will find all the sub strings all the something which of land stand will find all the suffering with tarf left hand and a now half minute inauspicious and to the frequency of them for example c twitter hash map working with string and validity number of minister at one time vansh veervar first time when the whole district but its position s 6 string will read me pudina part such that and one method frequency of this till now no any time any unwanted something which is already decided and agreed For Different Hindi Fashion Update Yearly Person Just Incremental You To Adjacent To The Frequency Of Deception Who Smacked Later And Middle Head Dept Dost Ki Value Added One Will Update In Answer To This Question Let's See Share It A View To Find The sub organization let alone and egypt in cbse eleventh length and width will be able to penetrate time airtel according to hair middling substring in this question in which will find answers in final odi match that in thought of with spring that a draw and belief typing and will smith MP Now Being Given This And Will Tree To V This Sequence Valid For 200 Dot Length 8 - 10 8 - 10 8 - 10 A Little I Labs Dainik Paltu Advance - 0 A Little I Labs Dainik Paltu Advance - 0 A Little I Labs Dainik Paltu Advance - 0 I Plus Switting This In This Commission Latest And Will Find Every Possible 20 Long Substring Every Possible Ten Letter Long Suffering And Regret And - Ten Letter Long Suffering And Regret And - Ten Letter Long Suffering And Regret And - Tan Because A Last Subset In Which River Which Will Be Fullerton With This Taste Will Be Descended From Beyond Death Will Find Any Specific Thoughts Ladoo Length Tan Will Win 8 And Intuitive And Something Unique Web Services Tax Return Long Subsequent Philosophy Singh Sudhir and Treated through Edit Length - Turn Off But I Don't - Turn Off But I Don't Agree with You Will Find a String of Long Ago Position Relative Starting Initially Pt Position Til-Til Understand and Length Will Pt Position Til-Til Understand and Length Will Pt Position Til-Til Understand and Length Will Be 10th by Sudhir Pandey Substring Details of 80 Length Election Doob Beta Testing Match Will Put in a Face Map and MP of Plus Will Increase e Increase The Frequency of Difficult Spring Towards Vid Increment One Listen After 10 Above Crisis Bhi Have All The Possible Something Which Of Land Can Map These With There Corresponding Frequency Now Nobody To B C D That Naidu Who Is Tractor Safe Button Springs Vibrating That He Because Beta Testing Spooch Acid Spring British Which Everyone But 119 Dost Something Witch Value Vitamin E List Not Visiting Are A String On A Letter His Map Arif Effect Second Remedy Value Is Greater Than One Word Verification Answer A Answer Husband Spring Video not support to subscribe and subscribe the Channel Ko Hai Bank Account Dr To bank to simply return ki saari in it vitamin hair a FD length of the input record of this transaction broken 0 that they simply return gift from if anti bacterial batter absolutely straight length office substring in Delhi and subsequent 2809 possibility of finding nor pativrat traveling of Planet 10 20 Minute Wise Sudhir Will Return MP3 Twitter From Here This World And Knowledge Front School A Hai Yes Okay After A While ABP Delete This A That Aapke Stress List Bluetooth Setting On Custom Cass No Late Submitted O Ask A N C Reddy Questions Cutting Accepted Biogas Like This Video Thank You
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
263
hi guys how are you so today we will solve our 18 day challenge question that is the ugly number so here we need to return true here we have a number and we need to return true if it has a factor and that factor is only Prime and that is limited to only two three and five okay so 6 as a factor 2 and 3 and that is limited to two three and five so one have a any Factor no one do not have any Factor that's why it is returning true if it has a factor and that factor should be Prime and that prime numbers will be limited to two three and five okay it has a seven as a factor 2 into 7 but 2 is also Prime 7 is also Prime do C1 is limited to two three and five no say 1 is greater than 5. and what is what all about zero so 0 is has a prime factor yes you can write 0 as a 0 into 2 0 into 4 0 to 5 0 into 6 0 into 7 so its prime factor does not limits to two three and five so that's why if we have a zero then we need to return first so I hope this is clear to you only this one uh so what I will do next okay so assume if we have a 15 so first I will check with 2 whether it is divisible no then I will check with 3 it is divisible yes so after dividing I will get five so 5 is still divisible by 3 no then I will reach to 5 because we have only three number two here if it is not available are only Prime and that has been limited to three and five so I need to return here true bye so okay so assume take as a 14 example here it is given 14 so first I will check 2 is divisible by 14 or 14 is 0 by 2 yes I will get 7 then 780 visible then the for 2 from 2 I have get the seven so I will check with three seven and eight divided by three no okay five feet divisible by 7 digital by say five no so what I will get n as a c 1 and it is not one so that's why I need to return here false let's take another example if you have a take 8 so 88 divisible by 2 yes so I will get here for 4 is divisible by 2 yes I will get here 2. so 2 is divisible by 2 yes I will get here 1. Now 1 is not divisible by with the help of two so then I will check with the help of three and five it is also not divisible so ultimately I have a 1 and that will be written true so that we need to only Implement here so let's Implement here so if it divisible by 2 then I need to divide it otherwise I need to check with 3 with the help of 5 ultimately at the last if we have uh n as 1 then we need to return true otherwise we need to return false let's directly submit it because it's easy I don't think so it will create any problem yeah so it has been submitted I hope this is clear so this is n and we are going through because end time because we are dividing every time so I hope this is clear we are not using any extra space so this is bigger fan and this will be go of one space complexity and bigger of end time complexity I hope this is clear to you I will meet in the next video with the next video till then bye take care and if you like the content then like the video subscribe the channel and comment as well I will meet in the next video with the next video
Ugly Number
ugly-number
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_. **Example 1:** **Input:** n = 6 **Output:** true **Explanation:** 6 = 2 \* 3 **Example 2:** **Input:** n = 1 **Output:** true **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Example 3:** **Input:** n = 14 **Output:** false **Explanation:** 14 is not ugly since it includes the prime factor 7. **Constraints:** * `-231 <= n <= 231 - 1`
null
Math
Easy
202,204,264
102
welcome to lead programmer today we are going to look at the question binary tree level order traversal so we have been given a root of a binary tree and we have to return the level order traversal of its nodes values that is from left to right level by level uh so if you look at the example one what it essentially means is these are the various levels so this is the first level this is the second level this is the third level in our level order traversal we have to form an array of elements in each level what that means is for the first level we'll have three for the second level we'll have nine and twenty for the third level we'll have 15 and 7. in order from left to right so 9 and then 2015 and then seven and at the end the result would essentially be an array of array so it'll be an array of these arrays over here and that's it awesome so now you might be thinking how to proceed with the question so as a rule of thumb um three traversal questions either follow BFS or DFS breadth first search or depth first search now let's quickly explore what each of them means depth first search essentially means we explore the depths before we explore the breadth and breadth for search means we explore the breath before we explore the depth so one possible depth first approach over here would be okay first we have a three then we go to nine and then to 20 then we go to 15 and then we go to seven you see we up we go to the depths first but in this question we wanna uh execute uh we're gonna go level by level which means we don't want to explore the depths first so okay you might think that points to breadth first search we explore the breadths first and that's exactly what we have to do so we have the node 3 and then we explore all its neighbors we go breath first so first we have a three and then after three we go to nine and twenty so we explore its neighbors after we explore three's neighbors we explore Nine's neighbors and after we explore Nine's neighbors we explore 20s Neighbors so uh let's add two more elements here let's add one and two now how would this work uh so okay so we start at three we are at three now when we are executing three we want to keep track of its neighbors so the neighbors of three are nine and twenty all good now when we are at nine we're gonna keep track of Nine's neighbors so we have one and two and when we are at 20 we want to keep track of twenties Neighbors which is fifteen and seven and then we execute all these individually so as you can see what do we do here we essentially have to use a data structure to help us achieve this and one thing that you might have noticed is we can whatever element we insert at the first is the one we execute first which is something like first and first out principle and what uh which data structure follows the first and first out principle you heard it right it's a queue so we can essentially use a q so let's see how a queue works for a platform search and all the breadth first search questions or the platform search algorithm makes use of a queue for its implementation so let's see how that works imagine that this is a q we are at three first so we insert three into the queue now we execute all the elements in the queue so we execute three so when we are executing the node 3 we insert 9 and 20. um so and at each point we take a snapshot of the game so now three has been executed it's removed from the queue now we take a snapshot of the queue so at the snapshot we have 9 and 20 so we have to execute 9 and 20 before we move on um to any other elements right so when we execute nine we insert one and two to the queue and then we move on to 20 we ex we insert 15 and 7 to the queue so once all the elements in the snapshot in the previous snapshot has been executed we take a new snapshot and then we continue the same Pro process so let's say we had a b uh d f so uh we would have first popped one and then entered a b we pop two nothing to enter then we pop 15 it's D and then we pop seven it's F and then we execute these after taking snapshot of these so you get an idea we use a q uh at we create a snapshot and that's how we go okay now there's another thing to observe so let's redo this example uh so we have a queue and we are executing our breadth first search algorithm so we first insert three we take a snapshot of it and when we are executing three we have inserted 9 20. then after executing three uh we take a snapshot of 9 and 20. and uh this is what we previously saw then we take a snapshot of this well notice one thing this particular snapshot has three which belongs to the first level this snapshot has 9 and 20 which belongs to the second level from left to right this particular snapshot has elements 1 to 15 and 7 from left to right in the third level so as you can see breadth first search algorithm in itself goes level by level because it explores its neighbors completely before moving on so there you have it's essentially the solution to this question is a normal breadth first search uh the only thing we have to add to that algorithm is just to keep track to have a variable or an array to keep track of the elements of each level so let's see how that works let's look at the code so we have a result array that's what we returned at the end uh if we pass an n empty node so if root is empty we just return an empty array we have a queue data structure as we saw we populate the Q data structure by the root and we keep going till the queue becomes empty so if the queue is empty we are done uh now over here you see we take the length of Q this is like taking a snapshot of the queue so we execute so we have a for Loop to execute all the elements of that size because we took a snapshot of the Queue at that point and we execute that many times and uh and then after taking the snapshot we can keep inserting elements in the queue it doesn't matter if you're just going to execute uh size number of times so uh in the for Loop for each element we first pop it from the queue and then we want to process it so we check if the uh if the left child is not empty then we append it to the queue and if the right child is not empty by empty I mean uh null then we insert it to the Q and we also have a temp array to keep track of the nodes at each level because this for Loop executes all the nodes at one level so once we are done with this for Loop we can just insert it to the results array and uh that's it that's the solution to the question uh the space and time complexity can be said to be the Big O of n because of the first case uh if you have a linear arrangement of the nodes then we go through all the nodes uh so I hope you found this helpful uh please subscribe to the channel thank you
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035