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
138
hey friends today let's practice lead code number 138 coffee list with random pointers so this problem is given a linked list such that each note contains an additional random pointer which could point to any node in the list or no and we need to return a deep copy of the list so my approach to this problem is to use map and go through each node in the original list make a copy of the node only with the value and put it in the map the key is going to be the original node and the value is going to be the copied node in the after that iteration we go through the original list again and then assign the copied nodes next to any random nodes based on the original nodes and we can get to those two values from the map is that makes sense so let's start with creating a map since we're going through this list I'm going to make a dummy note to point to the head so that we don't lose the head as we go through the list so now let's go through the list well how does not know would create a copy off the head and put it in a map you know we move ahead to the next node so now all the copy nodes only have the value it doesn't have any values for the next node and the random node but now we go through this list again and assign the next node and the random node so let's coin it to a head again I'm gonna go through this list again we grab each copy node based on the original node and the sign it's next node after that move the head and after these two iterations the node results that we want should be the heads value in the map all right let's take a look at this so we have a map and the key is the original node and the value is the copy node and would create a dummy node to hold the starting point of the original list then we move the head through the list and make a copy off the head with its value and put it in the map after this iteration we move the head back to the original position and go through this list again we'll get a copy of the head and assign its next value to the copy of the has next value and so is the random node then we'll move ahead to the next one and return pads value in the map let's run it's a mint all right that's it today see you next time
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
35
hey everyone welcome to Tech white in this video we are going to solve problem number 35 search insert position so given a sorted array of distinct integers and a Target value we need to return the index of the Target and if the target is not found in my input array then I need to return the index where the target would come in my input array now we will see the logic and the code for this problem now let's dive into the solution so from the question we know the input array is sorted and we need to write and login time algorithm so we are going to use binary search so here I have my input array and the target value is 5 so I need to return the index of Phi right so I'm going to have left and right pointer and I'm going to have a middle value when you take the middle value you see left and right pointer by adding the left index and right index and I am going to divide that by 2 to get my middle value so here my left pointer is 0 and my right pointer is 3 so these are my index then if I add them I'm going to get three and if I divide by 2 basically I will use the floor operator so that I will be getting an integer I'm going to get 1. so my middle value will be 1. the middle value is pointing to the index 1. right then I need to check my middle value whether it is equal to my target here it is not equal to my target 3 and 5 is not equal then I need to check whether my middle value 3 is greater than my target or it is lesser than my target right so in this case Target is greater than the current middle value so I'm going to increase so this condition is true in this case so I'm going to move my left pointer after my middle value right since my target is greater than my middle value I'm moving my left to pointer after the middle value right now I will add the left and right pointer index which is 2 plus 3 and I'm going to get 5 and I'm going to divide by 2. here my middle value will be 2. so this is nothing but the middle index so both my left pointer and my middle pointer will be pointing to index 2. now I need to check whether my middle value is equal to my target here the target is Phi and the middle value is also 5 then I will return the pointer m which is nothing but 2 here now I will show you guys with another example if the target is not found in the input array so in this example have a Target 2 which is not found in my input array basically so now again I'm going to add my L and R pointer I'm going to get 3 which is nothing but 0 plus 3 I'm going to get 3 I'm going to divide by 2 I'm going to get the middle index value so I'm going to get 1 so M will point to First index this will be my middle value now I need to check whether my middle value is equal to my target no it's not equal to my target then I need to check two conditions whether it is greater than my target or it is lesser than my target whether the current value right current middle value so here in this case 3 is greater than my target it's greater than 2 right my target is 2. now I will move my right pointer before my middle index value so now my R comes before my middle value so basically l r m or my index values right so again I will run the loop so I will run the loop until my right pointer is less than my left pointer so in this case both are pointing to the same index that is 0 so I'm just going to run the loop again I'm going to add L plus r so I'm going to get 0 plus 0 and I will divide it by 2 so my middle index will be 0. so M will be pointing here so all of my three pointers are pointing to index 0. now I need to check whether my middle value that is 1 here middle value is 1 is greater than my target now it is not greater than my target so I'm going to move my left pointer to the right of my middle index so I'm going to increase my left pointer so my left pointer will come here so basically my left pointer will be pointing to 1 now right so in this condition I am not going to run the loop again since my left pointer index is greater than my right pointer index so my right pointer index is pointing to 0 my left pointer is pointing to 1 so I'm going to come out of the loop now I will return left pointer so the basically the left pointer will be pointing to index where my 2 will come if I need to insert in the input array so basically if I want to insert 2 in this input array I will insert it in the index one so I'm going to return 1 here which is nothing but the left point now we will see the code so before the code and if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and keep supporting guys so initially I'm going to have the left pointer will be pointing to the zeroth index then the right will be pointing the last index of my input array right then I'm going to write the loop so I'm going to run this Loop until my right pointer is greater than my greater than or equal to my left pointer so now I will calculate the middle value middle Index right by adding the left and the right pointer I'm going to divide by 2. then I'm going to check whether my middle value is equal to my Target if it is equal to my target I am just going to return the middle index else if the middle value is less than my target I'm going to move my left pointer to the right of my middle index yes I will move my right pointer before the middle index so if I didn't find my Target in the input array then I'm going to return left pointer so basically left pointer will be pointing to the index where my target would be inserted if I need to insert right now let's run the code so the time complexities or log of n since we used binary search happy learning keep supporting cheers guys
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
127
Jhaal Hello guys welcome to here Amazing question world in this question Thursday subscribe and subscribe the Channel Please subscribe And subscribe Video to like subscribe Video subscribe ki sapoch this is the example given winners subscribe this rumor subscribe And subscribe The Amazing spider-man Acidity subscribe The Amazing spider-man Acidity subscribe The Amazing spider-man Acidity Ki Problem is doing so will get you have three types of Thursday subscribe must subscribe width combination its combination subscribe in a number of middle to-do list fifty chat every word anti The Video then subscribe to the Page if you liked The Video then subscribe to subscribe in adhin that guy subscribe tu ritu note are clicked in this question Thursday subscribe combination Video subscribe and subscirbe appointed subscribe and subscribe this Video hua let's see how they can quote 10 using given then an in five years will see subscribe to A Beneficial Exalted and Vice President No words to not mean that doing enough evidence which contains that the end world citizen canteen dhlo om namo he will discuss with to have been set in you find the acid country will define the term that in bringing a minute And difficult word in the form of operations on the capital of birth change in the middle of vid oo ka naam bijli supply ab fans operation on this at will define this ritual difficult like share and subscribe liquid must subscribe to why not old woman president in the Beginning Set Also Remove WhatsApp Subscribe Remove They Will Remove All Your Husband 14 Dodgy Sites Into The Biggest Winter Please Like This A Favorable Position Starting From 0 To That Winter's Chintak Characters From Madhes Position Will Convert subscribe The Amazing Modified Cars ' Facility Changes Are Ingredient ' Facility Changes Are Ingredient ' Facility Changes Are Ingredient ki kuldevi from k mein tel valid naagin changes position to this character subscribe button not hidden veer vinay david whatsapp subscribe thursday subscribe to tomorrow morning whatsapp contains a new word fuel subsidy into with oo hai what is the new word in it's a request to the Video then subscribe to The Amazing Play Services A Plus One Understand Plus B Subscribe After All Pressure Complete The V Which They Remove Video Subscribe Loot Lo Ajay Devgan Simply Returns 20 Otherwise Written In The Middle And Avoid A That Distance In Winters Uber is they do the distance in the overall result for example in this subscribe I Suresh Kauth submitted successfully vitamin space complexity of a process of times square * in our what is the length of the subscribe mode of subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe Congress Hand Will See How They Can Implement and How They Can Operate * Implement and How They Can Operate * Implement and How They Can Operate * Optimized Toe Hang Meet Doobie Face Beautiful Individual Should Not Have Any Set To You Will Find Another Site Twitvid Jai Hind In Just Like Jab Bigg Boss Debit The Biggest Evil The Video then subscribe to Hai Tu Kal Swimming And The Injured Have Been Not Have Any Adverse This Line Will Change The That A Commented On Then Will Still Be A Good Condition President That Animal So That Add Will Be Answer Blurry change the size of this at mid subscribe and subscribe the set kar do loot hindi sex condition entry never withdraw its content subscribe my channel subscribe must subscribe ki sugar review feelings of use time difference baikunth mil Sake Power Off Video Subscribe subscribe this Video Subscribe Liquid Subscribe
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
572
when it comes to Binary trees we all know about the inorder pre-order and know about the inorder pre-order and know about the inorder pre-order and post order traversal techniques right but what happens when you start solving problems we forget about them correct so let us try to explore a problem on lead code that uses these travel cell techniques Hello friends welcome back to my Channel first I will explain you the problem statement and we'll look at some summative cases going forward I will tell you how you can use these traversal techniques to come to an efficient solution and then you will also see some of the gotchas and caveats that you need to be careful about after that as usual we will also do a diagram of the code so that you can understand and visualize how all of this is actually working in action without further Ado let's get started first of all let's make sure that we are understanding the problem statement correctly in this problem you are given two binary trees A and B correct and you have to determine if the tree B is a sub tree of tree a right so what does that actually mean so as you can see in our first test case this is the first tree a and the fifth tree B right and you can see that okay this tree four one two you can find this entire tree right over here right so I can say that with 3B this is a sub tree of the actual tree a so if this condition is true you just need to return a true else you need to return a false so in this case true will be your answer however you need to be careful about one thing you can see that in the test case number two my sub tree Remains the Same right 4 1 2. but if you check my original tree this is slightly changed right and you may say that okay you can find the same tree again over here right but in this case the answer will be false because your tree B this does not have any child nodes correct but in an original tree this node 2 this has a child node 0 right so you cannot say that this tree is actually a sub tree of tree a so in this particular test case you have to return false as your answer this was one of the primary things that you needed to be careful about so now if you feel that you have understood the problem statement even better feel free to first try it out otherwise let us dive into the solution before we start solving this problem I want to let you know that this solution involves the knowledge of knowing either the in order or the post order or the pre-order traversal techniques so if pre-order traversal techniques so if pre-order traversal techniques so if you're new to them I would highly recommend you to stop this video right over here and look at those videos first you can find the link in the description below because based on that we will try to come up with an efficient solution so let us take up an example you are given two trees right and you have to determine if this tree B this is a sub tree of your original tree correct so just looking at it visually you can see that yes okay you can find the same tree 412 right over here right but how do you go about solving this programmatically how do you write an algorithm for it so a few things can come to your mind you know that you have to Traverse this entire tree somehow right so you are gonna Traverse the first tree and then you try to gonna Traverse the second tree so that is how you know that okay I can iterate over each of the elements and once you have got all the elements then you can start to think that okay now I have the elements and I can try to compare that okay the same elements are occurring in the same order and that can tell you that hey this tree is a sub tree of the original tree so try to understand what I'm saying you need to find a way that you can Traverse this tree so you Traverse this tree in a certain fashion right you will get some sequence of all of these notes correct and then what you're gonna do is you will try to Traverse this tree also and then once again you are gonna get a certain sequence right so to determine if this tree B this is a sub tree of your original tree then this sequence this will lie somewhere over here in the bigger sequence right and this is where the tree traverses will come in very handy so for now what we're gonna do is we are gonna try to do a pre-order traversal of both to do a pre-order traversal of both to do a pre-order traversal of both these trees so how does a pre-order these trees so how does a pre-order these trees so how does a pre-order traversal actually work for a pre-order traversal actually work for a pre-order traversal actually work for a pre-order traversal you Traverse the root first then you Traverse the left Fab tree and then you Traverse the right subtree correct so now let us try to apply the pre-ordered traversal on our first tree pre-ordered traversal on our first tree pre-ordered traversal on our first tree so starting off with the rule first of all we get the root element then we need to look at the left subtree once again we will apply the pre-order once again we will apply the pre-order once again we will apply the pre-order traversal technique over here so we are gonna get four that is the root then the left element and then the right element for now the root if taken care of the left if taken care of you're just remaining with the right child right so I take this up and I enter it so this is the pre-ordered traversal of your first the pre-ordered traversal of your first the pre-ordered traversal of your first tree correct similarly what you're going to do is you will do a pre-ordered traversal of your will do a pre-ordered traversal of your will do a pre-ordered traversal of your tree b as well so doing a pre-order tree b as well so doing a pre-order tree b as well so doing a pre-order traversal first of all we get the root that is for then the left element and then the right element so then I get 4 1 and 2. so this is the pre-order traversal of your is the pre-order traversal of your is the pre-order traversal of your secondary and this is the pre-order secondary and this is the pre-order secondary and this is the pre-order traversal of your first tree right so now try to feed you can see that this pre-ordered traversal pre-ordered traversal pre-ordered traversal this particular sequence you can find the same sequence over here in the full pre-order traversal as well right so pre-order traversal as well right so pre-order traversal as well right so this tells you that yes this tree is in fact a sub tree of your original tree so this is a concept that you can try to apply what you will do is you will first get the pre-ordered reversal of your get the pre-ordered reversal of your get the pre-ordered reversal of your first tree and then you are gonna get the pre-order traversal of your the pre-order traversal of your the pre-order traversal of your secondary and then just try to compare if this shorter screen or this sequence this is a substring of your original bigger sequence if yes then you can simply return a true else you have to return a false in this case you can find the sequence existing so true will be your answer so for this particular test case I took the advantage of pre-order traversal it the advantage of pre-order traversal it the advantage of pre-order traversal it is up to you can either choose the in order traversal technique or you can also choose the post order traversal technique an important thing to notice over here is that the level of traversal technique will not give you a correct answer let us try to do a level on a traversal technique and see what is the problem so for the first read the level of traversal will give you three then four then five then one and then two correct and for the second tree you are gonna get four and then one and then two right so you can see that 412 does not exist anywhere in the sequence right and then this will tell you that the answer is false so a level or a traversal technique will not give you the correct answer and that happens simply because a level or a traversal technique does not take into account how the nodes are connected it will just go level by level and try to give you a sequence whereas all of the pre-order post order and in all of the pre-order post order and in all of the pre-order post order and in order traversal techniques are based on recursion property and they follow the property of a tree throughout that is the left child the root and the right node so just don't use the level order traversal technique you can use any other traversal technique as you wish but also then there are a few gotchas that you need to be careful about before you actually write your solution so let us have a look at them so once again I have these two trees in front of me right three a and 3B so if an analogy was correct we try to apply the pre-order traversal technique apply the pre-order traversal technique apply the pre-order traversal technique on both the trees and then we are gonna just see if the tree B string is a subset of the tree a string correct try to do a pre-order traversal of tree try to do a pre-order traversal of tree try to do a pre-order traversal of tree a how does the pre-order travel actually a how does the pre-order travel actually a how does the pre-order travel actually go you go root then left and then right so I start off with a root and I write down 4 over here then I go to the left in the left as well I have a small tree and then I take the root so I take a one then I take a left and I get a 2 and I don't have anything on the right all the values are none right so I get my pre-order traversal as four one two pre-order traversal as four one two pre-order traversal as four one two correct now let us look at our tree B and once again do the pre-order and once again do the pre-order and once again do the pre-order traversal on it you will go root then left and then right so once again what do you get four one two correct and as you notice both of these pre-order traversals are same so if you pre-order traversals are same so if you pre-order traversals are same so if you try to check the sequence in this sequence this will give you true in fact correct but as you can see this tree you cannot find this tree in the original tree correct so what do you feel is your Technique wrong no the caveat that I'm talking about is you also have to include all of the null nodes when you are approaching this problem using this technique let me show you what I need when you're looking at your tree a this tree actually have all of these null nodes also right and then if you look at the pre-ordered and then if you look at the pre-ordered and then if you look at the pre-ordered reversal we never accounted for all of these null nodes now when you have all of these null nodes in place how will you pre-order travel end up looking your you pre-order travel end up looking your you pre-order travel end up looking your pre-order traversal will end up looking pre-order traversal will end up looking pre-order traversal will end up looking something like this correct because how do you Traverse it first of all you go to root so you get four then you look at the left Factory right in your left subtree again you look at the root for one you get a one and then once again you look at the left in your left you have the small tree so you get a 2 over here then you get your null note as a left node then you get the right node that is null again then you go back up so you get a null node again and then you go back at the root node so it Traverse your right mode so with all the null values this will be your complete pre-order this will be your complete pre-order this will be your complete pre-order travel file for now try to apply the same technique to the secondary as well in your second tree also you will fill out all of your null notes now once again try to do a pre-order now once again try to do a pre-order now once again try to do a pre-order traversal of this complete tree with all the null nodes and when you do it you will get your answer something like this for now do the sequence check try to find out if you can find this sequence in your actual string you cannot find it over here right because this has changed now so this is the only major caveat that you have to be careful about while solving this problem all of this is now clear to you let us quickly do a dry run of the code and see how it works in action on the left side of your screen you have the actual code to implement this solution and on the right I have a big tree that is defined by root and I have a smaller tree that if defined by sub root and both of these trees are passed in as an input parameter to the function is subtree oh and by the way this complete code and its shift cases are also available in my GitHub profile you can find the link in the description below so moving on with the dryer so if you notice in the beginning I have a helper function now this helper function is nothing but it takes in a root node and it will try to do a pre-order traversal it will try to do a pre-order traversal it will try to do a pre-order traversal of the entire tree so what it does is it takes in the node to begin with and then does the entire pre-order traversion does the entire pre-order traversion does the entire pre-order traversion it will then return me this entire traversal in form of a string so I can look it at in a form of a sequence correct so now let us move back to our actual method in this method what is the first thing that we do first of all I convert my first tree in form of a string right and then in the next step I will convert my second Tree in form of a string so once these sequences are formed I will get correct so this is the sequence of the first tree and this is the sequence of the second tree and these are in the pre-order format right pre-order format right pre-order format right so you have to determine if the second tree is a sub tree of the first one I just use a contains function that is in the standard string library right so you can see 412 dove in fact exist in the pre-order sequence of the first tree pre-order sequence of the first tree pre-order sequence of the first tree this is true and simply this will return your answer the time complexity of this solution will be order of n where n is the total number of nodes in your bigger tree and the space complexity of this solution will also be order of n because you are using recursion and you are using the space to hydrate over every node in your bigger tree I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that when it comes to Binary trees I know that level order traversal seems very easy and it is usually advantageous than all the other techniques correct because in a level of a traversal you can literally go level by level iteratively and then also visualize what is happening you can pick every element and then see okay these are its trees and that's what I want to do right but sometimes for example in this problem you will not be able to achieve this solution using the level Auto Service technique so do not just skip all of the other traversal techniques just because a level of a traversal technique did not give you the correct answer so always just watch out and keep an eye on the other traversal techniques as well it could be possible that they can give you a better result for example a binary search tree it can give you all the elements in a sorted order using the inorder traversal technique so always just watch out for all of them so while going through my video did you face any problems or have you found out any other problems that cannot be solved using the level of a traversal technique but can be easily done using any of these separate techniques or are there any other special test cases that you found out where these techniques are very handy tell me all of these things in the comment section below and I would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify concept for you also let me know what problems do you want me to follow next until then see ya
Subtree of Another Tree
subtree-of-another-tree
Given the roots of two binary trees `root` and `subRoot`, return `true` if there is a subtree of `root` with the same structure and node values of `subRoot` and `false` otherwise. A subtree of a binary tree `tree` is a tree that consists of a node in `tree` and all of this node's descendants. The tree `tree` could also be considered as a subtree of itself. **Example 1:** **Input:** root = \[3,4,5,1,2\], subRoot = \[4,1,2\] **Output:** true **Example 2:** **Input:** root = \[3,4,5,1,2,null,null,null,null,0\], subRoot = \[4,1,2\] **Output:** false **Constraints:** * The number of nodes in the `root` tree is in the range `[1, 2000]`. * The number of nodes in the `subRoot` tree is in the range `[1, 1000]`. * `-104 <= root.val <= 104` * `-104 <= subRoot.val <= 104`
Which approach is better here- recursive or iterative? If recursive approach is better, can you write recursive function with its parameters? Two trees s and t are said to be identical if their root values are same and their left and right subtrees are identical. Can you write this in form of recursive formulae? Recursive formulae can be: isIdentical(s,t)= s.val==t.val AND isIdentical(s.left,t.left) AND isIdentical(s.right,t.right)
Tree,Depth-First Search,String Matching,Binary Tree,Hash Function
Easy
250,508
107
okay let's talk about binary level order traversal 2 so you are given the root of a binary tree return the button up label order traversal official value so 3 9 20 15 7 right you have to written 15 7 9 20 and 3. so this is uh straightforward for preferences so you're adding the queue into i'm adding a node into a queue and then for each level you just add to the list and then later on it just add to another list then when you add to the list of lists you just have to add to the font so they just call it so this base integer i'm gonna call this name i'm using linked list because they will actually save a lot of time when you uh add to the front and it root people know let me say return base so uh let's empty this right so i need another um key right so q go between i'm gonna call q new linkage and i would just add go over or that doesn't matter add to the queue and then well uh q is my mp then i will traverse i'll kill you now uh at the end i just have to return to this one okay now i need to um i need to store each level no so i need another list i'm going to say a list of individual code labels instead so uh this will be it doesn't matter already so it doesn't matter and uh what we have to do is we have to memorize the size of the current queue so insights is actually cute outside because we need to try very so full loop um we need to follow the traverse the current label and if i at this position i know my q um i know my note has two children so i add these two choosing to my q so if i just using the q the size this is incorrect because when you pop right you do actually modify your size of cube so this is a fixed size for the level and three node i'm going to call no and then q dot poll i'm holding the three all right i'm adding the three and pulling the three and i'm going to check uh okay so before i check i'm going to add to the list of integer which is level and let's put that uh leader level. and then i'm going to check if my note on that is not known and if it's not known which means there's a children right then i know that's you then same for the right and do that i know that right then this would be the solution but at the end of the for loop we need to store every single uh value which is a list of integers into the list of lists right so we already store every node into the label then we need to know um i need to add every single node in this label to the list so list.add and i this label to the list so list.add and i this label to the list so list.add and i need to add into the front right because the bottom up right so do the and for the next level loop right you will just keep traversing all right let's just run it okay i do have an error so what is it if no okay basic i may type over here okay this is pretty good so standard and let's think about the timing space complexity so uh whatever you do you need to translate this every single note right so that will cost all of them for time how about a space is out of length because you store every single note into a list of lists right that would be all the fun right so this question uh is straightforward you can use preferences to solve this problem and if you have any questions subscribe like a like the video if you want and then uh leave a comment if you have any questions all right i'll see you next time bye
Binary Tree Level Order Traversal II
binary-tree-level-order-traversal-ii
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[15,7\],\[9,20\],\[3\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
102,637
1,792
hi everyone it's albert today let's solve the contest median question maximum average pass ratio and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical questions with clear explanation animation and visualization now let's look at a question in this question there is a school that has classes of students and each class will be having a final exam and we are given a two dimensional integer array classes where each item in classes is another sub array of two items past and total and we know beforehand that in the eye class there are total students but only past number of students will pass the exam and we also have the integer extra students these are brilliant students that are guaranteed to pass the exam of any class they are assigned to and multiple extra students can be assigned to the same class and we want to assign each of the extra students to a class in a way that will maximize the average pass ratio across all the classes and here we define the pass ratio of a class is equal to the number of students of a of that class that will pass the exam divided by the total number of students of the class and then the average pass ratio is the sum of pass ratios of all the classes divided by the number of the classes and we have to return the maximum possible average pass ratio after assigning the extra students to optimize classes so in example one we can assign the two extra students to the first class and then the highest average pass ratio we can get is 0.78 is 0.78 is 0.78 any example two with a given classes and four extra students the highest pass ratio we can get is 0.53 is 0.53 is 0.53 and the data constraint for this question the length of the class's array can go up to 10 to the power of 5. the intuition to solve this question is a greedy algorithm and greedy means that we will primarily assign extra student to a class whose average score will increase the most and to keep track of class that will have a highest score increase we will use the heap data structure or so called priority queue now let's look at the code okay and the first step is to build a heap and in python you can just use a standard list to form a heap but to use a hit push and hip hop api to add and remove item from the heap and for every item in classes we'll first calculate a delta and delta means that if we assign an extra student to that class how much will the average score change and then we will push a tuple of negative delta pass and total into the heap and why negative delta that is because the heap in python is by default a minimum heap and we want to keep track of the highest delta class so in this way the class with the highest absolute delta will be pushed to the front of the heap and next we will start to assign the extra students so first pop the first item from the heap and then assign the extra student and calculate the new delta after assigning the extra student and then push it back into a heap because we are able to assign multiple extra students to the same class and after assigning all the extra students we will calculate the average pass ratio at the end and return rest now let's see the coding action okay and here we'll be looking at example two this is a classes array and we have four extra students and the heap will be looking like this and here we can see that the first class 2-4 has the highest absolute delta class 2-4 has the highest absolute delta class 2-4 has the highest absolute delta 0.1 it means that if we assign 0.1 it means that if we assign 0.1 it means that if we assign an extra student to this class its average score will increase the most compared to other classes so we will assign one extra student to it and then the new delta and pass and total in a subarray is a point zero six seven and three five and then we'll push the new tuple back into the heap and now in a new heap the class 210 the fourth class now has the highest delta so we will again assign one extra student to this class calculate the new delta pass and total and push it back to the heap and now we have two extra students left so now the new heap class 39 has the highest absolute delta so again we will push one student into it calculate the new delta pass and total and get the new heap i repeat the same process now is the first class already got one extra student and still have the highest data so we will assign another extra student to it and then calculate the new delta pass and total and the new heap now we don't have any more extra students so the total average pass ratio will be the sum of a pass divided by total in each tuple in the heap and then divided by the size of the heap which is 0.534 in this example which is 0.534 in this example which is 0.534 in this example and this will conclude the algorithm finally let's review so the main algorithm to solve this question is a greedy approach and greedy is we primarily assign extra student to the class whose average score will increase the most and to achieve this we use the heap or priority q data structure and the time complexity of this approach is big of n plus k log n for the heap then the space complexity is big of n and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
Maximum Average Pass Ratio
find-the-most-competitive-subsequence
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam. You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes. The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes. Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2 **Output:** 0.78333 **Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333. **Example 2:** **Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4 **Output:** 0.53485 **Constraints:** * `1 <= classes.length <= 105` * `classes[i].length == 2` * `1 <= passi <= totali <= 105` * `1 <= extraStudents <= 105`
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
Array,Stack,Greedy,Monotonic Stack
Medium
402,1159
384
with go to question number 384 Chevrolet this is medium question let's get into it shuffle off set of numbers without the pretension ok let's check it again for the one really super nonsense one two three so we able to shepherd 1 2 3 &amp; 3 1 three so we able to shepherd 1 2 3 &amp; 3 1 three so we able to shepherd 1 2 3 &amp; 3 1 2 1 3 that is the same of the big the one of commutation but we needed to keep the weight the mean is in this position the 1 2 3 ever to sit here equality so and then another history said he said is change it to oddity that value so 1 2 3 so we need to increment the three teens the first to reset we needed to keep reading a value and it must be copied by belief to not copy by reference because if you the capybaras if original data is changed or electrons value also change it so we need to do to take care of it so first left side no cellphone output is lumps and that's F is the call by value so the capital to make a new list and then put a unit test number then this one ant is on its different object so if we will change it is on but this one is that cannot change did not change it so that the service it is the self out what I will put list of self original to keep on it in a video so return self out for the last self ok can we make delicious and then I will suffer from the first index to the here one up here because if we put this is 2 and this is 3 and then this one is no need to shuffle because this value chopper only one thing is to see you make sense so for I in range length 4-1 so let's make the index it 4-1 so let's make the index it 4-1 so let's make the index it under the index to swap this one from two so index time like the rental value LAN anthem we lend int start for I 2 then minus 1 plus T itself and then I will swap index with ok now we switch swap each potential value and then return it looks good in this case 10 copies for initializing is constant and then we set also constant and then shopper that has one iteration so all of the function without shuffle is constant and then shoplog is linear time and species it take the linear space because it keyboard is not value thank you
Shuffle an Array
shuffle-an-array
Given an integer array `nums`, design an algorithm to randomly shuffle the array. All permutations of the array should be **equally likely** as a result of the shuffling. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the integer array `nums`. * `int[] reset()` Resets the array to its original configuration and returns it. * `int[] shuffle()` Returns a random shuffling of the array. **Example 1:** **Input** \[ "Solution ", "shuffle ", "reset ", "shuffle "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\]\] **Output** \[null, \[3, 1, 2\], \[1, 2, 3\], \[1, 3, 2\]\] **Explanation** Solution solution = new Solution(\[1, 2, 3\]); solution.shuffle(); // Shuffle the array \[1,2,3\] and return its result. // Any permutation of \[1,2,3\] must be equally likely to be returned. // Example: return \[3, 1, 2\] solution.reset(); // Resets the array back to its original configuration \[1,2,3\]. Return \[1, 2, 3\] solution.shuffle(); // Returns the random shuffling of array \[1,2,3\]. Example: return \[1, 3, 2\] **Constraints:** * `1 <= nums.length <= 50` * `-106 <= nums[i] <= 106` * All the elements of `nums` are **unique**. * At most `104` calls **in total** will be made to `reset` and `shuffle`.
The solution expects that we always use the original array to shuffle() else some of the test cases fail. (Credits; @snehasingh31)
Array,Math,Randomized
Medium
null
1,380
hello viewers welcome back to my channel I hope you are enjoying all the problems that I am uploading if you haven't subscribed to my channel yet please go ahead and subscribe today's problem is lucky numbers in a matrix given M by n matrix of distinct numbers written all lucky numbers in the matrix in any order a lucky number is an element of the matrix such that it is the minimum element in its row and maximum element in its column so basically there can be zero or more lucky numbers which can satisfy this property it should be minimum element in its row and a maximum element in its column right so let's go ahead and try to understand with an example here alright so here let's put in a matrix format so that is more readable right so that's how it is and then right alright so let's see minimum element what we care minimum element in row right so minimums so means we have three rows right so what is the minimum element in first row it is three right what is the minimum element in the second row it's nine what is the middle of an event third row it is fifteen right exactly so max right so we need maximum and it's calm so what is the in the first column what is the maximum it's 15 right and what is the max in second column it's 16 right what is the third one 17 right Maxim that is essentially the last row it seems right in this particular example 15 16 and 17 right so if we are saying an element which is maximum in its first row and minimum sorry minimum in its row and maximum and its column right in that case we would say this is the answer all right so we have calculated minimums and maximums so from here what we can say what is the common between those two we could just easily select right so one approach is take common element and common elements and that's answer right but this will be fine right this will be fine as long as there as long as the duplicates are not there right as long as duplicates are not there so one could argue that even if there are no duplicates this method might really work so let's say if 3 9 15 and 15 16 so we calculated minimums in each row and maximums in each column right so whatever the common elements in these two those are the answers we could easily go ahead and say that right there might be some catchers like if there are right if there are what is a duplicates in the array that strategy may not work right so that strategy may not work so that's the reason why I am NOT going to go with that approach right so it the strategy may work or may not work so we will have to try through all the test cases that we have we are given here right this the reason why I may not go with this approach so this is approach one so you could go ahead and try and see what happens with the second that approach and the second approach that I am I have done here is so I go through the mattress again right I go through the matrix again and for each element and check if this is there in the means and max if so I'm good I am going to generator answer array and add our answer list and keep on adding to that thing right so that is so go through matrix again and check if each element is in both means and max at corresponding index so this is important thing at corresponding index so this is the reason why I was not going with the approach one right so it could work and cannot work but the code that I'm going to show is where the approach to right so let's go ahead and try to dive into the core so first things first get the number of rows and number of columns right and create the Romans and column max that's what we created here right and so calculate the Romans and calculate the column means all right so that's what we are doing here for each row calculate the Romans for each column calculate column and then once we have the Romans and column ministry so create an answer at list which we are going to return right go through the matrix again and this is what we are doing from 0 to R 0 to C go to the matrix again and after this right what we are doing is Romans of I is equal to matrix of I J and column means of J is equal to matrix of Isis so romans of I row it should be equal to matrix of I J and J column max it should also be equal to matrix of IJ in that case we are going to add answered our ad matrix of IJ right so that's the thing so this could work easily finally you're going to return the answer so one thing that we can say is just whatever the common elements between mins and Max that should be your answer but that's what also you could say right so you could keep on calculating the mins and when you calculate the max right so see if any values there in the mints so if so you just written right then end there so that's a that is one more approach that you can try and experiment with so let's go ahead and look at the time complexity and space complexity of this algorithm it's a time and space right so time so we are going through the array to calculate the mins and calculate the max and we are going to the matrix again to check the elements so totally we are doing the operation number of operations is equal to the number of rows and number of columns since I am calling the number of rows as are and columns is C so the time complexity for that will be ahdre are into c right so we are going through each row and each column so that is the time complexity and let's go ahead and try to understand the space complexity so for row means i need order of row plus order of column right because for row means and broken and for an answer it should be anyway anything ranging from zero to R plus C right so it could be the maximum is R plus C the maximum so it is actually it's not actually our plus C it is anywhere from zero to R plus C right so but in the worst case I'm just taking it as our maximum of our C that's the best thing right maximum of R and C that's the best thing in that case our privilege say makes sense to minimum right minimum of R and C right so the minimum of horan see that will actually make sense then maximum out of RN C so that's the space complexity for this particular algorithm if you have any questions please post them in the comment section below I get back to you as soon as I can if you haven't subscribed to my channel yet please go ahead and subscribe and also click the bell icon so that you get all my future video notifications also please share among your friends thank you for watching again either back with another problem from leadcore very soon till then good bye
Lucky Numbers in a Matrix
number-of-closed-islands
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:** \[15\] **Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column. **Example 2:** **Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\] **Output:** \[12\] **Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column. **Example 3:** **Input:** matrix = \[\[7,8\],\[1,2\]\] **Output:** \[7\] **Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= n, m <= 50` * `1 <= matrix[i][j] <= 105`. * All elements in the matrix are distinct.
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
110
Friends welcome again to my channel so in today's video we are going to see the balance by tree problem ok and earlier the problem we had seen was the diameter of binary tree which I have just opened and we have just completed it on the white board. I understood it and did it here also after understanding it. So guys, this problem of my balanced binary tree is based on my problem of diameter binary tree. Those who have not seen my problem of diameter of binary tree, then please see it. Because if I repeat the same thing again, the video will become very long, so to avoid making the video bigger, I am recommending you to watch my previous video, the link of which I will put in my description. Okay guys in the video, to see what is the balance of balanced binary tree, it is said that given a binary tree, determine if it is height balanced and not then what is the height for balanced binary tree, they have also given the definition of height. Balance Bindi Tree is a Bindi Tree in which the depth of two subtrees of every node never differs by more than one so what they are saying that if any node is any given node then its subtree i.e. this 20 If we look at the node, subtree i.e. this 20 If we look at the node, subtree i.e. this 20 If we look at the node, its subtree i.e. on the left and its subtree i.e. on the left and its subtree i.e. on the left and on the right, the height of the left subtree and the right subtree should not be more than one. If it is more than one, then it is balanced. It is not a subtree. If it is not more than one, then it is a subtree. So guys, let's look at this example. Here, if we look at three threes, then the height from the left is one and the height from the right is two. What is the difference between the two? 2 minus if we are doing 1 - 2 also difference between the two? 2 minus if we are doing 1 - 2 also difference between the two? 2 minus if we are doing 1 - 2 also or if we are doing 2 - 1 then we are getting one. Okay, if we or if we are doing 2 - 1 then we are getting one. Okay, if we look at the sign later then we are getting one, so this is not our more than one, so this is our What is balance mind tree, that's why they have written two. Let's see in the second example from here, we see tooth from anywhere. Okay, from anywhere we will see natu through okay guy, so from here you can see the maximum height which is from our left. Okay, that is our three and right. What is our one because there is only one node going, ours is 3 - 1, that is only one node going, ours is 3 - 1, that is only one node going, ours is 3 - 1, that is, our height is coming to the entire overall tree, so what is ours, it is not our balance because there is more than one, which is Two is ours, so I hope guys, you have understood this, then you are seeing that the concept of height is coming here. Okay guys, so we need height from left and height from right, so height from left and right. How to find height Also, if we have to see the node in that subtree, is it our balance or not? Okay, it can be anywhere, it can be in the middle of yours and it can be anywhere in the entire tree, so where are you getting that balance? No, all this tree is mine or the tree is my balance, from there we have to tell that it is not our balance. Okay, so for that we have to find the height and right side from the left. If we find the right side from the left, then we will make a function. Guys, here I have to return height, so I definitely want to return it, so I take it here, I create a method named height, get height, let's get height and here we have this tree node root. Couldn't we have copied this into this because all our values ​​will be of this type. Okay, now let's make this root the base case, all our values ​​will be of this type. Okay, now let's make this root the base case, so what will be the base case if we assume this is the last node of mine. Okay, what will be its height? Otherwise, the tree on the left. There is no node on the right. There is no node on the left. There is no subtree on the right. subtree on the left. There is no subtree on the right. So what happened? Its height became zero. Okay, because it is not there on the left and right. So 0 My 0. What will happen? Zero will be the base case. So what is the base case if any of my nodes is zero then what will we return zero if root into null then return zero guys ok if mine is not zero then what will we do we will take out the left side first then int left and To find out the left side, we will have to do it again, we will have to get the get height, so we will copy the get height and paste it again and here we will call b, root dot left. Looking at this, if we will get the left side of four, then root dot left. We will do OK and enter right and we will call the same method in right also because we have to use rec from right also, so right and what do we do in this, we have to see what is the difference of the height that I have got from left and right, maximum. If it is more or less then what will we do for that, we create a result or on global int result and by default we put minus and or zero minus and in it. Okay guys and inside this we will update the height difference which will be the height. Okay, so what we have to do is to find out the difference, so to find out the difference, we will do int difference, we do it and here we use a method, we do math dot absolute, okay, so by doing ABS, its method is absolute, so this is What it does is if our sign is coming minus then it makes that value positive because we do not know whether the value is coming more from the left or the height is coming more than the right so if the height is coming less than the left then it will be more than the right. If it is negative then our result will be in minus, so if we make it positive then what to do, left minus right, you can also do right minus left, here both will work because we have used this method, in this we have to make this sign positive. Will give our OK, now what we have to do is to update the value in it because right now we will not be able to return from here because it will go in the stack, all the resources are ours, so whatever call is made by all, we will go to the first stack and the entire resource will go to the stack when the stake is over. Then what do we do with that result? Whatever result is coming, we include it in the result so that later when our stake goes ant, then we can make whatever final call from this result. So after doing our return, we will check that the value is positive negative and then from there we will return the final result. Okay guys, so now we update the result here too. Result is equal to y math dot max. Because we want max result, max value, only then we have to do false, if other wise is less then there is no problem, so here we do the result and here we calculate the difference from left and right side of both. And finally what we will do here is we will return the height of the tree okay note whatever we got from the left and right so what we do for that is math dot max a max and from here we will return the height of the left and right subtree which Also our max is that plus one his height plus one ok guys now everything is inside my result so what will we do for that first of all copy our height here and call it because from here all our We will hide some height, from here all our calls are being made, everything is being calculated and we pass in this the first note that is a root note and what will we do in the return, all this is happening here as soon as we have this get height. The stake will be exhausted and everything will be returned, so this is our final return here, okay guys, and we will get a height there, the type of the site is not used yet, but it is being used in the calculations inside, here we return. Let's do the final return now, we will return the result which we have updated, so the result is sorry, we will not update the result, we will check the result if our result is more than one, because more than one should not be ours, as if the balance has said that it is more. It should not be greater than one. If R is more than one then it means it is not my balance then I have to return false. If it is not more than one then I will return true. If the result is greater than one then it means it is not my balance. If yes then I will return false otherwise I will return true o guys just submit it and let's see if I have made some mistake in writing ok so guys this has just been executed and run I mean now I submit it So this guys, my submission has also been done, so I hope guys, you must have understood this problem and those who have not understood well, how do we calculate height, what is the procedure, then you can see one of my problems, diameter of The binary tree on which this problem is based, on the basis of which all our next two-three problems have been all our next two-three problems have been all our next two-three problems have been done, is the diameter of the binary tree and the max depth. If you look at the one with max depth, then the one with max depth or any one of the diameter and binary tree. If you can watch then you will understand this problem so if you like it then Kindly subscribe my channel and press the bell icon bye
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
504
hello everyone so in this video let us talk about base 7 problem from lead code the problem is very simple that you are given an integer num you just have to return a string of your particular number in base 7 representation now uh if you know how to represent in binary form or any particular form it's very simple what you'll do is that if you want to convert a number to a particular base format you just keep on dividing that number but for from that particular number so if you want let's say base seven keep on dividing that particular number with 7 and whatever remainder is that number keep on depending that okay and then keep on dividing that number with 7 until it becomes 0 and that's it whatever numbers you have got throughout this whole process is just the representation in base 7 format uh in negative form just remove all the negative part and then again just convert it to the base seven and just append negative sign that's overall Logic for this particular problem let us take one small example let us say 100 let us understand all of that so what we'll do is that let's say we take 100 now what you'll do is that you'll divide it by seven let us take a small number because I have to do this a lot of division but let's say if a is the closest with 7 is so 7 goes with seven one just seven three is that 728 so the first remain so as you can see that it's it goes with 14 times but a remainder of 2 so first you'll take two and then the remainder is 14. so now you'll come from 10 to 40. and the remainder is 2. now again divide 14 by 7 and what is the remainder it's 0. okay and then what is the dividend like what is the one that is on the top that is 2. so not 2 divided by 7 the remainder is 2 again and the top part this number is zero so when it becomes 0 then whatever the part that you have as the remainders is the actual representation but it should be reversed okay because 2 0 2 is same but it should be reversed so answer is two zero okay that's the whole thing that you have to do is that I hope you understand the logic part but you have to reverse the order actually also in the end okay so the ordering should be 2 0 2 but it should be from the back to front has a little thing so let us talk about the code part now it's pretty simple I hope you understand all of that now so we have nums of zero if the number is zero then the answer is obviously zero uh nothing much we have to do about it so we have to find out the answer we just have to check out first that whether the number is negative or not if it is negative just to that it is a negative number and just make a number as positive okay so that in the end I will append a negative sign you don't have to do anything while the process of dividing okay don't I don't want negative sign in there so what you can do is that you can just first check out that whether the number you have it can be negative also if it is negative just know that it is a negative number and just make the number positive so that you have a stored somewhere it is negative number now what I'm doing is that I am using a while loop until it is not zero if it becomes 0 to a breakout of this value what I'll do is that I will find out a mod okay so mod is num mod 7. when I do this I will get the remainder of that portal number divided by 7. I will get the remainder so I will add a personal remainder in answer and then divide the portal number with 7 and keep on doing that until we can become 0. after that what we'll do is that we have the numbers now I will insert that if it is it was a negative number then I will put your negative sign here as well in the end I'll just reverse out the whole number because I just want that which I've told you the answer is that if you have also found binary numbers also the remainders you get from top to bottom but the answer is printed in from bottom to top manner which is like reverse so in the same manner whatever Windows you have got you have added from top to front but you have to print it from back to front so you just reverse out all the uh numbers or modular signs stood in the answer first thing and then just print out answer so that's it uh nothing much complicated here as well also you just keep on doing that solution exponential tangency problem because you keep on dividing it by seven and that's it that's your logic and the code part for this particular problem as well if you still find it off you can mentioned in the comments of this particular problem thank you for watching video till the end I will see you in excellent recording and bye
Base 7
base-7
Given an integer `num`, return _a string of its **base 7** representation_. **Example 1:** **Input:** num = 100 **Output:** "202" **Example 2:** **Input:** num = -7 **Output:** "-10" **Constraints:** * `-107 <= num <= 107`
null
Math
Easy
null
297
hello everyone welcome to the channel today's question is serialize and deserialize binary tree the question says serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer or transmitted across a network connection link to be reconstructed later in the same or another computer environment so this was the definition of serialization a question says design an algorithm to serialize and deserialize a binary tree there is no restriction on how your serialization and deserialization algorithm should walk you just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure so we are given with the example and as it is mentioned in the question that there is no restriction on how our serialization and deserialization should work so it's up to us whether we want to take this exact example or not so let's move on to pen and paper let's see with an example what question says and how we can solve this question after that we will see the code so let's see how we can show this question I have taken an example and this example is not similar to the example we have in the question why because I am sending this question in pre-order it is mentioning the question pre-order it is mentioning the question pre-order it is mentioning the question that we can solve it in any way pre-order in-order or post order so I am pre-order in-order or post order so I am pre-order in-order or post order so I am solving this question in pre-order so solving this question in pre-order so solving this question in pre-order so the question here is that if I am given with this tree I need to convert it into a string and if I am given with this string then I need to convert it into a tree and I need to perform both of these functionalities in this question so first of all we will look at serialize serializes we are going to be that tree and we need to convert into a string so will we will solve this question recursively and for recursively we need to have some base case and one more thing if you look at this function serialized where just one parameter which is route but we also need to get enough strength will make a helper function so let us name it help save lives and we are gonna pass route and a string and this string will gonna be in empty string what will one of your base case if root is none suppose we don't have a tree or we reach at a position where we don't have a root then we're going to add none to our string so our string will gonna be shrink plus none so this was gonna be our string okay we are done with our base case what next if you have some value associated with our root then else our string will gonna be string equal to string plus value but we need to take care of one thing here that thing is it should be a string value not an integer now we will perform this function on the left side and on the right side and at and we will read in the string and now we will call this function in our serialize function return itself dot help serialize and we're going to pass route in a empty string so now we are done with our serialized function now comes the second part when they'll give me the string and we need to convert into a tree so we are with this function and we are going to be the string first of all we need to convert that string into a list for that we will use spread function so we're splitting the string at the coma now we will make a helper function for our deserialize and we will give it a list again for the recursive function we need a base case for that if new string at index zero is none that means we don't have any rule oh so if this is the case that means we have reached where Widow dawa fruit or we are in the end of the tree so we will going to pop it new string and we will use a power function and we'll pass the index 0 and we will simply written now if this is not the case then our root will gonna be tree node and this is giving the question new string at index you and then now we are going to pop it again we'll perform it on the left side and the right side and at then we will simply writ in the room and now we will use our helper function in the main function now root will be equal to self toad helper deserialize and we will return row so this was the question and now let's see the code so we have four functions so I made this helper function and this helper function so initially we have serialized function so let's look at help us I realize first of all we take care of the base case if root is none then we will simply add non 12-string then we will simply add non 12-string then we will simply add non 12-string else we will add root dot value in string form to our string then we will take our helper function and we will work on the blue boat left and root dot right and at then we will return the string will call our help us utilize function in the main serialize function and if you look at this is lies first of all we are going to convert the string into list then let's see what we'll do in our helper function if value at index 0 in the string is none then we're gonna pop it and we will do nothing else we will gonna take the value at index 0 and we'll make it a tree node and we'll put our root equal to that then we will pop it and in the same way we will keep adding the values on the left side and we keep adding the value in the right side and then here we call the helper function in the main function and we will written the row so this was the code if you will copy this code and paste it on leet code it will happen to be on a wall thank you so much guys for watching the video please don't forget to subscribe please give it a thumbs up thank you
Serialize and Deserialize Binary Tree
serialize-and-deserialize-binary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. **Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. **Example 1:** **Input:** root = \[1,2,3,null,null,4,5\] **Output:** \[1,2,3,null,null,4,5\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
271,449,652,765
984
hi guys this is another nickel problem called string without aaa or bbb given two integers a and b return any string s such that s has nest in plus b and it consists exactly a letters in definitely b d letters the sub screen a does not occur in s the substring dbb does not occur in s so for this example a equal to one b equal to two so we can output a b a abb bab or bbb are all correct answers for this one well we cannot have a or bbb so this is the solution a b is valid so yeah basically for this problem that it's kind of greedy like if a or b is greater or equal than 2 each time we just output a or bb so let's use that everything reading to solve this problem finally we firstly we have a stream buffer to store the strings that generate strong a and b so we use stream buffer and then we just do probably a and b a greater than zero and b greater than zero so here if a plus b uh a greater than b which means that a is at least two so each time we can append the two a's and append one b because b is greater than zero so after that we just minus a with two and b minus is one so else here we know that is a less or equal to b first thing we need to check if a equal to b and if a equal to 1 which means that a and b are both wrong in that case we just append a append one a and append the one b and then a minus plus one b minus plus one and then we continue here if a just less than b which means that b is must be or equal must be greater or equal to two in that case we just append one a but we can advance to b here because b is greater or equal to 2 here we just a minus plus minus 1 b minus or equal to 2 and we continue this loop until either a or b equal to zero so if b equal to zero a log equals e zero is still greater than zero then we just append each time append one a and a minus while if a equal to zero b not equal to zero which means that well here is a trick because we because the general string must start with a so to be safe we just insert b to the beginning of the screen of the generated string so we just insert b and b minus b is either one or two so with this while loop at the beginning of the generated stream buffer they'll add both the two b's in the beginning and finally we just return the stream buffer to stream and that should work let me try that doesn't work okay it's the low case b not an uppercase b let me try again that work the stuff me okay guys so that worked it should be a hundred percent right let me try again okay never mind okay so guys ideally simple we are greeting we are using greening algorithm that if a is greater than b which means that a is at least greater or equal to 2 so in this case we add two locus a's and just one b if b is greater than a then we are greedy we add at least the two b's and just the one a because a might be just one and what end with this loop until we're doing this until a or b is equal to zero if b is equal to zero then we just add adder the rest add the a add the rest of one or two a's to the end because the because when we do this the end character must be b so we append a to the end of the stream buffer that is safe but if b is not equal to zero b is one or two we should insert it to the beginning of the screen to be safe because the beginning of the screen must be aaa or a and finally we convert stream properties screen and that works let me know if you have a better solution thank you
String Without AAA or BBB
most-stones-removed-with-same-row-or-column
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:** "abb " **Explanation:** "abb ", "bab " and "bba " are all correct answers. **Example 2:** **Input:** a = 4, b = 1 **Output:** "aabaa " **Constraints:** * `0 <= a, b <= 100` * It is guaranteed such an `s` exists for the given `a` and `b`.
null
Depth-First Search,Union Find,Graph
Medium
null
316
today we're gonna be working on lead code question number 316. uh it's called remove and duplicate letters uh given the given a string uh s i remove duplicate letter so that um every letter appears once and only once you must make sure your result is the smallest and lexico graphical order uh among all possible results so if we have been given this b c a b c uh the answer is gonna be a b c uh we cannot have b c a the reason being b bca is not like the smallest in the lexicographical order now we are looking for a smaller element at the beginning then b which would be a and then abc would be the best option we have uh the way the algorithm is going to work is that first of all we need to make sure that we keep record of the last occurrences of uh all the uh of all the characters used in the uh in the string uh so it's gonna be uh this operation is gonna be uh it's gonna be linear uh time complexity we can like in linear time we can actually uh calculate what is the last occurrence of uh every character inside the string so for that uh we're gonna say that we're gonna be using because uh we know that these are only the lowercase english letters so we can hardcore the size of this last index equals to new end of 26 okay and then we're gonna go through and i equals to zero i is less than um s dot length i plus okay uh we're gonna say that the last index um s dot character at i minus a is gonna give us uh the value and that's gonna be the index and it's gonna overwrite uh if it finds a new one it's gonna overwrite that particular uh index of that elastic index so we are good over there uh other than that we're also gonna have that um we're gonna keep track of if we have seen this element or not before so for that we're gonna say uh scene we can use it as a boolean array new boolean again of size 26 as we have only lowercase english letters okay now we're gonna have a stack now which is gonna be a stack of integer let's call it st and it is gonna be new stack okay so we're gonna iterate through all the characters and the string okay so that our current character is gonna be equal to s dot character at i minus a okay so first of all we want to say that have we seen this character before or not if that is the case right if we have seen dot contains uh actually sorry scene and then the current character is that true or not if that is true meaning we have already seen it we want to just continue if that is not the case we haven't seen this before what we're going to be doing is like we're going to be looking into that uh first of all we want to check that if the stack is empty or not right now if the first of all if the stack is not empty right uh again let's just say that if the stack is empty right so the first thing is that if the stack is empty what happens if the stack is empty uh we don't want to get into this while loop all we have to do is to push this element uh into push this uh the current uh current integer which is basically the string represent like the integer representation of that character uh into our stack and we want to say that the scene of that current should also be true that's it okay but let's say if this track is not empty right and we peak it and when we peak it right that peaking value is greater than the current value right there is one thing and there is one thing we want to do something on that and at the same time we already have seen that value i is greater than sorry i is less than last index of s t dot peak if that is the case if we our stack is not empty and when we peak it in that peaking value is greater than the uh the current value right and then we also wanna make sure that uh okay it is greater than the current value but that value is the last index of that is actually greater than uh the current index only then we're gonna be removing uh we're gonna say that scene we're gonna say that first of all we're gonna pop it right once we pop it that element we also wanna say that uh scene of that the element we are popping from the stack uh we also want to set it to false that okay man we haven't seen it yet uh as we already know that we will be seeing it later on as the last index is greater than the current index so once we are done with this one we are done with our uh i like we have iterated through it uh all we have to do is to get all the elements from the stack and create the string builder sb is equal to new string builder okay while the stack is not empty now the stack is not empty sb dot append as a character okay s t dot pop um plus because that was uh like an integer representation of a character we're gonna change it to character and then put it into the sp and then just before returning it we're going to be returning the reverse of it as we were at as we were putting it into the stack uh we have changed the order so we're going to say reverse and then to string okay looking good and it works
Remove Duplicate Letters
remove-duplicate-letters
Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results. **Example 1:** **Input:** s = "bcabc " **Output:** "abc " **Example 2:** **Input:** s = "cbacdcbc " **Output:** "acdb " **Constraints:** * `1 <= s.length <= 104` * `s` consists of lowercase English letters. **Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)
Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i.
String,Stack,Greedy,Monotonic Stack
Medium
2157
922
welcome to september's leco challenge today's problem is sword array by parody 2. given an array of integers nums half the integers and nums are odd and the other half are even now sort the array so that whenever num's i is odd i is also odd and whenever nums i is even i is talking about the index number return any answer array that satisfies this condition so if we had an array like this 4 2 5 7 we can see 4 is in the right place because 0 is an even number but 2 is not because this should be an odd number 2 is even but the index number is odd right so what we're going to do is swap that with this number 5 because 5 is also odd but it's in an even index number so if we swap those two 5 and 2 everything else should be in place now you can also return in these orders but the thing is they want us to do this in place so we can straight up go to the in place solution what we're going to do is have two pointers one pointing to the first even index number so we'll call this e and one point to the first odd index number this will be o so what we'll do is check to see all right for this even index number is this number even and we can see it is even right so what we'll do then is move ahead this e pointer two spaces so that it's at the next even index now we'll check this number and see hey is this odd or even it looks like it's odd so what that means is we're gonna have to swap this with some other number that's also on an odd index number but it's even so here with o we'll first check hey is this index number uh or is this number odd because it should be odd but it's not right so what we'll do is swap these two and then we'll continue our algorithm we'll say okay even go to the next one and at this point it reaches the end right and at that point we should assume that since every even number has been accounted for all the odd numbers are also in place so we can end our algorithm right there all right so let's have an l or call even and odd index numbers and this will be zero and one we'll also have to have n which is going to be the length nums so while e is less than n and o is less than n we're going to have two while loops here we'll say for the even number while e is less than n and let's see we're going to check our number here nums e we've got to make sure that this is even so as long as it's even we are going to continue and add 2 here and we're going to do the same thing for odd except we want to make sure that this is odd right not even so all we have to do is say don't does not equal zero and oops so at this point if we are still within this array we want to swap the two so we'll say nums of e and nums of odd let's swap them oops finally at the end we should make sure to increase our pointers again just so we do get into an infinite loop and finally return nums itself because it should have been sorted in place okay so let's make sure this works four five two seven that looks correct and there we go so time complexity wise it's going to be o of n and space is going to be constant because we only modify the list given to us now there are some variations to this but really they're all basically this if you didn't have to do it in place it would still be pretty similar we would just be appending these numbers into some sort of other output so really this is probably the better solution anyway all right thanks for watching my channel remember do not trust me i know nothing
Sort Array By Parity II
possible-bipartition
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
1,348
well I'm going to do problem number 1,348 of the it code which is called twitcams 1,348 of the it code which is called twitcams 1,348 of the it code which is called twitcams performance and what this problem is about is that you have to teach a class that does certain things with the tweets so to speak we are going to have the class of twitcams that will to have a good constructor that we are not really going to use the cuts tweets function to which we are going to pass a tui name that is a twitter user so to speak and a time a meeting is from when he put it and that is we are going to have a function to which we are going to send a single tweet er a frequency that will be minutes hours or days and true this time range so well it is a bit far-fetched the so well it is a bit far-fetched the so well it is a bit far-fetched the truth is that this problem they put the 239 contest on it seems delicate to me no It just happened a few minutes ago and all of our programs, if you realize it has almost all hands down, then it's a little confusing. What it's about is that we're going to be posting the tweets. It's simply the username and the interista and the one. What we have to extract is to return a list of integers where each previous decade represents the number of tweets that were sent in a certain interval at a certain frequency during a time interval until it is a little confusing but we will understand the code better later the first thing we What we have to do is the function to store the tweet and to do it we go to a smart and it will have a string that opposes the name of the user and a list of interest with which the times expanded each of the tweets and ok then when they see the tweet what we are going to do is create the inner list here we go to the function what is it called is kitsch default this is not good to use the auto complete but good ability the name of this thing where we are going to use whitney or if it is not there if it is so if this comes out twitter has not uploaded any message then we are going to return united register of interest since we have it ready we are going to add the time and then we put it on the map again I have seen this is this very simple function the next function is where is the trick where is the problem then the first thing we have to do is bercy creates a function to perform the action result where to start it is an idea to create what the whole structure where the variable where they are going to return the response made like you It helps to organize a little and here we have frequency on the train I am thinking that if the user does not exist then we have to return 10 so it is during we jump that to me approving it is good if the tweets already exist and if we already have tweets with the name of this wow then we are going to pull the and times and here the interesting thing about this matter is how and to shape the answer because it is telling us that we have to be in a certain period at a certain frequency so for that yes for example always values ​​the starting time always values ​​the starting time always values ​​the starting time for states in seconds the time is also taken in seconds but if they ask us, for example, to return it in intervals of minutes, hours or days, we have to see how we are going to create those intervals then because those intervals we are not going to be an arrangement where we are going to put them yes and those intervals are going to be given well but we analyze a factor for example if of seconds then each interval is going to be six minutes then each interval is going to be given in 60 seconds then we must divide einstein - starts time by 60 and león is called factor 1 only because it could be zero and well then how are we going to give this factor for deforestation where a 60 because it is the number of seconds that in a minute but if the frequency and which was to our then factor we are going to multiply it by 60 and in days now then it will be by 60 on 24 ah although and now simply then what good thing we are doing here for example if you give us a period of time, for example 120 seconds, they tell us how many tweets this user sent per minute between second 0 and second 120, so 120 is two minutes, so we are going to take it in periods for each minute, that is, we are going to deliver a list with two integers. What do you feel I find out for minute one and one whole for minute two where each of them is going to do the count per minute the count of tweets per minute if it were per hour in three we just have to do just one just because in the two minutes of the second 0 to 120 because they are within the first hour because the first hour has 3600 seconds unless they told us that he tweeted something in the second 5,790 then it is already two the second 5,790 then it is already two the second 5,790 then it is already two hours so we have to give two answers the same with the days So we are taking out this factor to precisely take out the intervals, for example, if between start time in time there are 2 minutes, with this we are taking out an arrangement of two members where in each member we are going to put the sum of the tweets that were made in that minute. then and now we are going to start having times and then it has another important condition if te is greater than enters is less than being time then we should not grab that otherwise we are going to grab intervals and here in the interesting logo also thanks r2 to gain time - start time thanks r2 to gain time - start time thanks r2 to gain time - start time to know at what point in which interval of the many intervals that we have, well, it could be a single interval, we are going to put this one, so for example, if they ask us for 0 to 120 minutes, seconds are not two minutes and we are taking it per minute if this tweet was in seconds 10 then what is 10 - 0 between the factor that 60 is going to 10 - 0 between the factor that 60 is going to 10 - 0 between the factor that 60 is going to give us the cause of where it will be before so that in the first interval the opposite case would be if it were not one minute If it is 90 - 0 / factor that it sits, it is 90 - 0 / factor that it sits, it is 90 - 0 / factor that it sits, it is rounded to 1 then it is in interval 1 which would be 2 because we have the inter-10, would be 2 because we have the inter-10, would be 2 because we have the inter-10, it is a patient from William's century but it is not complicated at all and then since we have our interval full with this more difficult way of doing it, the truth is that the most happened ah let's examine our result with what we have and let's go with 3 and for a change it doesn't work because it doesn't work it works for this use case let's see if it works for the case of faith that comes here for nothing because I think that when it is zero we have to return a zero and we are not doing it, that is, when a person had not tweeted we inserted this I don't know looking for tweets from a person who does not exist I come back like this we must return an array with a 0 and a null arrangement but let's see now if it works, it is very efficient but there it is
Tweet Counts Per Frequency
tweet-counts-per-frequency
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **seconds**) would be partitioned into the following **time chunks** with these frequencies: * Every **minute** (60-second chunks): `[10,69]`, `[70,129]`, `[130,189]`, `...`, `[9970,10000]` * Every **hour** (3600-second chunks): `[10,3609]`, `[3610,7209]`, `[7210,10000]` * Every **day** (86400-second chunks): `[10,10000]` Notice that the last chunk may be shorter than the specified frequency's chunk size and will always end with the end time of the period (`10000` in the above example). Design and implement an API to help the company with their analysis. Implement the `TweetCounts` class: * `TweetCounts()` Initializes the `TweetCounts` object. * `void recordTweet(String tweetName, int time)` Stores the `tweetName` at the recorded `time` (in **seconds**). * `List getTweetCountsPerFrequency(String freq, String tweetName, int startTime, int endTime)` Returns a list of integers representing the number of tweets with `tweetName` in each **time chunk** for the given period of time `[startTime, endTime]` (in **seconds**) and frequency `freq`. * `freq` is one of `"minute "`, `"hour "`, or `"day "` representing a frequency of every **minute**, **hour**, or **day** respectively. **Example:** **Input** \[ "TweetCounts ", "recordTweet ", "recordTweet ", "recordTweet ", "getTweetCountsPerFrequency ", "getTweetCountsPerFrequency ", "recordTweet ", "getTweetCountsPerFrequency "\] \[\[\],\[ "tweet3 ",0\],\[ "tweet3 ",60\],\[ "tweet3 ",10\],\[ "minute ", "tweet3 ",0,59\],\[ "minute ", "tweet3 ",0,60\],\[ "tweet3 ",120\],\[ "hour ", "tweet3 ",0,210\]\] **Output** \[null,null,null,null,\[2\],\[2,1\],null,\[4\]\] **Explanation** TweetCounts tweetCounts = new TweetCounts(); tweetCounts.recordTweet( "tweet3 ", 0); // New tweet "tweet3 " at time 0 tweetCounts.recordTweet( "tweet3 ", 60); // New tweet "tweet3 " at time 60 tweetCounts.recordTweet( "tweet3 ", 10); // New tweet "tweet3 " at time 10 tweetCounts.getTweetCountsPerFrequency( "minute ", "tweet3 ", 0, 59); // return \[2\]; chunk \[0,59\] had 2 tweets tweetCounts.getTweetCountsPerFrequency( "minute ", "tweet3 ", 0, 60); // return \[2,1\]; chunk \[0,59\] had 2 tweets, chunk \[60,60\] had 1 tweet tweetCounts.recordTweet( "tweet3 ", 120); // New tweet "tweet3 " at time 120 tweetCounts.getTweetCountsPerFrequency( "hour ", "tweet3 ", 0, 210); // return \[4\]; chunk \[0,210\] had 4 tweets **Constraints:** * `0 <= time, startTime, endTime <= 109` * `0 <= endTime - startTime <= 104` * There will be at most `104` calls **in total** to `recordTweet` and `getTweetCountsPerFrequency`.
null
null
Medium
null
273
hello friends now let's try to solve the integer to English words okay convert a non-negative integer to English words non-negative integer to English words non-negative integer to English words representation given input is a guaranteed to be less than 2 to the 30 one minus one see example 123 the choctaw enter 345 and this is 1234567 and this should be 1 billion 234 million five hundred sixty seven thousand 1891 how do you think about this problem I think it's like a simulator how we read these numbers you will see actually we read them three digit by three digit so we can approach them straight into the passage and the only difference is the thing after the three digits say this is the one median this is the median and then we really there are 234 and we appended this thousand and the final is 560 say that so this is our approach we read a three digit by three digits and then we append the bigger units such like in their thousand media and the PDF okay let's code actually I a little bit a cheater I write on these thousands less than 20 tenths advance because I think that if I called anyone be much below and I said a way neither the big units there is a thousand media and the B do the 0 planes should it be empty why because then I will be easily over 1001 Salander over what an hour get one so I will directly the L sound and then the media so yes it will be more simpler for us to implements the function and we also made at least 20 because if the less than 20 we should read them loud and the 10 22 or 34 so on faucets so we should write them down okay yes employment this function H case check never forget if the number equal to zero will just a return zero right okay this is the true relation problem so we may think about use the string judo and we also use a needle in that's why because we should err to handle the things after the three digits at the billion media salad and a way start from there less sugar to the more to a smaller item to the larger item so we do the look while the number not equal to zero or it of course and they're asking in passing its SM if the number mojo one sont not equal to zero we shall handle this is three digits right and we used insert why because index starts from zero so we read the very small thing to the very last thing so we insert use insert and though we will use a temporary stream Buddha why because we want to handle the three digits use another function there's a help function it's temporary spoon-billed in it's temporary spoon-billed in it's temporary spoon-billed in the number module one salad then we insert that now we get the temporary and a we use temporary and we should hand that you see it have this y space or a panda Y space but which refers a pen they're the south-south index and we they're the south-south index and we they're the south-south index and we appended the space white space and every time we should do it des plus and we also update the number equal to number divide the ones out and finally we reach enter string do it choose three and do not forget you remove the leading order ending were space okay let's implement this help function with the screen builder speed and we also have the number okay let's increment if the number equal to zero we definitely just a return with star Thrones our smoke to a large it's a number less than 20 what is your week to go just SPF handle the last 10 20 the number okay and I do not forget your app and there's a white space and a we return okay how about a little number less than 100 because these case we make a pendant tents right so let's be appended it's less than 100 so should attend the third tenth there are number over 10 and the we append the white space now we do the helper s be the time number dojo tap to go like sir 94 we get to the 90 and we only going to handle the 4th so ammo georgette else if it's larger than 100 the only higher Crandall straightedges if the larger they're 100 who should a candle like sure because satellites are 345 so we will get to the less then 20 that number over 100 and then we append the hundred ohms have space right okay let me handle the say the 345 so we are handle a state number mojo 100 okay is that our help function it's it I think we have finished that just see if we are correct okay we are correct so okay thank you for watching happy coding see you next time bye
Integer to English Words
integer-to-english-words
Convert a non-negative integer `num` to its English words representation. **Example 1:** **Input:** num = 123 **Output:** "One Hundred Twenty Three " **Example 2:** **Input:** num = 12345 **Output:** "Twelve Thousand Three Hundred Forty Five " **Example 3:** **Input:** num = 1234567 **Output:** "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven " **Constraints:** * `0 <= num <= 231 - 1`
Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out)
Math,String,Recursion
Hard
12
38
let's hello morning count and say if think yeah i've done this okay let's see how i did it counter say is a sequence of digit strings defined by the recursive formula um okay count say one is gives you one count say with an n is the way you would say okay the digit string from uh count and same n minus one which is then converted into a different digit string okay that's descriptive to determine how you say a digit string let's put it into a middle number of groups so that each group is a continuous section of all the same character then for each group say the number of characters then say the character convert the saying into the string replace the counts with the number and concatenate every saying the conversion and digits the saying and conversion of digit string this um gives you there's two threes three twos one five and one okay that makes sense so is that how is that what the output should be if i pass it into count and say well okay counselor returns a string okay but then what's the recursive relationship like you pass in the string and that's what it returns ah so at some point it's like depth first search so if you do um count five then that means you need to pass four that means you need to pass three and two and then eventually get one and you start going back up and they're like right so there's one i don't know when you get to one it's a one and then to the function that get the function the recursive call that received to will call one which returns it one string and then the two will count and say whatever is returned from the one from this call below and you're like all right that's uh that's one there's one there ah yes and then this one would be like all right there's two ones there and then this one be like okay there is one two and one and this one will be like there's one and there's one two n is two ones so four is one two one exactly right so all we have to do is have a base case if n is equal to one and return um one otherwise um string say is equal to count and say n minus one then i need to convert this whatever this is into this um how do i do that well i just need a while loop i guess yep while loop would do start from zero so while i is less than uh state of size i want to go through and be like and j is equal to zero while and char c current is equal to say at i and while j is equal to current now while say at j is equal to current then increment j then if i then i could do j minus i to get the length of that and also i could say all i is less while j is less than zero size and this um if j is minus i um convert that to a string so like to string and i want to append that to well it gives me a num that gives me a char right so that's a number so if i add a to that i could do it result dot pushback this char um but i want it to be zero indexed length wait a sec it should be zero yeah now zero plus that and then result i push back whatever the current is and then return result it should be a string all right let's try two please be one oh um okay and that's because i'm not incrementing i oh wait a sec i can make it more efficient that's like n squared if i make i is equal to j that will also work all right let's do three so that should be two one yep and let's do four you're kidding oh that should be i oops there we go um and also five and what's the highest input here 30 oh beautiful thanks for watching and subscribe see you next time
Count and Say
count-and-say
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula: * `countAndSay(1) = "1 "` * `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string. To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit. For example, the saying and conversion for digit string `"3322251 "`: Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_. **Example 1:** **Input:** n = 1 **Output:** "1 " **Explanation:** This is the base case. **Example 2:** **Input:** n = 4 **Output:** "1211 " **Explanation:** countAndSay(1) = "1 " countAndSay(2) = say "1 " = one 1 = "11 " countAndSay(3) = say "11 " = two 1's = "21 " countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 " **Constraints:** * `1 <= n <= 30`
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
String
Medium
271,443
5
longest palindromic substring is a quite easy problem especially if you have some experience in competitive programming we were given a string s with lengths up to 1000 and we should find the longest palindromic substring a substring which is a palindrome so it reads the same backwards first let's think how to check if a string is a palindrome we can reverse a string which is quite is in many programming languages and then compare the two strings the initial one given one that we want to check and the reversed one if they are the same we have a palindrome and for this one we would reversed have ECC e and here we have equality this means that ecce is a palindrome this was one way the other is to compare characters one by one indices are usually from 0 to n minus 1 and we need to compare 0 with N and minus first then first with n minus first minus 1 generally I've with n minus 1 minus 5 and we can iterate with I from 0 to n over 2 or just from 0 to n minus 1 then we will repeat some comparisons but it's ok the complexity of both these methods is just off and either we iterate with for loop over n elements and every time we do one comparison or we reverse the string this is off and also comparing two strings is often where n is length of a string quick look at pseudocode for above these methods either we compare us with regards occurs or we iterate with I and compare check if two characters are different the slowest solution for this problem will be to check for every substring if it's a palindrome and if yes save it as a possible answer I will remember length of a string and now for every left bound let's call it uppercase L from 0 to n minus 1 and for every right bound from L inclusive because maybe it's just one character in particular one character is here I meant till n minus 1 if one character sub string is a palindrome R + + if this is a palindrome R + + if this is a palindrome R + + if this is a palindrome from L to R as substr comma and here in C++ we should give length of this thing C++ we should give length of this thing C++ we should give length of this thing that we want to take substring if this is palindrome of that then we consider that as an answer if just if we were just looking for the length I would say answer is max of answer and R minus L plus 1 but we also need a string we need to save a string so I will say int past length westland is 0 string best s is just empty and here if R - ow is just empty and here if R - ow is just empty and here if R - ow L plus 1 is greater than bestland then vast land update and this is as subs so because I reuse it let's save it this is subs is as sub days also why not save the length now the code will be a bit nicer even though the number of lines increased if this is a palindrome and length is bigger I can just put it here and land is greater than Westland then I update Westland Islam and best as is substring at the end return best as I can run this just to check if it works for the sample test but the complexity is off and for this part later it over left hand right and this is already in square and every time inside I use is palindrome which is linear as well so it's an you big and to the third power it worked for the sample test I can submit but I expect time limit exceeded or maybe accepted with very big crank time and this shouldn't be this is for sure not expected in this problem I got time not exceeded it will be slightly faster if I put a comparison of length first because C++ has lazy if of length first because C++ has lazy if of length first because C++ has lazy if conditions so if it are this is that the first one is not true that we will not increase the length then it will not even run the second check if you write something like if condition1 and condition2 in c++ and condition1 and condition2 in c++ and condition1 and condition2 in c++ and condition 1 is false then compiler already understands that this cannot be true in total so it will not check it the second condition this should be slightly faster but doesn't change the complexity from time to time something like this will change the complexity in some problems because you can prove that only this second thing will be run some number of times but here it is not the case one improvement to this slow solution would be to implement this Pandorum in the other way that I expect to be slightly faster because here we do something with memory we create a new string we reverse it would be faster to just iterate we follow up over characters and also break when we have a mismatch if you also here at counts drink and unperson so you pass by your reference then usually for loop will not be linear it will be faster because if the first character is already a mismatch then we don't need to compare though maybe still a string will be just consisting of that there's a and everything will be a palindrome because every substring will be just a this will be linear done but maybe thanks to also this condition it will be faster because we will increase the length of answer by one only linear number of time that maybe if you use enough fixes enough improvements maybe it will be quadratic instead of cubic but proof would be quite hard in your accounting interview you want to be able to prove your complexity one more thing to notice is that this operation is also linear when we over we overwrite the sub stream that we would print at the end it doesn't matter here because anyway a moment ago we use a spine term that is linear so it's off n plus off end of 2n is design but if you wanted to improve such a small part in maybe in some other problem it would be an issue you could hear save instead of doing that you could save that's a best start is L best and is our and at the end here return substring as dot substring from best start to best end you need to save the length but it is possible to replace this linear part with something constant and only at the end retrieve the substring that you should return this was an cubic and we will improve it now if you want to think about it yourself pause the video now and if not we'll first think about N squared log N and then the intended version that is n square also of n is possible with monikers our algorithm it's called monikers you can read about it but it's much harder and we'll focus just on n square this log of n can come from many things but in particular it might be some sorting or here binary search if you should find it the longest something you can binary search over this length one idea is to here do the following if you have al the start of your substring then maybe you can binary search are so starting from this position how far to the right you can go to still have a palindrome but this is not correct and an example of that is let's say that starting from some position we have say a BBA and then maybe something more but when you binary search and you check for example if this substring of length three is a palindrome it will be the answer will be no it is not a palindrome and binary search would then try to find a shorter palindrome this is why it's not correct to binary search over the right end for fixed left-hand binary search end for fixed left-hand binary search end for fixed left-hand binary search works if and only if for some value is good means that also every bigger value is good then you can binary search because every prefix will give you one outcome and every suffix will give you the other outcome but what is correct is to do a general binary search over the answer and to here say I don't know minimum or something like that's called law this one high is N and now binary search over the answer we would need to say though why if there is fine room of some length there will be also a shorter palindrome if you have some very long string and in particular there is a bt TBA such a sub-sub string there is a bt TBA such a sub-sub string there is a bt TBA such a sub-sub string that is a palindrome then it's of length 6 but in particular it has inside a substring palindromic substring of length 4 this shows that if there is something a palindrome of length 6 then if you just remove first and last character you also have 4 and also have 2 and so on this is a proof why if there is correct length x there will be also X minus 2 this is it not enough for binary search to work because maybe there are those lines that are correct there is a substring of this length but not of the other parity so a correct complicated solution in N squared log n is to check every parity so it's something like 4 parity in 0 &amp; 1 so it's something like 4 parity in 0 &amp; 1 so it's something like 4 parity in 0 &amp; 1 now binary search the best length with this parity lowest one highs and now we only need this party so I will say if flow model Auto is different than parity than log plus if high moderato is not party than high - - what I did is I had party than high - - what I did is I had party than high - - what I did is I had 1 and n and I decreased it this interval for search only 2 proper parity if parity is 0 it should mean that I search only even lengths so instead of this boundary from 1 to 9 where I binary search it could be only from 2 to 8 ok and now while love smaller equal high or something like that it is low + high something like that it is low + high something like that it is low + high moderate or again we need to fix the parity here so maybe if mid module 2 is not parity then mid plus but maybe this exceeded the interval from low to high I will say if meet greater than high then break already I didn't find anything and now if good of mid so there is a substring of this length then consider this as an answer Westland is max of best land and mid it is that possible answer length of a pine wrong but what is function good it should check if there is a panoramic substring of this length meet and I can implement this function good of length x also I need to pass string as it would be for every L for every start if is palindromic is palindrome of as substr of l comma x so starting at L with length X then return true because there is a palindrome this should returns true if there is a palindrome of length x and the complexity of this is quadratic of n times of and for checking the palindrome but thanks to binary search we run this function good only logarithmic number of times and it would be here if good of meat then update the best line actually also updated best us and lowest meat plus one but also fix the parity but because meat has good parity then I would this lowest mid class though else high is mid- to yes so it's something high is mid- to yes so it's something high is mid- to yes so it's something like that I will now remove this and quickly fix any compilation errors like I will in particular fix this I need to change function good so it would return the starting position here say return L and otherwise return -1 because I need and otherwise return -1 because I need and otherwise return -1 because I need that to retrieve the answer and if good is not TMP is good of meat if TMP is not -1 so I found a palindromic substring of -1 so I found a palindromic substring of -1 so I found a palindromic substring of this length mid then here best us is as substring starting from TMP of length meat I still expect some compilation errors may be other issues I didn't care that much about the correctness here and it's missing in good I need to pass as now I had a mistake here I check with L from 0 to n actually I want this to be true L plus X smaller equal n otherwise I'm going outside of the array that was undefined behavior and I could also get rent a mirror this is accepted with running time of 200 milliseconds faster than 20% of C++ 200 milliseconds faster than 20% of C++ 200 milliseconds faster than 20% of C++ submissions and well it wasn't an easy solution for this problem the solution that we will see in a moment is much easier it is something that you can use in other problems as well binary search over the answer is a common technique now to the real social in the first cubic solution for every sub drink we checked if it's a pine drum that can be done by comparing first with last character second with second last and so on then maybe we check some other substring and we also do this track but there are some things that we do a lot of times operations that we repeat a lot of times unnecessarily instead of saving some values you can think for a moment what that could be and I will now show you that when we checked this substring a moment ago it's much easier to check if this sub string is a palindrome because we should still check this that and also one new pair of characters so to check if something from L to R is a good sub strings with a palindrome we should just check if from L plus 1 to R minus 1 is a good palindrome well it's a palindrome so this think shorter by one and also L is equal are well I mean alpha character is equal our character and this is enough to check if this longer substring is a pain if something is a plain wrong if you remove first and last character it should still be a palindrome and saving values in algorithm problems is usually about applying dynamic program we can iterate over l and r and use DP safe if something is a palindrome then if you want to track this lr then just use the computed value of L plus 1 R minus 1 this will be quadratics space and time we can do in the pan butter similar to this stuff we can notice that every palindrome have some middle point and there are only a linear number of possibly middle points either between two characters are exactly at some character if palindrome has odd length like free then its middle is a character if it has even length like for a BBA this middle here what we can do is check every middle possible middle position in that given string like this one and expand from it add character by character keep comparing them and just stop when characters are not equal from each of n positions we will expand at most n times and that will be n square in total complexity will be n square with constant extra space we just need the given string and it may be hard to get here I mean Big O notation maybe it is hard to get just like that at hoc but noticing that we will repeat some operations in brute-force allow allows operations in brute-force allow allows operations in brute-force allow allows us to get dynamic programming that is quadratic and is already good enough to pass it's faster than our previous n Square log solution but this dynamic programming it kind of shows you what should be that is give longer pondrom is based on a shorter palindrome that one an even shorter punter and so on so why not start from the middle and keep expanding you should often think about changing the order of doing some operations because maybe then the solution will be easier let's quickly implement this above the previous code and the new one will be it my github repository link in the description I will leave an is actually best line is fine this is fine and will stay as well I will just remove the middle part and functions now for every middle and this could be car position from 0 to n minus 1 this denotes disposition I will keep expanding so for every let's say with left mid minus 1 or with X will be lengths from middle to a new character 1 and here mid - excretory called 0 and here mid - excretory called 0 and here mid - excretory called 0 and mid plus X smaller than and this means that string is still characters at length X from me are still in the string plus X if as of mid minus X is different than as of mid plus X the break otherwise if Len is what 2 times X plus 1 because this character and X to the left X to the right if Len greater than westland best land is land best as is as subst starting from mid minus X of length 2 times X plus 1 or just learn this was for middle position in some character and now between two characters this might be slightly harder let's say that middle will be from 0 to n minus 1 and this denotes that the middle is between meat and meat plus 1 here an example would be if string is a BBA then if meat is this one B then it denotes middle just after that I will have something similar X is 1 but here meat minus X plus 1 and is greater equals 0 and meat plus X smaller than n you can check that here I have position meat I say that middle is just after that so if X is 1 I want exactly this position meat and meat plus 1 you can check that if X is 1 then this should give me characters at positions meat at MIT class 1 then if X is 2 meat minus 1 and meat plus 2 and so on if as of meat minus X plus 1 is different than s of meat plus X break you can see that this is similar to the previous part maybe you can do it with just one piece of code but I'm not sure how to do it easily then I prefer this way and here something very ugly a copy pasted just remember about this different position of the start for sure it can be done with one piece of code if you think enough and one more thing I should also consider length 1 of a substring and I will just change this to 0 because then this will compare a character with itself for X equal to 0 and - this land equal to one will be - this land equal to one will be - this land equal to one will be considered I think I'm done here and this will be quadratic I said a long time ago that this might be an issue that we override best as this is linear part Soter ethically it is n times and for this part times M looks like an cubic but we increase the length only linear number of times we can do this often times at most so this part even though it's it is inside too far loops so it is n square times this but this can be done only some small number of times so this contributes to the complexity only n square as well now we have this way and square time and of one extra space but not of one because we save this string so it will be of n but could be of one if we say that the string is given and we don't count it in memory and here if we just return the length new runtime is twenty eight milliseconds just what you would expect by from a solution that is faster by law Gert once again links are in the description for the problem and my code and I hope you enjoyed the video see ya
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
127
hey everyone in this video let's take a look at question 127 Word ladder on lead code this is part of our blind 75 list of questions on Lee code so let's begin in this question a transformation sequence from word begin word to word N word using a dictionary word list is a sequence of words begin word S1 S2 all the way to SK such that every adjacent pair of words differs by a single letter every s i for I from 1 to K is in word list and note the begin word does not need to be in word list and SK equals n word given two words begin word and n word and a dictionary word list we want to return the number of words in the shortest transformation sequence from begin word to N word and zero if no such sequence exists so it's kind of a mouthful but let's basically take a look at what's happening here and copy this example onto here let me just do that I will paste it back here okay so what's happening here so our begin word is hit or end word is cog and our word list is basically just this right here hot dog hot dot dog lot log COG there's all very similar words you can see and what we want to essentially do is we want to transform this word hit into the word Cog to see if it's possible so the shortest transformation is hit will become hot and we can do that by simply changing this I over here to an O then hot will become dot we change the H to a d then dot becomes dog and that finally becomes Cog and the total is five Transformations and we can see here that only one letter is changing every single iteration we can't have two letters change it has to be one letter change here we can see that it basically cannot happen in any circumstances so we can take a look at this one so actually if the ending word isn't even in the list of words then it's completely impossible for us to do so there's no way for us to even try to do that but we note that the starting word hit does not have to be in the word list okay so we understand the problem here now how might we go about doing this well you think about it like let's say you have the word hit right let's say you have to heard a word hit so I'm actually going to remove this I'm going to uh yeah so I would just have the word hit so if you have the word hit what are the things that we want to actually look out for or actually I guess the first thing we could do is we could just check if like end word is in wordness right if it's not in word list then there's no point in continuing so um that's just one thing we can just say out of the blue but let's assume that you know that's already valid and begin word we have hit what do we want to do well we need to find a potential word that hit can become right and that word has to be from this list over here that word has to be from this word list over here so what are the words that hit can become well hit can either become what looks like can it become anything else it can't become anything else so actually hot is the only option here okay and now we're on hot well what can hot become what can become dot what can also become lot okay so now we have these two scenarios to consider okay anything else can become no nothing what can dot become well dot can become looks like it can become dog dot can also become lot anything else it become nothing else okay what about lot what can lot become a lot it looks like it can become dot again it can become log okay now what are like the words here well we have a lot we already considered a lot so we're not considering again we already considered dogs we're not considering we ought to consider dots so we're not considering again but what about dog or dog can become Cog which is exactly what we need and we can see that we form a kind of like a sequence over here so if you kind of think about this like what does this look like this kind of looks like an adjacency list does it not kind of like connections on a graph if you kind of think about it and so why don't we treat this as some sort of like graph problem and see if we can actually form a connection from one word to the other one now one more thing you want to kind of notice here is notice how I'm like processing level by level right so first thing I do is I process hit and I see that I can perform hot for hot I can see that I can do Dot and lot and then in the next iteration I process Dot and lot and then I can see that I can just perform actually dog and the final one I just processed dog and I can see that I can perform COG kind of think about this and if we if you've done other problems with me then you know that this is kind of similar to a breadth first search because what exactly we're doing is we're starting off at one letter or one word here starting off let me make this bigger we're starting off at one word over here right and then we're gradually considering the other words that are bigger we're considering the other words that are bigger or considering the other words that are bigger and if you think about this we can think of this in terms of like a depth first search way because what can initially happen is that initially we just have the word hit in our queue right then we can see that from Hit we can form hot so then we'll just have hot in our queue we can process hot and then we can actually see that while processing hot we are able to form Dot and lot and so you can check these out now and notice how I'm only processing at each level so now that we have Dot and lot we can see that we can perform or get we can get dog and we can also get log and then basically notice how I am expanding one letter at a time and when you do it this way the path that you get will always be guaranteed to be the shortest this path that I get if I go from here let me do maybe something like that from the starting word to the ending word this will be the shortest path because I'm expanding one word at a time I'm expanding one letter at a time so this has to be guaranteed to be the shortest path why don't we take that approach and treat this simply as a breadth first search type problem it's actually a hard problem but it's really not if you understand what breadth first search is doing so let's kind of go into that and see if we can solve this using a breakfast search type algorithm so let's see how we constraint this all so first of all one of the things that I want to do is well I'm just gonna put this as begin and end and I'm just going to call this words to kind of make our life simpler Okay so what do we have so we have to begin where we have the N word now word is actually a list right first thing I'm going to do is I'm going to convert it to a set because we'll often be looking inside of word so I'm just going to convert it to a set to make our lives easier and code faster one thing we can immediately check is if and not in words if that's the case then automatically we can just return false right because and has to be in words as per example two okay otherwise now let's treat this as a simple Q problem a BFS problem so we want to q and what do we want to start off with what we want to start off with the word hit so this is our starting word right now we can do while Q now what well if you recall how we did what was that one question we did where we had to process level by level I believe it was the question where we had to like take a bunch of nodes and then connect them together level by level but there was a question like that but regardless what we need to understand now is we want to process this level by level so what I mean by that is we want to process this level and then we want to process finally this level it's completely possible that while we are processing this level our queue actually becomes larger but we will not process those just yet we will just process that level so maybe this is like two items we'll pass it will process those two items and then maybe we've added in like three more item then we'll process the remaining three Etc so we'll keep going like that one thing I can do is I can do size is the length of Q and then I will just process and actually I don't need I so in range 0 to size I would just process the amount of letters or the amount of words uh the amount of like items in the queue that I need to so I think I can do something like Cur this will be q.pop but now at this point we will be q.pop but now at this point we will be q.pop but now at this point we will get hit right so we'll have hit okay now that we have hit I guess the first thing we can actually do is we can check if this is the target word if it is then we know we are finished we know we are able to form the answer so I can do if Cur is equal to Target and I just made a Target or I made it end okay current is equal to end and we return true otherwise what well oh think about this so if we've already arrived at our word we're good but if we haven't then let's say we're at hit but we need to know what to add to the queue next right we need to know what are the words that are basically just one letter away from my current word and so that's what will well in this first iteration We'll add hot but once we're at hot we need to add in dot we need to add in lot we basically need a way to figure out like what are the words and the words like a word list there are just one letter away so what's a way in which we can do this well one way that comes to my mind is basically given the current word like let's say hit I think what we can do is we can basically just go through I guess all the way from a to Z and we can try replacing each one of these letters with any of the letters from A to Z and then we want to see if that exists in the words list if it does then we know that's a valid word that we can add otherwise we just move on and we check the next letter and then we check the next letter Etc so let me Let Me Maybe write that in code to see if it makes more sense because a little bit hard to explain visually but let me try to write that in code so basically what we would have is that we would go through Brian range 0 2 and of Cur right what we want to check is we can check every single character in looks like a b c d e f g h i q r s t u v w x y z this I think you can do like strings dot ASCII underscore that might be better but let's just maybe start off at this one so in this one what do we have so let's say let's see where the letter a right and instead of hit let's just say it was like AIT if it was something like this well we don't need to replace with a right because a already exists so um we can maybe just check for that so we can check if like if her at I is equal to C then we'll just continue right like we'll move on to the next letter otherwise if that's not the case then we can form a new word here right so we can form like X word for instance and what is this equal to well this is just a little bit like string concatenation but it would be equal to something like this so occur up to I and there'll be plus the C this new letter and then it would be Cur I plus one onwards I plus 1 onwards so basically for something like this it would transform this one word into bit and then like kit like this Etc right so once we form this new word we can check to see if this word is actually like part of our words list so if next word in words so if this is the case then we can add it to our queue append next word right now what's one thing we're missing here well if you think about it when we were over here when we cut to hot and we added in Dot and then lot and then we process Dot and we visited dog and then we visited a lot but like we're already visiting a lot again so we don't want to make we want to make sure we don't repeat any of the words you want to make sure we don't repeat anything so as with like all the DFS or BFFs we need a way to see like all of the words that we've seen before us to make sure we don't repeat them so I have like my scene set over here and in the start all right I'll just put this down here actually in the start I'll just add in my begin word and then basically here I want to make sure that X word not in scene and if it's not then I'll add it to my queue but I'll also add it to my scene and that's basically all we have over here all we need to do is figure this out all of the next words to add and then we need to add it to the queue so that should pretty much be it so let's go ahead and try running our sample test cases to see okay so my output is true and false so my output should actually be like the number of I guess the levels right so luckily here the levels it's just like where we are going in this uh in the BFS call so this is level one and then we will process level two and we'll process level three so all we really need to return is that level so initially I think I can set level equal to one if it's not inwards level is zero otherwise what we can do is after each like after we're done processing each level we will increase level by one level plus equals one here we overturn the level and assuming we can't find any answer we'll just return zero so let's try that okay perfect and we can go ahead and submit a perfect so we arrived at the answer even though this was a hard problem if we thought of this in terms of a breadth first search then it suddenly becomes a doable problem what I'd say would be like a medium I think the hardest thing here is to basically understand this is a breadth first search problem and really come up with the next set of words and you can take a look at this just to make sure what we're doing but essentially like if we have any sort of word we're surrounding it by like a different letter and we're seeing if whether that exists in the word list and if it does then we go ahead and add it on so if we think about like time and space of this well time I think you can think of it as like we're basically just at maximum we're considering like the total amount of words that there could be maybe like o of n there and similarly in terms of like space it would be similar because of the queue and um the set okay thank you for watching
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
96
Hello hello guys welcome back to tech division in this video you will see the unique entries problem system list date 4th june challenge personal problem given to the number possible tasty unique and having its number from one to the number from one to three subscribe for Subscribe Notes Number One To Three 500 Notes And You Will Be Having Only One General Unique Values Will Be Having Only One General Unique Number Australia Test Match Let Me Show You All Simple Maths Formula Excel If You Give Entry Difficulty To The And Factory Combination Of Units structure and subscribe also unique word total number of combinations with must subscribe and e don't think so let's you to the number of but not want to 400 tweets must subscribe notes23 400g with the number of do tunic besties scholar must at you can see but IF YOU TAKE ONE MUST HAVE DANIEL FACTORY YOU ARE NOT HAVING BEEN ELECTED REPRESENTATIVE OF NOT HAVING KNOW THE COUNTER SUBSCRIBE VIDEO SUBSCRIBE SWEATER ACCOUNT IN THIS CASE WILL NOT GO INTO THE QUALITY AND LETTERS ON MAY 20 2012 MUST SUBSCRIBE subscribe The Channel subscribe The Video then subscribe to the Page Second Latest Represented by C Two Cities Having Two Notes OK So the Total Combinations in this case will be C One * C to OK Combinations in this case will be C One * C to OK Combinations in this case will be C One * C to OK No Latest One This Note 3S Root OK So IF you make Note 3S Sure Den Left Side you will be having One more vitamin A single number subscribe and subscribe the Channel subscribe and subscribe the subscribe third total number of combinations 2018 total number of combinations still serious note okay so what will be the total number of combinations directly total number of structural unique best years when you Have this point note soiled note servi 151 basically interested in doing so will change the configuration everyone will get you can count what will be the number Australia 1st Nov 09 individually and you will not get the total number of structurally unique subscribes and they calculate the thing e no exactly a total subscribe google unique besties so what is this for electrification work only and nothing but a number subscribe nine number found can be represented sc code to sum of 10 icd - 9 - 100 this is not very simple to understand this icd - 9 - 100 this is not very simple to understand this icd - 9 - 100 this is not very simple to understand this number Has come for this is related to the number problem number can be reduced and different through which can be interested can solve this problem solving equations and you can solve this problem or have already video where is all about this number 1 loot dynamic programming and this formula Date this channel as official as well so you can calculate the normal co operations in order of time the regional Gautam Das Swami plate put middle name in this video you will provide you a very simple Veer Da The Airplane In The Video 34 Highly Recommended The Voice Kids Videos For This Video Ise Zara Solution In Different Languages ​​In This Zara Solution In Different Languages ​​In This Zara Solution In Different Languages ​​In This Post With Everyone Can Benefit From Like Share And Video subscribe our Channel subscribe Video C Bank
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
135
Hello gas, I am Lalita Aggarwal, welcome friend, who has understood the problem well, there are six things to try, see this D question literature is very much, it is a question, it is not a matter of taking much quotation, see the tag of hard here. Do n't be afraid, this can be done with a literally greedy approach. There is no need to maintain any kind of DP or anything. What does Giridih call her greedy approach or does she say that here one is next, ours was zero, that's it. Just checked the next, I am not thinking ahead, yes brother, I will go now, bla, don't think so much, you have to move normally, very comfortably, what has he said here that he is telling himself to all the students or to all the children. You will have to give minimum one candy. Now if you have to give more than one, it will depend completely on the ratings and neighbors. If you understand, then what can you do? By default, it is a small brick. You can give candy to everyone, Mulanchi. I gave it absolutely right and after that what did you check, once while going ahead, check that while going ahead, take the story like a mother, you are coming first is your hero method, after that then leave it. Two, start from here, okay, you check whether it is bigger than the previous one, no brother, if it is not bigger than the previous one, then it definitely does not need extra conditions. Okay, then Apna is on this. Apna said, is this bigger than the previous one? It is not big, brother, this one is also not bigger than the previous one, so this one also does not need even a second, so why did you come, then you took it from yourself that this one definitely has something extra, it was not there till now let's do our news, it is a matter of courage, it is a simple thing. Then Apna is here, what did Apna say? Is this smaller than the previous one? She said, yes brother, this is smaller than the previous one, which means it definitely has some extra conditions. So Apna is okay while walking in this direction. Then Apna is on this. I came back and did not check whether it is big, so it is big, it must be of an egg, when I asked for it again, it became 212 and said, Hanju bhaiya has become and this was my answer, when you call brother, I salute you, how many become. And that is what we have to do for ourselves. A little more literal button on this. They did not understand. There is no need to take tension. First of all, we are going to understand this question very easily. After that, its Afros. Will butt and give the final bill Most words implementation Look at the explained question What was six in the question No, you have no error in life, okay one zero, you are inside it and you have to do the return, you have to fat okay now this five has come How come, nothing brother, these children were standing here, the students were standing here, it's okay, his rating was one, his rating is zero, and his rating is zero, now see what is your condition here, at least you have to give one candy to two, three. If you have one, this candle beauty said, okay, very good, now apart from this, your first condition says, let's look at that, the first condition of yours was this is yours, according to the ratings, and the second is yours, then leave it, others are dependent on whom. She has become dependent on the other, that she is not her own, she has to see her rating, if she is never, then suggest that she is okay, if the rating of Never is big, then you will have to give her more than the number, okay, understand. There should not be any doubt in this. Have you understood, where did the concept of rating come from and where will the concept of never be? Now look, what do you have to do here, like this is one, it is completely fine, so there is no on the left of it in the initial. No, he said, yes brother, I am not on the right, he said, yes brother, first let's move to the right once, then we will move to the left, he said, okay, then here, now here, let's look at the left, let's check the cash which is on the left. Is it smaller than the one on the left? Did you say? No brother, it is not the same size, so now please calculate on it. Is it necessary for inspection? Said, No, Spectrin disc is definitely there. It was not found. Then, the one on the left said, yes. Yes, back to the left, then back to the left, what did you say next, is the element to the left smaller than this, the one at the last place is small, so it is good for you, what is the extra candy here, because what is this, it is big, said Hanju. If it has more ratings in the big one, then what are its extra conditions? Surely, you came here, it is a simple thing, I understood it, I said, yes, I understood, I have done all the open travels, now why go back to the top? If you travel, will it not exist? Then you will start back from zero. Now tell me, I have come back to zero, there is no problem. Tell me, who is on the right of zero. Is he smaller than 0? No, but he is not smaller than zero. The quality of his own said, Is the one who has become the one with the right, is he small? He said, Yes, the one who has become the right one is small, so it is your blessings. What will the forest also have to give? 10 days. You will have to give an increase. Okay, I understood. Once you have turned your left, have you reached the total number of candies, that is, whatever you have to give, you said, yes brother, you have to give it, now just count them. Five will come, no doubt given, let's track it once on our second example also, said okay, see what is there here 1 2 Okay one, you, once we will go to your left, once to the right, it is clear, first one is the one with problem. No problem, you are fine first, what did he say about the point of time, is the one on the left is smaller? What did he say? Yes brother, the one on the left is smaller, what does it mean that there is an increase here, there should be no doubt in it. Said yes brother, ISP came to this and said, is the left one small or not, brother, the left one was not small, it was equal, I have nothing to do with the equal one, I just wanted to check the small one, is it small, is it not complete, is not small. Okay, leave it, the one- is not small. Okay, leave it, the one- is not small. Okay, leave it, the one- way journey is complete, now Travels Apna U will go, said okay, now when the driver was going, Sir Papa, he will not be on this, he will start from here, okay, Apna checked back, is the one on the right is the smaller one? Brother, the one on the right is not small, so there is no increment in it, then what is the meaning of apna yahan pe? How much is four? Is 4 our answer? He said yes, four is our answer. Question solved. This is the approach we are going to build. We are going to travel once to the left and to the right. Then whatever is yours is in the glass. This vector will be updated, maintain it like a vector, make it equal to whatever it will be, that will be your answer, it is not that you were just trying to understand the question and not just trying to understand it and the implementation happened there itself. Exactly, we will put things into implementation when Apna had done it. To understand the question, Apna came here, see what Apna said as soon as she came, first of all she took this time, what is N, what is Apni, what is the size of the ratings, which is Apna. This life was of good quality because you have to attract yourself on it again and again, so you took it in another variable and there is no region, okay then you made a vector a friend, what is this saying named Candidate? There is nothing to say, the vector that you had created there is this one, you are one and this is this bullet, so this is on you have written it directly on the white board, you will have to store it there like this, yes. So, what did he do for this, he made it a vector, he said, okay, now understand carefully that its size is related to NFC, it is the size for N students, and what he has given to everyone by default. See, by default everyone has one candle each, it is okay, as I did the initial here too, it is very good, now look once, this is my traversal and let's go once, after spilling the two drivers, I understand easily, I want only one life, said okay. Then what are you doing here right now, here are you moving in this direction, Jaan said ok, there is no problem, after that I said that we will not start with this, what do you always see, have you seen the one on the left, there is something in his laptop. Apna does not exist, it does not start from here, I will start from here, I said, okay, so what have you checked here, see index 1, I have to go from one to more, Apna said, no, here, what have you checked at each point of time? That this is the value of this one, how big should it be bigger than the left one, if this one is bigger than the left one, then we will make it bigger, it's a simple thing, this was said somewhere, Apna said, yes brother, Apna has said. That if the rating of your current one is bigger, which rating of one is bigger, which ratings with zero means minus one, then from the left one, if your current rating is bigger, then what will you do with it, what in Hindi? We will do +1 in the plus one time, +1 in the plus one time, +1 in the plus one time, whatever value was there in the left candle, we will do it within that, there should not be any doubt, brother, it is clear that I have understood it, so now we have gone to the left side once. Where will it start from N - 2? Where will it start from N - 2? Look at the reason for starting from N - 2. N is here. It has become N - 1. Now don't do it from here also here. It has become N - 1. Now don't do it from here also here. It has become N - 1. Now don't do it from here also because if you don't adjust anything to its right then you will have to do it from your gap, hence it is made like this. And mines, there should not be any doubt in this, the one on the right should be smaller than this, okay then what you said here that the one on the right should be smaller, what does the right one mean that the current one should be bigger, if the current one is bigger then Then what will we do, here we will come here, now here we will find out the maximum that out of this, the value which is present in the candidate is the bigger one or in the previous one, by adding plus one, it could mean here that the value which was already present in the candy. Suppose if five was present here, then it is already much more than 5, meaning you are much bigger than that, so if it is so then it will also be okay and if it is not so, then you are actually not you, plus one minimum, if you want three, then say three. It should be bigger than . I also understood this three. It should be bigger than . I also understood this three. It should be bigger than . I also understood this thing and said, I understand, there is no doubt in it, then here is our candle vector, now in it the final head answer has been given, here in paan, this answer is it was zero and then our What did he do with his NDA? He retracted the entire above and like what is his rate? Finally, what happened here, meaning whatever values ​​were there in his factor, meaning whatever values ​​were there in his factor, meaning whatever values ​​were there in his factor, he made his answer. Return his answer. I hope you understand it well. A must have gone literally too much, this is a question, there was no need to be afraid of seeing it in hard times, after submitting, you are watching, it is proving very easily, tell me the space complexity of the spoon, see, there is no space complexity here too. No space complexity There should not be any doubt otherwise it is a late matter, now let's talk about our time complexity, that is, okay, how much time is off and it is within it, then it is off and within it, you are also off and at the moment I am also off. If N is placed inside it, then off three becomes three, it has no value, it means off and our time is on the left side, I hope you have understood well
Candy
candy
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. You are giving candies to these children subjected to the following requirements: * Each child must have at least one candy. * Children with a higher rating get more candies than their neighbors. Return _the minimum number of candies you need to have to distribute the candies to the children_. **Example 1:** **Input:** ratings = \[1,0,2\] **Output:** 5 **Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively. **Example 2:** **Input:** ratings = \[1,2,2\] **Output:** 4 **Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. **Constraints:** * `n == ratings.length` * `1 <= n <= 2 * 104` * `0 <= ratings[i] <= 2 * 104`
null
Array,Greedy
Hard
null
389
Jhaal Hello Hi Guys Welcome To Cold Be Used As Question Spinal Difference In This Question Being Given To Streets As A Team Which Consists Of Only Lower Case Latest Printed Per And Subscribe The Amazing Position Mid Day Miles Per Hour Will Contain All Of Hindi World Channel Like This acid subscribe and subscribe the Channel and subscribe this Video not support to that now discussion can be done in this approach as I will destroy all the three approach as this approach is fashion approach but will do the first visit to the frequency of its kind Swap them dentist consider distic acid bases contains all the letters of hindi world channel subscribe ke beej and in one time series if in one time and this also giving one time she did not return with this also screened at one time and listen Become Metius Don't Nobody Should You Will Attract Beginning Springsteen That's the Biggest Ring and Teachings Will Find Weather It's Present in Time and Not Present Weather Its Frequency Is Later 20 and Not Reflect See Cold Not Be Positive End Definition of Discrepancy No Withdrawal Distic which contains one letter extra not every Indians will check the date particular character in this present s or not present in the return of the day that and take care tips pregnancy house map is that is present in the map fog check weather this country But are not limited to return back like nd share a family of 50s string dry ginger content does but intense pain straight silver is present but they were not present president of 220 wear look in the committee will decrease tree to an egg subscribe of soil from 120 thursday August 9 A Hindi Tea Spoon This Will Be Present In The House Map But Iron Hanging Exactly 120 Sudhir Will Answer In This Case Will Be This Morning Vitality Of I Sudhish To Economic Condition Which Would Follow First Where To Check Weather Tripathi And Credit Balance In History For not it is not present day test cricketer only no will check weather this practice paint house map and misses and note it is not get 1000 they returned to only light can discuss as president and does in Sudhir and disapprove of this a blend of spring no Space Complexity Will Be Ordered 2601 1922 Because You Never Given But Seeing This Will Contain Only Lever's Sales For Its Soldiers Who Sacrificed There Only From 60 Forward Space Complexity 15.2 Over Now Only Election Let's Space Complexity 15.2 Over Now Only Election Let's Space Complexity 15.2 Over Now Only Election Let's Look At This And Approach 968 Enterprises Shopping App Launch In This Will give and input reach one and a half and ditties gomez pet clean input drown school nobody will develop a different busy course course course voice messages simple code dentist behave trade will after shooting this two streams will tree to ver of molesting that is a b c d now every day this will check weather the values ​​of smt adopting induction same values ​​of smt adopting induction same values ​​of smt adopting induction same and note is that values ​​is the date index is and note is that values ​​is the date index is and note is that values ​​is the date index is divine percentage is not same validity of i unemployed answer like and asked for se 1000 this but acid an air chief executive Acidity is but is now a case where are you want it lasts opposite consists of suppose belief is remedy abcd one will find the value of doom will return of the day vision of vikas mold benefits oven shopping app launched at 34 point notes23 approach nav third airport jobs and operation notice approach similar to this question in which year to find a unique number from here in which every number is given price dentist vinod add gaurav to same numbers is 540 2120 vinod not consider this question on yes betu 2012 302 Find A Unique Number From Its Only Thing One Only At Least One Superhit Video Few Seconds Or Off All The Numbers And 2120 200 Difficult One And Once Or With Three Entry Ladies Vs One So Answer Udyan One Status Drinks And Of Every Element It Is And of two element beans in the answer is zero two in this question disposes similar to this type of nation but will give water contains all the letter at present s well s one except words but can do we can travel expense and georgette with every Great Tarf SNT Deposit DDA Ne Half Update Top Nor Will It Like Subscribe And You Will Cancel Ho Mein Novel Did You Will Be Glad You Will Be Getting Canceled For Individual Will Be Generating Aa Answer Which Is The Unique Character Is A Flat Lovety Code Sidhi Double The most obscure 1999 are using any express now in both cases like this is or operation also and in that fashion approach of birth time complexity boys suchancombed to win but in this approach they maximum variables wicket 106 because 06 half a lower castes and tribes in english Language Sudhir For The Most Optimized Approach Will Be Tijori Approaches Vikas Initiative In One Variable Subha Aayi Ho Like This Video Thank You A
Find the Difference
find-the-difference
You are given two strings `s` and `t`. String `t` is generated by random shuffling string `s` and then add one more letter at a random position. Return the letter that was added to `t`. **Example 1:** **Input:** s = "abcd ", t = "abcde " **Output:** "e " **Explanation:** 'e' is the letter that was added. **Example 2:** **Input:** s = " ", t = "y " **Output:** "y " **Constraints:** * `0 <= s.length <= 1000` * `t.length == s.length + 1` * `s` and `t` consist of lowercase English letters.
null
Hash Table,String,Bit Manipulation,Sorting
Easy
136
29
hello everyone let's talk about um this little problem divide two integers it's actually a good problem i think but in because there are a lot of some sounds it's because um there are a lot corner cases and said make people very upset for example second cases are about integer maxima integer minimum and sometimes it will be overflow so people get a lot of runtime errors from it and this gives some dance okay let's take a look at how to solve it an elegantly okay this is a problem given two integers dividend and divisor we need to divide two integers without using multiplication division and mode operator note assume we're dealing with an environment that could only start integers within the 32-bit sign integers range 32-bit sign integers range 32-bit sign integers range so for this problem assume that your function returns 2 to 31 minus 1 once division result overflows so one was the division versus overflow imagine that dividend is negative 2 to the 31 divisor is negative 1 so we will get 2 to 31 which is on beyond the range so for this case we need to retain integer maximum okay let's take a look at these four and simple examples for the first example 10 divided three we get three for second example 70 by negative three organic negative two first third example zero divide one we get zero notes and the problem mentions that divisor will not be zero so for the first example is one okay assuming the dividend is 59 and divisor is 3. in order to get the result using a multiplication division or mode we need to use subtract so we can subtract 3 19 times get 2 which is smaller than 3 then we can stop and we get the answer 19. okay imagine that the dividend is 10 million but the divisor is 2 or 3 then you need to subtract millions of times which is super slow so how can we improve the speed minus subject 3 is very slow but we can subtract a larger number for example we can subtract 6 each sub subtraction will contribute 2 right so we just subtract 10 times and we subtract 6 9 times for each subtraction we get two contributions so the answer is 19. we can make it faster we can subtract 12 fourths or 24 or 46. for 46 we subtract 46 so we substitute one six and one three we just need to subtract three times then we get to answer so this is the core ideas of these problems okay for this table we know three is the base divisor the contribution is one and comes six contributions two then 34 46 and 48 the contribution is 16 and initially the dividend is 59 so we can consume 48 and answer will become 16 and we still have yet 11 then we try to consume 24 no we can 12 no we can 6 yes we can we consume 1 6 answer will become 18. then we can keep consuming 3. answer is 19 so we can just return finish okay let's see how to implement it for the first solution um i will allow use long type in the program i will reflect vector later so in this solution 2 we will not use long so for now we can use law okay at the very beginning let's consider corner cases of the overflow if the dividend is in minimum and divisor is negative one we know it will be overflow then we can just return in maximum okay next we just um decide if it's positive or negative okay then i want to convert numbers to uh positive numbers so we get new dividend and new divisor note i need to use long here since dividend and divisor can be in minimum if we use abs in minimal and it can be undefined behavior okay next i define power is related due to the contribution for example initially the new divisor is 3 so the contribution 2 to 0 which is 3. when newt for example a new divisor becomes 12 the power is 2 so contributions 2 to the 2 which is 4. so in this while loop we try to make our new divisor we try to make our new device as large as possible but with but which one cannot exceed the new divide and otherwise is meaningless so in this while loop if the dividend is 59 after this while loop the new divisor will become 48. okay we'll keep this while loop as long as power is not negative and for my content a new dividend as long as it can consume a new divisor we will consume it and as a contribution to our results then we just decrease the power and for this operation it's just like and divide my new divisor by 2. okay finally if it's positive i return result otherwise i written negative result okay for this solution we use long type here let's see how can we get rid of the loan type so in order to get rid of the loan type we need to make dividend or divisor not integer minimum as long as it's not integer minimum we will not get undefined behavior let's say how can we make them not integer minimum okay so it's a solution and most of the code remains the same one differences is here we just declare integer instead of long okay the major difference is in the grid box let's see how can we make sure the dividend or divisor is not integer minimum here okay if the divisor is into minimum then it's very easy to handle you know only instant minimum divided into two minimum is one anything errors divided into minimum is like zero point something or negative zero point something so it's just zero okay if the dividend is integer uh minimum first we need to consider corner cases if the divisor is negative one which is just returning to your maximum otherwise we try to consume one divisor first no uh if divisor is positive send the result is negative so we need to append a negative one here then we just consume one divisor here otherwise if the divisor is negative we know the result is positive so we append one here and we consume one device here so we recursively call this function and in the recursively funct function since we put process as a dividend so in the next call it will not be inter minimum then we can simply use the abs function here so that we get rid of the long type okay that's it that's the solution thanks
Divide Two Integers
divide-two-integers
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator. The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`. Return _the **quotient** after dividing_ `dividend` _by_ `divisor`. **Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`. **Example 1:** **Input:** dividend = 10, divisor = 3 **Output:** 3 **Explanation:** 10/3 = 3.33333.. which is truncated to 3. **Example 2:** **Input:** dividend = 7, divisor = -3 **Output:** -2 **Explanation:** 7/-3 = -2.33333.. which is truncated to -2. **Constraints:** * `-231 <= dividend, divisor <= 231 - 1` * `divisor != 0`
null
Math,Bit Manipulation
Medium
null
342
all right what's going on gents ladies and folks today we're going to go ahead and solve this question over here power of four using recursion so let me just go ahead we saw that we'll reset the code we can go from there so let me just move this second there we go okay given an integer and return truth powders four other Twin Falls and it's just a pound of four false that okay so okay let me go ahead and do this so if let me see here given an integer n return true if it is a power of four so if n go to different powerful return false okay sounds pretty easy okay we need a responsion for this cell okay let's go ahead and try this out so let's go ahead and do this so let me say like X is equal to 16. we're going to go ahead and check if it's recursion so technically if it's a power of four if we do that then that equals zero technically anything equals zero now what we can do is we can go ahead and double check this cell you can open with all my ID real quick okay so over here let's go ahead let's do uh zero let's do 64. 02 yeah because technically if it's a power four then anything divided by it is four two so okay so we know that so let's go ahead and do that real quick so let's do that in red let's do it in red uh okay zero okay that's one thing we found out okay so with that in mind uh return n equals one is true okay so n is one is true okay uh let me move this zoom out the way over there do this okay so with that in mind let's go ahead let's do this so return and true so okay so let's see here what's the number and again that's fine I'll just get down back here um and then there's one okay what about zero I'm assuming false let's put that over there so okay and wow I'll do occursion so if okay I'm gonna make x equal to four okay so what I'm basically going ahead and doing is I'm making a variable x equals four because we're trying to power four then we're gonna go ahead and keep calling it keep multiplying four by itself until it gets to or honestly don't even need to do that because if it's divisible by four because technically if let's come over here let's say that like it's like this number right but let's not gonna do this number okay and there's a block by four if it equals zero that means of the power of four technically so we don't even need to use recursion let me go ahead and try and so this so if n or equals to zero turn true so this typically should work in here obviously you fix it up a bit so I think that looks over okay so that works for the first three cases let's submit it and see okay I'll put his true as expected to be false there's a negative number I'm assuming okay foreign there we go yep because it's time to not the power of okay after recursion comes the issue is that n equals eight which technically passes this because that but thing is it's not the power of four it's times two so okay no worries then we can use recursion so okay let me go ahead take this and use some recursion how much time left okay we're at five minutes six minutes okay so should be pretty good uh so the average time trying to get is 20 minutes so we'll see how that goes so this grab this oh there we go Okay so um if and wow I'll do this and okay I'm gonna go ahead and see there okay I'm thinking is that the only history I'm having is that effects I'm getting us out there so we keep using recursion I'm trying to like initialize a variable right here like x equals four but the only issue is that if we keep doing that and we keep calling itself it's going to be 4 again so I'm thinking what we can do is uh let me see here it is something like this so n equals if n equals zero turn false okay so we need these this is good we need that now X is less than n and if we call X consider this it's not gonna work but minus of x equals n turn s work it's not going to multiply by four return is power of four and we're just giving it gonna be X so but the only issue is that it is right here so um oh we don't even need to do that because the thing is that okay the only issue I'm getting is that okay so I'm thinking is that we do something like this we could do like multiply n times four which technically should work because it's gonna stay consistent but then this one wouldn't even pass because there's no X but if we do initialize an X I know issue that we're gonna get is uh if we call it again it's going to make x equal to 4 again and again but technically 21. it's not really what we want because I'm thinking is this is let's say x is like four right here and run it through okay in this example um it's n equals eight okay so back over here if we use this one over here if x is less than n return cell to the power n times four which is something good or sorry x times four only issue is that X already equals four so that's gonna what's gonna happen again it's going to be done it's gonna go like call it again and again because it's going to keep on calling this a x times four okay then it's going to not go over your UPS like this could be for again hmm I'll make another variable Z equals X it's not gonna work either let me go ahead and debug this a bit we have 10 minutes I can make a better one so um sorry there's something wrong okay so it's kind of embarrassing me to save up they're actually ran this let me see here foreign okay let me do this real quick I don't need this there we go uh okay um foreign I think I know the issue huh okay uh foreign recursion depth exceeded yeah cause of this bro but I'm thinking is that I can't I think I can't do this yeah it looks not gonna work maybe if I do like something to find another issue with this part so I pretty much got the question down it's just this part right here where um I'm thinking is because we need times of four times four which would work but the only issue is that we need two numbers okay let me go to pauses real quick let me do some research and then I'll let y'all know what the Vibes are I'm back I'm doing research I just washed my face so there's that because it's 4 a.m and I'm doing leap code while it's 4 a.m and I'm doing leap code while it's 4 a.m and I'm doing leap code while everyone else is sleeping but it's okay because it's Ramadan so let me turn this camera off too hopefully this weird setup isn't tripping all out Okay so back to the issue is this is that if I go ahead and call this again I need to have X to find but if I go ahead and have X over here x equals four it's going to make x equals four again and that's going to keep doing this is until it runs into an infinite Loop like as we'll see right here in its maximum depth look at that return because of this line right here so I'm thinking is the how can we get it so that we have an outside number that adds to itself that we can compare n to so um I'm thinking is I mean look at the solution real quick just to see like okay this is crazy I don't know if they're doing 11 time this is all one time sorry okay um okay uh let's see here okay I'm pretty sure I can do this without recursion honestly like I can only just like I think it's doing this topic version everything I could do without recursion yeah I'm gonna try that recursion okay let me just find the brute force method real quick first so 17 minutes in let me second again in 30 minutes okay so it's not even need to do that okay so let's do this so we already have this x equals fourth and uh right here okay there's four if x is greater than n inet um if x is greater than n because what's happening is that we're going to keep running and running it while X is less than equal to okay so excellent 64.64 while X is less than or equal to 64.64 while X is less than or equal to 64.64 while X is less than or equal to 64. so X equality okay so it's 4 16 so 4 right through then x times equals four which will be 16 if x is greater than n return false no because you run on the dot okay if x is greater than n returns uh okay this should work oh what oh pretty again that false yeah there we go okay it's gonna look like you know man um foreign so 17 while X is less than n x equals okay so while X is less than n x equals x times four is four sixteen okay x squared that and return false this should work let's see no that's wrong actually okay there we go got it okay so I did the non-recursion method uh in about four non-recursion method uh in about four non-recursion method uh in about four minutes it's not that's all I'm gonna take to solve it I'd say probably like let's just say 10 minutes I can figure out how to do it myself but yeah there you go so we're using brute force method wow really wow okay yeah using a brute force method I was able to solve it and literally let's just say like seven minutes um not even actually probably like five minutes using recursion uh I haven't figured that part out yet so yeah we'll see but I'm probably gonna make another video to see if I can do it in recursion because I kind of gave up Midway through from I try to do recursion for the first like 17 minutes and then the last 11 minutes I was like man let me just like brute force method it but it wasn't pretty this is nowhere near pretty but it works but I want to practice with the recursion so we're going to try it again in about like five minutes and see if I can do it but yeah
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
1,973
hello everyone welcome to my channel this is Leo let's do some more lead code problems today so this problem is called count no equal to sum of descendants so basically we were given the root of a binary tree and we were asked to return the number of nodes where the value of nodes is equal to the sum of the values of his descendants by descendants we mean the left sub tree and the r of tree okay so this looks pretty simple like uh DFS problem the only thing is that this is going to be a post order traversal because we have to record everything from the left sub tree and then everything from the right sub tree then add the root node itself okay so let's take a look at an example so we have 10 3 4 2 1 and we have two roots that its value is equal to all of its descendants okay so obviously there's three which equal 2 + 1 and 10 = 3 + 2 + three which equal 2 + 1 and 10 = 3 + 2 + three which equal 2 + 1 and 10 = 3 + 2 + 1 + 4 1 + 4 1 + 4 okay and about this one there's no notes that fits this description okay all right if the root is zero it equals to itself so we should output one okay so how do we approach this problem like I said we can use a DFS to Traverse the tree and at each level we're going to return the sum of the all the noes in the left sub tree and all the noes in the right sub tree along with the root node value itself okay so let's make a global variable let's call the count and let's call the DFS function so I call it on the root and return the count okay so the DFS function should be when it reaches the end of the when it which is the end yes the end of the tree which means there's no Leaf nothing we should return oh sorry I shouldn't have a void now let me call it long because I'm afraid there should be uh some integer overflow so let's be safe and if the root is null we can just return zero and like I said it's going to be a postorder traversal so in left is DFS m. left and right is DFS right okay sorry this should be long and long okay yeah now we have the sum from the left sub tree and the sum from the right sub tree and we're going to update the count okay so if root. value equals to left plus right which corresponds to the description here the value of the node is equal to the sum of the values of The Descendants okay so in this case count Plus+ okay so in this case count Plus+ okay so in this case count Plus+ okay if it's not what are we going to return like I said we're going to return all of the sum of all of this descendant and the root value itself okay so root Value Plus left plus right okay so that should work let's see yeah that works perfectly so about the complexities obviously we're traversing through all the noes in this tree so the time complexity is oh then and the space complexity since we're doing a DFS we are not actually saving anything to anray or something like that so the only thing we have is the cost stack which is the height of the binary tree okay so let's submit it and it passed okay um thank you so much for watching I'll see you in the next video
Count Nodes Equal to Sum of Descendants
count-nodes-equal-to-sum-of-descendants
Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **sum** of the values of its descendants_. A **descendant** of a node `x` is any node that is on the path from node `x` to some leaf node. The sum is considered to be `0` if the node has no descendants. **Example 1:** **Input:** root = \[10,3,4,2,1\] **Output:** 2 **Explanation:** For the node with value 10: The sum of its descendants is 3+4+2+1 = 10. For the node with value 3: The sum of its descendants is 2+1 = 3. **Example 2:** **Input:** root = \[2,3,null,2,null\] **Output:** 0 **Explanation:** No node has a value that is equal to the sum of its descendants. **Example 3:** **Input:** root = \[0\] **Output:** 1 For the node with value 0: The sum of its descendants is 0 since it has no descendants. **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `0 <= Node.val <= 105`
null
null
Medium
null
392
hey guys how's it been going this is Jay sir in this video I'm going to take a 392 is sub sequence for given a string s and a string T check everything as is subsequent of T a subsequence of a string is a new string which is formed from the original string from deleting by deleting some can be none of the characters without disturbing the relative position of the remaining characters like ace is subsequence of ABCDE because we can delete B and D and while AEC is not because the order is not cat mm-hmm not cat mm-hmm not cat mm-hmm so for example ABC we get a HB GD c ax c eh hpz DC and then it we get here of course this is okay and this there is no X right cool okay so the input s will be between within 100 characters and T will be very long actually I see so let's just dive into the base example okay now we're going to actually search for the sequence from ABC with in a HB GDC right let's just take a look at the first letter like a is it in it of course it's in it the first one is now okay now we need to search next be right where the first B after a ok such B we get edge and it's should be a minute and then we go to B and the fanuc and okay be found now we saw C right so and we'd go G and D and find a see well we immediately realized that we could just move through the string s and string T and when we are searching and try to search the corresponding characters in T right and this say we start at the first index 0 and then we compare if they are the same if they are same we're moving the first index moving to B and then we are search speed again right so only we will move the indexing as forward when we meet a same character and how we the end well and when we are down traversing s right cool so this actually is will be done with two cursors that equals zero J equals to zero okay Wow I swear that s talent and the Jace water then T does it while they are all within our ranches and we will compare them right so if si equals to s j TJ it means we found same character so we could move both of them forward if now if they are different then we just move J forward right we keep searching in T and so when this end it means either of them is done traversing and we only care if the I di the s is found so we return I if it is equal to s dot then okay I made a mistake smordy smord of that so this should work yeah it should be simple okay so we're done the actual we will loop through me s and T of course it says T okay so the time would be a longer one not longer well right so Oh max then max lint of s and T this is time-space there's of s and T this is time-space there's of s and T this is time-space there's nothing we use constant time well there's a follow-up if there are a lot there's a follow-up if there are a lot there's a follow-up if there are a lot of incoming a lot of s and my more than 1 billion and there's a T so how can we improve our program well from the constraint we know that T is much longer than s right so when we're certainly asked every time we search we will search the fool T actually for the worst case so it will basically depend on T actually so generally it should be o and ok s size times the teen end right so maybe we could improve that to what we prove that to the Oh sighs app and the average size of s average s so how can we do that so for each astraying we will Traverse 40 all right from start to end while we already see from this example from the wire loop here we only care about the index of the same little characters between s and T so maybe with after one Travis soul of T we could keep track of the Audion X's indices so like we are searching for ABC rather than we loop through T we could just you get directly for where AOA is right so for a so we could say the index will be 0 if suppose there is another a we get 0 5 4 or something like this of course because we are going to just to check if it is true or not we just to keep the leftmost right so we set it to 0 and they would get B we could get directly the index this index must be bigger than zero we so we couldn't choose five like suppose there's only one five we have to choose five and B 2 well 2 is smaller than 5 so force right so we need to choose weekend smallest index we has to find 2 bigger than 0 so bat it and keep track up just remember these two and now we're going to search C c/g the C's last like four to search C c/g the C's last like four to search C c/g the C's last like four see here something like this and the seat 4 is bigger than 2 so fat it and it's done so we can just check if the string is subsequence of another string with the nests of itself not the target with this we could just improve the size from T to ass right but with the extra but of course with the extra with extra space of indexes for each letter in T oh sorry I forgot to change the font size oh it's just spaced too cool maybe I can make it bigger okay so that's all for this one hope it helps see you next time bye
Is Subsequence
is-subsequence
Given two strings `s` and `t`, return `true` _if_ `s` _is a **subsequence** of_ `t`_, or_ `false` _otherwise_. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not). **Example 1:** **Input:** s = "abc", t = "ahbgdc" **Output:** true **Example 2:** **Input:** s = "axc", t = "ahbgdc" **Output:** false **Constraints:** * `0 <= s.length <= 100` * `0 <= t.length <= 104` * `s` and `t` consist only of lowercase English letters. **Follow up:** Suppose there are lots of incoming `s`, say `s1, s2, ..., sk` where `k >= 109`, and you want to check one by one to see if `t` has its subsequence. In this scenario, how would you change your code?
null
Two Pointers,String,Dynamic Programming
Easy
808,1051
1,690
Hey guys welcome to our channel co division in this video you will be talking about 10 leaves of problems cold store game and will be facing problem number seventh office serious problems cold store game ok and it's n Medium Problem Udhar Leaf Way Can Experience Of Problems Of Stone Pumice 1.10 I Think Similar Problems Of Stone Pumice 1.10 I Think Similar Problems Of Stone Pumice 1.10 I Think Similar Questions Stone Games Tom Games And Soon You Can Do This Problem Sudhar You Can Have A Better India Water Portal Serious Problem This Point To Cigarette 500 Talking About This Problem Let's Discuss What a license for telling game and gives no gratification and it's ok the end stones rans in rule lower systems which can remove here left no stone and the most stone from the product at the same time stones 21082 elite se zara indian anu certain places to eat start game Dhan Yash He Can Remove The Stone From This Position And From This Position Rate Vriddhi Possibilities To Remove Story From This App Gives You Subscribe And Water For The Statement Tyohar Isi Point To The Meaning Of Karo Subscribe Must Subscribe The Meaning Of This Dasham Starting From Plus One to the subscribe The Channel Please subscribe and subscribe the Channel subscribe karo tarf and minus one ok plate displayed avinash chavan with highest score dehydrate spot closed stones loop tourism ok own now this font only will oo all will use this cream tuesday semester third year Think So He Decided To Minimize The Producers Goal Is To Maximize Ther Differences To Subscribe And Who Wants To Minimize Subscribe To I Make It Difficult To Win The Yes OK The Address What Is The State Chief Justice To * Address What Is The State Chief Justice To * Address What Is The State Chief Justice To * Very Important Shift Solving Its Problems Strategies To Increase Add or Total Score Delighted Strategy Now That Decrease Says Unwanted Says To Now Lift Score Of The Game And Convert As Code Of The Giver Says Exactly 2 Airlines Sports - Box Ko - Box Ko - Box Ko I Only Discussed With The Idea That This Point Fee Increase Statement Not Discussed The Problem Statement We Are The Latest In And Give Energy West Indies Stone Representative Law Upa Is Time For Love Returns The Difference Take This And Box Ko Dibbs Booth Play Off K Malik Dative Want To Follow His Strategy And What Is The Finally Were Going To Get 10 Code This Difference Between The Lines In Balls To Deep Throat Cancer Let's Discuss Review Possible To Discuss With Over Now Let's Look At The Constraints And Splashed Sacrifice To Influence 12628 Most Prized In Stones Successful To Any 20822 Electrification So Straight Financial Solution This Point Work Worldwide Recorded To Take our content policies of president for registration cancel let me give to like because she takes poll interesting problem then on to learn a lot of things from air okay so let's move forward stunts problem in a little bit difficult together will double the exact pollution and Optimal solution for this problem in it's most common problems solved problems from big detail no one thing details Vinod Aishwarya subscribe to subscribe the right and what is the strategy for boost to decrease 10 to North Eastern Wave Remedy subscribe also possible Video plz subscribe and subscribe the noobs ko subscribe hai yeh test bhoot mode turn middle aged sports must increase is tried to here comes the common solution let's move like what is the solution 1512 loot liya hai ko camera tokio motor specific playlist walk and talk keyboard in general waksingh particular Player Is Going To Make Them On What Is The Strategy For Particular Players Were Already Started Out Both Want To Increase Hairs Who Also Attend Is Bodh Particular Planet Who Want To His Sermon In What Is The Meaning Of The Club School Subscribe To A Practice To Particular Place Want to Increase Hiss and Hotspot Subscribe School Weight Reduce Element Clear subscribe and subscribe the Channel subscribe our Jis Position to subscribe like subscribe Torch Light and Maximize This Player Particular Player School Speak and Return Gift Club Secretary Vaidya The Meaning of This point to taste no asfi plus one to ujjain anitya statement start with iya babuji this i plus one day this position of this situation and vansham aadha plus one comedy fight club lettuce this position element danish zahn his words for this one ok and This is the particular scorer player difficult plate use this one ok not difficult play list the meaning of this ok then to-do list manto meaning of this ok then to-do list manto meaning of this ok then to-do list manto to write in the class - said and comment it is the player of testis tuition a particular statement and this stone element And from girl f9 pro brightness that day his words code human rights and its effects neetu for all differences obliques ko dry yes - also add new segment is dry yes - also add new segment is dry yes - also add new segment is dushman ke this is the butler players point is point school head and studied at any type of this treatment For this problem element subscribe to the Page if you liked The Video then subscribe to subscribe our English One Point to Take Them 120 Two Things for It's Okay So Difficult to Maximize the Country with Dynamic Programming from Bottom Subscribe To That If So Let's Talk About Top Down For Approach Live Videos Solution Dynamic Programming Subscribe 502 and subscribe the Channel subscribe and subscribe karo Titan Ezli Brightness Ko Idli Appointment Process - Easy and Effective Appointment Process - Easy and Effective Appointment Process - Easy and Effective Se Zari Find Us Point Is Point SS - Se Zari Find Us Point Is Point SS - Se Zari Find Us Point Is Point SS - 8th OK Subscribe in Tarzan subscribe to the Page if you liked The Video then hai aur tu bhi matric site toh 101 10 ke prohibition - volume 12.5 lagayenge prohibition - volume 12.5 lagayenge prohibition - volume 12.5 lagayenge function leadership quality of life in the days of to be minus one with possibilities and demons like this Solution of Math Solve This Problem the subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to hua tha hai to it's nothing but very easy solution like DPO 1010 man last defined and definition in his life matrix is ​​minus definition in his life matrix is ​​minus definition in his life matrix is ​​minus One Ending Reminder Do Marine Interfering With Pictures From 2nd Id In Order To Approve Like Subscribe And Share Like Comment Subscribe To My Channel Must Subscribe And Share And Subscribe Me Account Statement Din What Is My Support For The Current Segment Is A Left No Stone And content support system - system Stone And content support system - system Stone And content support system - system successful ok this is my icon in travel account statement that then left most stone and what is my points ko dislike porn in coming segment incoming segment start with j plus one to economic him tuesday left most store and significant Difference Not But Since E Need To Front 10 Ko Difference Also Any Particular Place Chus Phanda Points Ko Resources Ministry Of Defense And Taxes Up Tips Stones Phad That Is Right Me Statement Of Account This Is My 592 next9 Maximum This To End Servant And Certificates Of Players can choose from alien distance from one audience at you can be turned upside down method pilot and amazon technique and you will pass all the best pina particular time ok sir jis uniform laptop download to take medicine more subscribe button click waterproof subscribe to subscribe and subscribe the That Space Exploration Difficult Traffic Jam Shouldering Unauthorized Two Time Statement Piece Jewelry Write and Administrator Define This And You Will Notice All The Positions With Boys Her Delicate Male Plays Important Role In This Needs To Be Understood subscribe for you liked The Video then subscribe to the Play list with is a right to what is the next move that you must be wondering but for players like it is this one and two know the answer for this statement right any player isko 21 dis vanshiya know the answer of this treatment subscribe And subscribe The Amazing Subscribe Like Share And Subscribe To Aam Aadmi Party Meet Pick Up This Element Answer For This Treatment Must Know Uttar Pradesh Katni Working On The Uttar Pradesh Katni Working On The Uttar Pradesh Katni Working On The Length Equal To Its An Order Condolences To The Day I Don't Know The Answer Flu Certification For All The Lunch Loot Liye Looteron Ko subscribe and subscribe the Channel Please subscribe and subscribe this Video from Dr Ki Abu Lens is equal to and you know the answer for love and like and freedom as it's ok sir no in this world is unique in more like button Click on subscribe The Channel subscribe How To Talk In Blank White Widow And My Segment Start Michael 2018 Gurjar Pimples Eye Plus And Minus One Torn Length So We Working confluence Statement IG Uninstall Surprise That Day What Is A N Sarvan More - The Like Character Positive Sarvan More - The Like Character Positive Sarvan More - The Like Character Positive Yeh Kaun Ise Glue Video plz subscribe Channel and tap on the Video then subscribe to the Channel Please subscribe and subscribe to video editor Abhilash Videos in comment section please share this video and subscribe our YouTube channel for latest updates thank you for watching this video mesh
Stone Game VII
maximum-length-of-subarray-with-positive-product
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, they can **remove** either the leftmost stone or the rightmost stone from the row and receive points equal to the **sum** of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove. Bob found that he will always lose this game (poor Bob, he always loses), so he decided to **minimize the score's difference**. Alice's goal is to **maximize the difference** in the score. Given an array of integers `stones` where `stones[i]` represents the value of the `ith` stone **from the left**, return _the **difference** in Alice and Bob's score if they both play **optimally**._ **Example 1:** **Input:** stones = \[5,3,1,4,2\] **Output:** 6 **Explanation:** - Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = \[5,3,1,4\]. - Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = \[3,1,4\]. - Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = \[1,4\]. - Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = \[4\]. - Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = \[\]. The score difference is 18 - 12 = 6. **Example 2:** **Input:** stones = \[7,90,5,1,100,10,10,2\] **Output:** 122 **Constraints:** * `n == stones.length` * `2 <= n <= 1000` * `1 <= stones[i] <= 1000`
Split the whole array into subarrays by zeroes since a subarray with positive product cannot contain any zero. If the subarray has even number of negative numbers, the whole subarray has positive product. Otherwise, we have two choices, either - remove the prefix till the first negative element in this subarray, or remove the suffix starting from the last negative element in this subarray.
Array,Dynamic Programming,Greedy
Medium
null
1,753
hello everyone welcome back to cs for all so today we are going to do the fourth problem from the stl module of the algo master sheet so it's a problem which you can find in lead code and i won't be telling you the concept right now so i will read the question once and i would ask you to think about the solution on your own if you get the solution that's great if you can't get the solution think of it twice or thrice i hope you will get to the solution on your own and even after thinking if you are still stuck you can continue watching with a video so let's get started hi again so let's read the question here you are playing a solitaire game with three piles of stones a b and c okay so we have three piles of stones okay so there are three piles of stones placed next to each other okay each turn you choose two different non-empty pipes choose two different non-empty pipes choose two different non-empty pipes okay so we have to choose in each turn two different non-empty pipes okay take two different non-empty pipes okay take two different non-empty pipes okay take one stone from those two different non-empty piles and add one point to our non-empty piles and add one point to our non-empty piles and add one point to our score okay the game stops when there are fewer than two non-empty pipes okay got fewer than two non-empty pipes okay got fewer than two non-empty pipes okay got it so given three integers a b and c return the maximum score you can get okay so basically we have three piles of stones okay and we have to consider two piles of stones in one step okay in every step we have to consider two piles of stones take one stone from each of the pile and add one point to our score okay the game stops when there are fewer than two non-empty piles okay so i hope you got non-empty piles okay so i hope you got non-empty piles okay so i hope you got the question so let's go to the miro board and understand it better with an example so we will always have three piles of stone okay so let's say the first pile has two stones in it okay the second pile has four stones in it okay so let's draw them and the third pile has let's say six stones in it okay so five and then six okay so what is a question saying has to do we can take we can consider any two piles among these three okay we can consider any two piles among this three we can consider this and this or maybe we can consider this and this okay so any combination okay time now let's suppose we consider this pile and this pipe so from each of these piles we take one stone okay so i take the stone okay and i add one point to my score so let's say this is my score and i add one point fine so this stone is removed okay now one step is over so in the next step let's say i am considering this file and this pipe so i take one stone from each i take this stone and this okay and i add a point to my school fine again i consider two piles of stone okay so let's say i am considering this pile and this pile okay i'm considering this two pair so i take a stone from here okay done i add a point here fine now this pile of stone is finished right this is completely eliminated i used two stones from this pipe now what remains this two pile remains right and how many stones is there are three stones here and there are three stones here okay so how many stones can we take in each step two stones one from here score added one again one from here score added one okay so when does the game stops when we cannot make a move anymore so the game stops here so what is the score is one two three four five and six okay so we have to find the maximum possible score okay so i hope you understood the question i will be taking one more example let's say we have four and six okay so i this time i will be just writing numbers four and six so in this pile there are four stones in this file there are six stones okay so let's say i consider this first pile let's name them okay two and three these are the three parts so the very first step i consider first and the second type okay so i remove one from each what is the score this four is one okay again let's consider first and second time so i remove one from each so what is the score added is one plus again the first and the second tile i remove one from each score added is one again let's say i remove one stone from the first and second pipe so the first and second pi becomes empty now i have six stones in the third pipe but do i have any other pile i do not have any other pile i at least need to pile to carry on a step i have only one pile that is the third pipe so my entire game stops here and what is a maximum score i can gain the maximum score i can gain is one plus one that is three so this is the thing which we need to do we have to maximize the score so i hope you understood the question completely now we will head over to the solution but i encourage you to solve the question on your own think of it do a heightened trial for two three times i can guarantee you will get to the solution on your own so if you have tried on your own and still couldn't get to the solution continue watching with the video so again there are three possibilities of considering the piles of stones so let's say we have three piles right so the first pile is let's say two then the second pile is three then third pile is four so what options do we have first option is we can pick up the piles with the highest number of stones so we can pick up two piles with the maximum number of stones so what are the two pies here three and four right so this is possibility one but the second possibility is we can pick up two piles with the minimum number of stones so what are the minimum number of stones two and three right so we can pick these two piles third possibility is we can pick up any random pile okay we can pick up two and four or maybe three and four or maybe two and three okay so any random pile in any step okay so these three possibilities are what we are going to figure out okay we are going to try run through these three possibilities so let's do that so as we said we have three examples so for the first possibility that is picking up the maximum bias okay so two three and four okay so let's say we pick up from four and three and i will be making a score here okay so we pick up from four and three so what's remaining two and three right okay done and score is one okay then we pick up from the maximum to what are the two maximum two and three right so we pick up from them again so it becomes one and two right and we add a score of one here now what are the two maximum the two missions are two and two right we pick up one from them so what it becomes one right and we had a score of one now what are the two maximums we can pick any of them once right so let's pick these two ones all right and this two becomes zero and this becomes one okay and we add a score of one here now can i continue any more we cannot continue anymore from here because we don't have two piles remaining we have only one pipe and we cannot go any further with one pile okay so this is the maximum score we can reach out to if we consider maximum piles at every step okay so this is four okay now let's consider the of pies in every step so we had two three and four right so what is and we have a score here okay so what is a minimum two and three right so let's pick them okay and add a score here again what is the minimum one and two right so let's pick them and add a score here okay now what is the minimum okay so zero it's totally gone right so we cannot pick up from here the minimum would be one and four right so let's pick from here and there okay so add a score up here now can we move any further with this current combination no because we only have one pi left we do not have two piles left so we cannot move any further so what is the score this time the score is three and last time the score was four okay now let's try picking up random piles okay let's try picking up random players so two three and four add a score here okay so let's pick up two and four okay so it becomes three and it was three right now let's pick up three and okay i have to add one score here okay now let's pick up three and three so what do we have two and we have one and we add a score here now let's pick up two and two okay so what do i have we have one and one so add one here okay now let's pick up this one and this one okay zero and we have got a one here so this we cannot move any further with this so this score is four and four okay so what we can see is if we pick maximum piles okay if we pick maximum piles we get a score of four and in this combination we pick the random files and we are getting a score of four okay so that's quite contradicting so we need one more example to get the things right okay so let's do that so let's see one eight and eight so we will do for first for the maximum and then for random and we won't do for the minimum one because that has already been eliminated in the last round okay so let's see the score is yes well let's pick the maximum here 8 and 8 that would become 7 and this will become 1 score of 1 here again 7 and 7 would become 6 and 6 this will be 1 and score of 1 again here again this will be 6 will give me 5 score of 1 here 4 score of 1 here 3 score of again 1 here 2 and 2 again score of 1 here 1 and 1 again score of 1 here and finally we had 1 here right again 1 and 1 this will give me a 0 and a 1 score here so can we further move with this combination no because we only have one pile left so what is the total score here one two three four five six seven eight okay so total score is eight this time for the maximum for picking up the maximum pipes okay now let's pick up random piles so let's say one eight and eight okay so let's pick up one and eight okay so that becomes what zero and seven and this is eight right so the score is plus one here for this removal and this removal now what i can see from this two figures here is if i continue seven more steps this will be completely eliminated and this will be zero and this will become one right and here seven will be added because in seven steps we will be adding one each right so seven will be added so this will also be a maximum score of eight right now one flaw with this particular approach of picking a random piles is it will depend on the pies which you are picking okay it will depend on the buyers which are picking you might get a score of two as well you might get a score of eight as well okay so it totally depends on the combination you pick but by picking maximum piles every time that is in every step that guarantees me the maximum score possible so we will be going on with picking the maximum bias in every step okay and we will eliminate this approach as well okay so let's go to the solution now how can we execute this so what we can do is we can take a max heap and as we said uh if we have four six okay so we will be inserting all of them into the max 8 so 4 6 and we will be taking a score up here so what we will do we will be picking up the top most element that is the maximum element we will eliminate them here they will come outside four six we will reduce them by one okay so this will become three and five and we will add a score here and again we will push three and five back into the max shape okay so what we will have here we will have four three pi okay again what are the maximum elements four and five right so maximum elements are four and five so i have to uh bring them out so four and five i bring brought them out i will reduce them by one okay i will add a score up here and i will again push them into the heap okay i push them into the game what is the heap now the heap is three four what are the maximum elements three and four right i bring them out i reduce them by one so two and three they become and again i push them into the heap right and the score will be plus one here what is the maxip now max apis three two and three right what are the maximum elements three and three right i bring them out okay i bring them out i reduce them by one so this becomes two and i push them back again okay and score is plus one okay so what is the score right now score is four i will be writing this up somewhere else because the space is getting congested and what do we have here we have two comma two in the maxip okay so the score is four and we have two comma two in the maximum okay we pick up two maximum elements we bring them out two comma two we reduce them by one we add a score here and push them back okay so these two were eliminated what do we have now one comma two comma one what is the maximum element this one right we bring them out eliminate them here one comma one we reduce them by one they become zero we add a score up here we push them in here so what is the heap now what is the max it now we only have two now because no need of pushing zero right no need operations we cannot reduce them further so we only have a two now so can we go any further with this no so whenever our max heap will have only one element in it we will stop and we will return the total score so what is the total score here total score is six right four plus one so that is how we will do it now let's go to the coding part okay so what do we need first of all we need a max heap so let's make a maxi that is priority queue okay so in data type and let's name it basket again as i always name so then what we have to do okay let's increase the size of this many students say to increase the size of the code so here it is okay so priority queue basket okay now what we have to do we have to insert a b and c that is all the three files into the priority queue so basket dot push a basket dot push b basket dot push c okay done now what we have to do until and unless basket size become one we have to contain the operation okay so while basket dot size not equals to one we have to continue the operation now what we have to do is okay so we have to eliminate two maximum elements from the basket at every step right so we have to do that let's name in the left equals to basket dot top and then a basket dot pop okay and right equals to again the second maximum element so basket dot top and basket dot pop right now what we have to do is we have to reduce these two elements by a one right so left minus right minus and then what we have to do we have to push again this reduced elements into the priority queue so basket dot push left basket dot push right okay and one more thing we have to keep a check if the left hand or the right becomes zero we don't push them anymore into the basket okay so you have to keep that check okay if left okay left not equal to zero then only push same thing for right if right not equals to zero then only push and what will be the score let's name answer equals to 0 first so every time my answer will be incrementing by a value of 1. so every time my answer will increment by a value of 1 okay so let us write an answer let's try running the code okay so it's running let's try submitting the code okay it's submitted so i hope you understood the solution the intuition and everything behind this video and still if you have any doubts you can comment down below or you can directly reach out to us through linkedin or join our telegram channel we have daily discussion over there and if you really like the video please consider dropping a like subscribing to the channel and share it with your friends so see you guys in the very next video till then stay happy stay healthy bye it's my life i
Maximum Score From Removing Stones
path-with-minimum-effort
You are playing a solitaire game with **three piles** of stones of sizes `a`​​​​​​, `b`,​​​​​​ and `c`​​​​​​ respectively. Each turn you choose two **different non-empty** piles, take one stone from each, and add `1` point to your score. The game stops when there are **fewer than two non-empty** piles (meaning there are no more available moves). Given three integers `a`​​​​​, `b`,​​​​​ and `c`​​​​​, return _the_ **_maximum_** _**score** you can get._ **Example 1:** **Input:** a = 2, b = 4, c = 6 **Output:** 6 **Explanation:** The starting state is (2, 4, 6). One optimal set of moves is: - Take from 1st and 3rd piles, state is now (1, 4, 5) - Take from 1st and 3rd piles, state is now (0, 4, 4) - Take from 2nd and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 6 points. **Example 2:** **Input:** a = 4, b = 4, c = 6 **Output:** 7 **Explanation:** The starting state is (4, 4, 6). One optimal set of moves is: - Take from 1st and 2nd piles, state is now (3, 3, 6) - Take from 1st and 3rd piles, state is now (2, 3, 5) - Take from 1st and 3rd piles, state is now (1, 3, 4) - Take from 1st and 3rd piles, state is now (0, 3, 3) - Take from 2nd and 3rd piles, state is now (0, 2, 2) - Take from 2nd and 3rd piles, state is now (0, 1, 1) - Take from 2nd and 3rd piles, state is now (0, 0, 0) There are fewer than two non-empty piles, so the game ends. Total: 7 points. **Example 3:** **Input:** a = 1, b = 8, c = 8 **Output:** 8 **Explanation:** One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty. After that, there are fewer than two non-empty piles, so the game ends. **Constraints:** * `1 <= a, b, c <= 105`
Consider the grid as a graph, where adjacent cells have an edge with cost of the difference between the cells. If you are given threshold k, check if it is possible to go from (0, 0) to (n-1, m-1) using only edges of ≤ k cost. Binary search the k value.
Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
Medium
794,1099
274
welcome to august leeco challenge today's problem is h index yes my favorite h index given an array of citations each citation is a non-negative integer each citation is a non-negative integer each citation is a non-negative integer of a researcher write a function to compute the researchers h index they give you the definition here but basically the h index is the index point at which this researcher has at least that many citations at least that many papers with that many citations so here the answer would be three because we have at least three papers with three citations and that's the maximum number that we can use so to give a few hints here first you can sort you could think about what the h index is represented by and also use extra space now let's start off by thinking about what we can do if we sort the array so if we have this example and we sort it in order it would end up looking something like what 0 1 3 5 6. and each one of these points is going to be representative of the h index and at index number 0 we have at least five papers with zero citations or more well obviously that's going to be the length right what about index point four well that there we have at least four papers with one or more here we have three here two and finally we only have six one at point six right so why not just sort and what we'll do is um go in order and return as soon as the h index is uh let's say or i should say the value of the citation that's at the h index is greater or equal to this h index number so that's fairly simple enough let's start by initializing the length of citations and we'll sort our citations and we'll then we'll just say all right for i index number and value and enumerates the citations we'll say hey if the h index that we calculate is i guess less than or equal to the value that we're on then we just return the n minus i so that's the uh h index and if we just don't find anything then we return zero if we do that should look like it's working and that's the straightforward method now there's lots of variations you can like simplify this to make it a one-liner and stuff like that one-liner and stuff like that one-liner and stuff like that but what if we want to do this in o of n time complexity because this sorting here is going to require to become n log n right so kui like this hint number three said create some sort of object use some extra space and do this in uh without sorting we can do it in o of n we can't do it in one pass but possibly do it in a couple passes making it of n time so how can we do that all right well let's just say we can't sort what object can we use to indicate what we're trying to find out so say that we had we can't use a dictionary because the order matters right but if we had a list where each index point is calculating the total count of how many citations we have then maybe something like that gets becomes possible so we're gonna need an extra one because we have also the zero citations here we can say this can be index five right zero one two three four five we'll say hey if we if the number is five or greater then uh increase this because we have a count right there because ultimately the h index could only be the highest one is going to be the length of the list right so say that um we see okay we'll start with three and say okay we have at least one number here with like that's not three so sorry get rid of this here's zero one two three we have one with at least three we got one with zero we got uh one with five or greater so one here and then five we have two so now we have this temporary object and we can say to calculate the h index each one of these is now representing an h index we can return we'll say hey do we have at least five at this point no we don't so we keep continuing and do we have at least four up to this point no okay and we're going to be accumulating the total sum like moving it forward so at this point we have two here we add this and now we have three do we have at least three and we do so we can return three there and you can see that we've created this in one o of n and then we go backwards to that which is also of n so this becomes well of n time complexity the problem is we need this extra memory space right okay so how could we do this let's get rid of all this stuff and start with creating a temporary object and we'll just say all these will be zeros four whatever in range of n but we need this plus one here to indicate the zero part as well so that's a little tricky to remember so now we have a temporary object and we're going to go through our citations the same way so for enumerate citations and we'll ask very first thing we want to ask is this number um greater or equal to the length that we have because if it is then we want to just increase the last index point there right so if the value is greater or equal to what uh i should say not greater or equal to it's greater than n then we want to increase our last point there by one otherwise we take our value and we increase that by one so at this point we have our temporary object and it should look something like this so this is the tricky part now we want to count backwards and accumulate the total that we have so far by moving backwards because we want to get of course the largest state index that we can get so 4i in range of start with n and we'll say minus one and first we'll add to our total whatever is um at our temporary point say put that and if our total is um our total is i guess greater or equal to this i point that we've calculated because we want 5 4 3 right so greater or equal to this i then return bi and i want to say that sits like i don't think we need any more than that so oop let's get rid of my comments there see if this is working okay it looks like it is let's go ahead and submit that i hope i didn't forget any edge cases and there we go accepted so this is all event time complexity pretty tricky to figure this out um but it's essentially using extra space and creating kind of like a counter but we can't use a dictionary we need to have this in a list after that you can kind of figure out oh we can still figure out how many total papers we have with this many citations by moving backwards all right so that's it so thanks for watching my channel and remember do not trust me i know nothing
H-Index
h-index
Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_. According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times. **Example 1:** **Input:** citations = \[3,0,6,1,5\] **Output:** 3 **Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. **Example 2:** **Input:** citations = \[1,3,1\] **Output:** 1 **Constraints:** * `n == citations.length` * `1 <= n <= 5000` * `0 <= citations[i] <= 1000`
An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space.
Array,Sorting,Counting Sort
Medium
275
472
hello everyone let's solve today's lead code problem concatenated words we are given an array of words and we need to find out order concatenated words in the given words array in this example cat dog cat is comprised of cats dog and cat so it is concatenated word and dog Cat's dog is comprised of dog cats dog so it is concatenated words and the red cat dog cat is comprised of cat lead cat dog cat so it is also concatenated word we can serve this problem using bottom up dynamic programming let me show this example we have five words cat cats horse seahorse and Cat sea horse the last one Cassie horse would be the only output let's see how we can calculate it at first we will initialize the P array variable and its length is word length plus one index 0 is true to make calculation easy add DP from index 1 to index ranks and are initialized by force we will iterate about all the subsequences by end index grows one at a time and starting text grows one at a time like this way by doing this we can check all the subsequences from the front side to the rare side and we can see that is sub problem plus support like Cassie case we've had cat in the words and we are trying to find the C in the words but it's not in the word so dp6 will be Force but if we have C in the words then dp6 would be true because we've already known solve problem part cat is served and it's true and the support part C is in the words so we can know that it is true okay let's do this example we start to hear C it's not in the words so we move on we checked is CA it's not in the words so we move on we check this a it's not in the words so we move on we check cat it's in the words so and it's sub problem was solved and it's true so we update tp3 with true it means we know we can make cat we check these cats now it's also in the words and its sub problem was solved and it's true so we update the P4 with true and we move on we can find any of subsequences in the words array finally we reached to the last index but at this time we can't start from the first index because the subsequence from the first index to the last index is the word itself so we have to avoid it so we move on to the next we find out cat is served and it's true and the seahorse is in the words so we update dp11 with true so Cassie horse can be the answer okay let's cut it we declare word set and we check the possibility of being a correct answer for each words we initialize the pra for calculating about 12 DP and we check all the subsequences of a word from the front side to the left side if DP is not served yet then we track this it's a solve problem the PJ is true and the sub word is in the word set and we'll restrict the word itself to be calculated after all iteration for subsequences is finished if the last element of DP array is true then the word would be the answer okay we made it these Solutions time complexity is Big O of N squared Pi M squared and here n is word length and M is a word length like a cat this is in this is m and this is M and this is an so time complexity is this and space complexity is Big O of n plus M because word set is n space and dpra has m space I hope you enjoyed this video and it was helpful and I will see you soon bye
Concatenated Words
concatenated-words
Given an array of strings `words` (**without duplicates**), return _all the **concatenated words** in the given list of_ `words`. A **concatenated word** is defined as a string that is comprised entirely of at least two shorter words (not necesssarily distinct) in the given array. **Example 1:** **Input:** words = \[ "cat ", "cats ", "catsdogcats ", "dog ", "dogcatsdog ", "hippopotamuses ", "rat ", "ratcatdogcat "\] **Output:** \[ "catsdogcats ", "dogcatsdog ", "ratcatdogcat "\] **Explanation:** "catsdogcats " can be concatenated by "cats ", "dog " and "cats "; "dogcatsdog " can be concatenated by "dog ", "cats " and "dog "; "ratcatdogcat " can be concatenated by "rat ", "cat ", "dog " and "cat ". **Example 2:** **Input:** words = \[ "cat ", "dog ", "catdog "\] **Output:** \[ "catdog "\] **Constraints:** * `1 <= words.length <= 104` * `1 <= words[i].length <= 30` * `words[i]` consists of only lowercase English letters. * All the strings of `words` are **unique**. * `1 <= sum(words[i].length) <= 105`
null
Array,String,Dynamic Programming,Depth-First Search,Trie
Hard
140
1,318
hello so today I'm going through problems of this weekly contest 171 we'll start with the I'm going to do now the second problem which is minimum flips to make a or B equal to C and so the problem says we get three positive integers or numbers a B and C and we want to return the minimum number of flips in some of the bits of a and of B so that we can get a or b so or he is binary or you can get C and then the flip operation basically he is considered changing one to zero or changing a zero to one in a binary representation of A or B and so we could see here a binary representation here when a is equal to two it's a zero one zero four be equal to six it's zero one zero right and so when change it here you could see so here they are not equal to C 0 or 0 is 0 right so we need to change here one of them so we change one to zero so that we can get service we change one zero near to one so we can get one or zero to get one and for these two which are ones we want to change them to we want to because one more one is one so we want to change them to zeros to get 0 so Shane put through 0 and 0 or one that's already one so like that there is 0 or 0 that's 0 so in order to get C we need to change both 0 the first 0 in a to 1 and the second 0 to for a to the 1 in a to 0 and then this one here me to change to 0 and when we do that we get the result so we had to change the 3 bits to get C and so that's why we return c we return 3 here and the rest of example have a similar thing is this these are the ranges we are dealing with so here you can see that like a double loop for a and B where I will try each combination and is changing a bit won't work and so let's see how okay so let's see how we can solve this problem so here what we had was that the solar system example here so the first example that the problem gives is we have a right which is equal to 2 and then we have B which is equal to 6 and then we have C which is equal to 5 right and so if we take the binary representation of each then we get for a it's 0 1 0 for B its 0 1 0 and then for C the binary representation is 0 1 and our goal basically is to make these or of these equal which is not the case right now right so what would do we need to do so you can see here just from doing it manually what I'm doing ok it's 0 right and I need one so I don't have to change something so I have to change this 1 0 here to be 1 or it or change the other one to be 0 whichever one we can do both here I have one giving me one but actually I need 0 ok so I can change this to 0 but the problem that's not enough I still get one with the earth so I need to change this one to 0 2 and so and pretty much once I do that I've got C right so you can notice some observations from what I did here manually right so the observations that we can make from this is first what we did is go column by column right by column and by column I mean here the bits that are here right column by column which means basically it's by the from left to right in the binary representation right so from right to left in the binary presentation right and so by that I mean that what we need here is so by that we can deduce that what we need here is getting the bit in the current carbon right and they cannot come so that's what we need and of course getting the bit and is just with basically finding if it's set or not right if it's zero or one it can be either the wrong one so finding the bit means just figuring out if it's set or not and we can do that by doing and one right so if you take some value of x and you say and one that will give you either 1 or 0 depending on whether it's set or not right so we know how to get that right and then now we need to know how can we go to the next column right so how to go to the next column that's the other part of navigating from column to column right so here how to get to that to go to the next column so that's also it's very simple right with binary in order to get to just move off of the first bit here to do that you could just say X like this equal to basically by shifting to the shifting right and so when you shift like this you will remove kind of this 0 1 and then when you do end 1 again you will get the second one here right which is what we want and we do that again to get this third one and we keep doing that until the value is 0 right and so here so iterating means we need to find out how we advance and we to find out you are done and here our case here done means the value is equal to 0 so done here means X is equal to 0 right except here there is the other caveat here is that we need to remember so we deal with is that we need to navigate for basically a B and C right because that's what if you had an addition of numbers three four plus a plus five six one zero for example you will need to navigate here and do fall you need to ever get here and you need to it until you are done with all of them right so when you reach zero if you have let's say numbers and you want to check if they are equal you would do the same thing right you would wait until you finalize every all the numbers you traverse all of them right and so we know who here how to traverse and we know how to check the bills now how can we know the minimum number of flips that we need to do so one thing you notice that I did here is that for the case where it was so for the case well so counting the minimum flips how do we do that while traversing in this way so we know how to get the bits that are settled now how do you count the minimum flips so you can notice here in when I was doing this when I did one so there was this one let me just repeat it maybe here so that it's clear so a was this 0 1 0 and B was or is 0 1 0 and C is 0 1 right and as we said we are traversing from here to the from the right to the left right so when I was doing it I said the volume here is 1 right so the volume here is 1 so to get 0 to be 1 I need to change one of them to be 1 right so when both are zeros here so let's just enumerate all the cases so when both bits are zeros so that means change one of them to or flip one of them to get one so here and C is equal to 1 that means flip one of them to get one right and then here we see when both were 1 I just replaced it this was 0 but that wasn't enough because I'm still getting 1 and so I need 0 so you could deduce from this is that when both are 0 and the one at position C is equal to 0 sorry on both are 1 then we need to flip both right so the count here is equal to 2 we need to increase the count by 2 and here we need to increase the count by 1 but this is not generally enough so we need to generalize this intuition here a little bit more so that we can find a solution right so one thing way one way to generalize it is okay let's just give these some annotation here so let's say at a position at current position while we are traversing right let's call X is equal to the bit at position high at position for a so that's what we get with X + 8 + 1 right so this is what get with X + 8 + 1 right so this is what get with X + 8 + 1 right so this is what we will get with a + 1 and then for 4 we will get with a + 1 and then for 4 we will get with a + 1 and then for 4 and then we will say Y is the bit at the position for be right and what's called Z the bit for C at the current position and we will get this one with B and one will get this one with C and one right and so we have two cases right so either we have X in binary right since X is a binary X or Y is equal to Z and that is do nothing right because that's what we want all the bits for a line here with C or now they are different in that case we have multiple cases so in that case well we have a case where we need to change everything which is the case when both are equal to one because we need to do two flips at that point so here if X is equal to 1 and why is equal to one that means we need to do two flips so that means here we need to do count plus two now if that's not the case so if let's say if both are not equal to I so we have a couple of cases right ada X is equal to 0 and y equal to 0 or X is equal to 0 and y equal to 1 all we have X equal to 1 and y equal to 0 right and so in all of these cases what we know that X or Y is different than that right so since for the case where both are zeros and said is do X or Y is different than that means that said must be equal to 1 because otherwise they will be equal so in this case that means that we need to just flip one of them to get one right we just flip X so we get 1 or 0 which gives us 1 or will flip why and we get 0 or Y or 1 which gives us 1 right so that means we need one flip right so let's call this so it needs one flip one and so this would mean we can do count plus 1 right the other case is that the other case is this case where x equals to 0 and y equal to 1 so since it's X or Y is different than that means that must be 0 because otherwise this would have been equal so Z must be 0 so if that must be 0 then that means that so let's just write this in the same color so this is count plus 1 so here that must be zero so that would mean in this case that we need one flip right we can just flip Y to zero to get both to be zero and to get Z to be zero so we need one flip here too which means here we can do just count plus 1 for X equal to 1 and y equal to 0 again same reasoning X or Y is different than set right which means Z 1 + 0 is 1 so that right which means Z 1 + 0 is 1 so that right which means Z 1 + 0 is 1 so that must be 0 again so the same reasoning and that means we can just again just flip X to 0 and we need we get what we want so we need one flip which means count + 1 so this way we can shut our count + 1 so this way we can shut our count + 1 so this way we can shut our eyes this now right because we know that the only case what we need to do two flips is this one when they are different when X or Y is different than said the only case where we need to flip is one X equal to 1 and y equal to 1 all the other cases we need to count 2 plus 1 so now we know what to do so let's just write the code for this so we have definition of we min flip that's what we are doing here and we have a B and C right so we're going to count how many of how many flips we need so this is just the quality clarity valuable for that and we wanna we want to keep going until as I said here in the section for the iteration we need to go column by column until we can go no more right and so that's we are we will wait for all of them to be equal to 0 that would mean that we are done so we will keep going while a is different than 0 or B is different than 0 or C is different than 0 so until we exhaust all the bits for all of them will keep continuing and so now let's extract x and y and set right which is the bit the bits at the current column for each of B and C so 4x that would be the value at position a so that's we can get it with a and 1 that's what I said yet to get to extract a bit at the lower position or the last position we do that for y we do B and 1 for C we do C and 1 sorry for that this is that okay so now we can do the conditions that we described it here which is or either X or Y is equal to Z or it's different right so if X or Y is different than that's where we'll do something the other case we don't need to do anything so we just skip it so here we have two cases as we said we have either both is e are equal to 1 then we add 2 to the flu number of flips in all other cases we add 1 right and so we say if X is equal to 1 right and Y is equal to 1 then in that case we have to add 2 flips right in the other case we need to add just one flip and then that's pretty much all there is to this portion and then we need to move to the next column right so that we can continue iterating and to move to the next column as we said it's by shifting and so we just shift each one of them a B and C so that each one of them moves to the next column here so we process it this column so we need to move to the next column here right and so to do that we just say shift a and then shift B and that should see then at the end when we are done we can just return the count and that's pretty much all there is to the solution okay so now let's write this in late code and make sure it passes the test cases that we just saw in the overview and so same well loop here and here we are getting the bit at the cannot column for each one of them if they are different we have either two cases both are equal to one then we have to change to flip both bits so we add two all we otherwise in all of the other cases we can just flip one of them and then we move on to the next column and at the end we return count so let's run this and submit it so here if you could see we Traverse at most the length of the unit of the longest one of them so number of bits so it's really just the number of bits that we can have for these numbers so it's not don't take a lot of time okay so that passes yeah so that's so for this problem thanks for watching and see you next time
Minimum Flips to Make a OR b Equal to c
tournament-winners
Given 3 positives numbers `a`, `b` and `c`. Return the minimum flips required in some bits of `a` and `b` to make ( `a` OR `b` == `c` ). (bitwise OR operation). Flip operation consists of change **any** single bit 1 to 0 or change the bit 0 to 1 in their binary representation. **Example 1:** **Input:** a = 2, b = 6, c = 5 **Output:** 3 **Explanation:** After flips a = 1 , b = 4 , c = 5 such that (`a` OR `b` == `c`) **Example 2:** **Input:** a = 4, b = 2, c = 7 **Output:** 1 **Example 3:** **Input:** a = 1, b = 2, c = 3 **Output:** 0 **Constraints:** * `1 <= a <= 10^9` * `1 <= b <= 10^9` * `1 <= c <= 10^9`
null
Database
Hard
null
421
hey everybody this is larry this is day 16 of the leeco daily challenge uh hit the like button hit the subscribe button join me on discord uh and let's get started on today's maximum xr of two numbers in a way okay um okay i mean it is what it sounds like and i think uh if you have you know the naive way would be just n square right and i don't know what n is but if n is small enough then you can do it i would say just from experience uh whenever you see maximum xor um my mind uh goes for two things right one is greedy and the other is by using a try and the reason why you get a try is that uh you look at the bi so xor or is an up uh it's um it's an operation on the binary numbers or more specifically binary representation of a number right so let's say you have the number uh or you know that's actually you know just for a thing for x and nums uh print binomial number of that right so let's say we have this on the test put cases uh so you have this um so now you have these strings and you know you have some prefix that you know that goes of it as well uh apparently just five digits but uh and we could just we move to zero b so you have kind of you know i'm using five digits as a representation but obviously an n still be 32 digits right but you can see that um ideally what you want here is well what do you want right well you want a number such that um you want a number because um in a maximum xor you only want one number where it is you know there's a one in it right and then after that you look at here so now you select this number um you can go okay it's still a number such that um you know uh but basically the idea is that uh you always want to max it's greedy in the sense that you always want to maximize the leftmost digit or the most significant bit right because you always want to one here because no matter what happens in behind the first digit um if you have a one there it's gonna be better than whatever you have because it's gonna be one or zero and you know and in this case this is um two to the fifth to the fourth oh yeah this is two to the fourth which is 16. uh 16 is going to be bigger than you know the rest of it combined even right so that's where the greedy works so we'll have um we'll try to optimize for the first digit as much as possible and then we'll optimize for the second digit right so that's our strategy for well that's why whenever i see maximum and xor i always think uh try um because then we can go down the list in that order and then from that for me it's just going to be naive right um because then now we can look at uh a tri data structure we're going to have 32-bit um have 32-bit um have 32-bit um length um and then we're just going to go backwards to uh look through every number we process to see what's the best way to go and what i mean by that is that for example let's go back a little bit to this um let's just say you know we go one number at a time so we have a try that consists of this right and then we when we insert this well as much as we can we want to make it so that this plus whatever is in the previous try uh will give you the number that gives you the highest bid at each representation right so then you do a traversal of the try from that um keeping greedy that you always uh optimize for the most significant bit or the leftmost bit uh to be one as much as possible and then you just kind of traverse the tree that way um that's how i would kind of go about it uh i'm going to explain it because this is easier to explain as i go through the code so i'm going to explain this while i code so definitely stay along with me but that's kind of the general idea of basically the general ideas greedy and tries cool so let's do it so basically my thing would be how would i do it right so basically for x and nums um i'm gonna well let's just say try and we'll uh we'll mix up some language over there we'll go over um what uh how to use this try but i'm just gonna write the structure which is for x and nums we're gonna write tristar at x at the end and then but only if um you know maybe something like best is equal to zero best is you go to max or best uh try dot get x or get max for x maybe something like that and then just return to best right so that's gonna you know this is very simple code and that's kind of my intuition or how or my algorithm for how to solve this problem is for each number in nums we do some magic and try and we'll go over the magic and then after that we add it to the number of the things that are already processed and because we know that well this is going to be all of 32 because we're going to go it's going to be at most 32 bits uh it's going to be oh so all of 32 is all one and add is also going to be at most 32 bits so also one that this is going to be linear time uh and yeah and it's going to be linear space for similar reasons but let's implement class of try then right so now we have to initialization uh so self. i um so i always write things to a similar way and it's a little bit more verbose but it allows me to uh be very clear of what i want to do so this is my root and then and i always define the uh things on the edge so yeah uh so add a number so how do we add a number right so when we add a number we want to add edges at a time so let's say current is equal to sub that rule and this is basic try stuff i would recommend going over it um if you're unfamiliar with what i'm doing at this point but we'll go over the magic part later so um so now in this case we actually want to do it 32 times because we it's always go in this case the try is always going to be fixed in that it's going to be 32 bits um yeah and so because we want the most significant bit first we want actually we want this to um be we want this to go from not from 0 to 31 but from 31 to 0. so you could write this in a different way maybe like this in python um and i'll oh actually i do need to write offset whoops so yeah and then now we check right if x uh so we basically what this does and this is these are uh binary operators all right and basically just checks whether um the bit in the offset bit is a one or zero if this is a one then we do current um we want to do current dot i don't know add one and then current is equal to kern dot get one you could change up the api a little bit uh otherwise but uh but this is what i'm going to do so basically this just adds then adds an edge to one and then we just move to edge along so that's kind of how i would do the add and yeah and let me actually implement the node class for a quick second and it's just stop that edge edges as you go to a hash table and now we have to support add uh add x i guess uh we want to add x we just go to do as you go to node if x is not in edges or self.edges uh and get ship is more straightforward oops it just returns self dot edges of x uh okay uh and then maybe we have do another one that just has maybe like has edge but we turn x inside that edges right uh and then now we go the magic the hard part is get max 4 self.x and for that you know we start 4 self.x and for that you know we start 4 self.x and for that you know we start at the root as usual um and again we do need this offset thing so um so yeah for offset in range of 31 minus 1 -1 offset in range of 31 minus 1 -1 offset in range of 31 minus 1 -1 basically now what we want to do is we want to get the answer right so that's well okay maybe that was an obvious statement but um but now we do a lookup table right so if uh it's the same thing right if the most leftmost bit uh is a one then what happens well now if the leftmost bit is a one given in our in incoming number we want to see if there's a zero in the first digit because if there's a zero in the first digit then that preserves the first digit as one right so let's do that so current um you could do it another way maybe i'll do this another way yeah okay so that means that so if the incoming bit is uh of one we want to try to get zero if we can so um so now if current that has zero um yeah if current dot has zero current goes current dot get zero right because that's just the greeting otherwise current is equal to current that get one right uh because otherwise uh this should exist as long as the try has one number you have to go down a path because you're forced no matter what and then inverse is true for this basically the idea here on this one is just that if the incoming bit is zero then you want to find a one in a previously seen table right so this is kind of the idea we this is we're almost done maybe uh and then now what we have to do is just well now it's good that we travel down this path but we want to get the answer right so if this is the case uh let's just maybe record the previous is a better previous number so the previous number we incremented by zero right so here we want to off shift it by left by one so yeah so uh obviously this doesn't do anything but i just wanted to draw it out for uh illustration purposes uh for educational purposes but basically what this is saying is that okay we start at zero every time we shift the number by one right so that's why we multiply by two and then if the current number is zero then we just add it to zero and then otherwise add it to one and at the very end we get the number that would give you the max uh max number for x but to get the actual value we just return x uh xor the previous i think that should be good as long as um try has at least one number in it so yeah uh so we could try real quick and it should give us um some error about uh yeah not found right because um because we do it for this first digit so we can do something like um there are a couple ways to do it but i'm just lazy so we could do just we add the first digit and then um do it from the first or first number and then do it from the first digit on and then we should get the x uh expected answer um yeah this is pretty fun but uh let's go over a couple more answers i guess just because uh i am confident about the algorithm i'm not super confident about their implementation just because um just because you know when you have 63 lines of code there's a lot of uh possibilities just for typos right uh i'm gonna want a random 100 numbers generator i'm just googling this when i use random.integer so let's see i use random.integer so let's see i use random.integer so let's see uh okay i do have the numbers but they're not in a good format okay maybe that's useless so let's just bang on the keyboard for a little bit um okay maybe that's good enough of a random number let's give a quick go give it some love um yeah and if you know that right now i'm uh confident maybe the only thing that is having zero input elements uh we don't check for that i don't know if that's rounded input uh maybe we should check for it because i feel like i always get bitten by these yeah okay uh so let's just do if length of number is equal to zero return zero actually it's not clear what do maybe the answer should be undefined but maybe that's okay i guess it's a non-empty array actually non-empty array actually non-empty array actually um and we tried one number so okay let's just submit it then cool uh and again we already we actually already went over the complexity in the beginning but um but yeah for you know this is going to be 32 operations because if you look at this um you know we just do a literally do a fall to put 32 um operations and each of these just does um just do a has and a get and both of these are all one because it just doesn't step off a hash table right um and add similarly uh all it does is do an add and again and both of these will be all one so everything will be all one so this is linear time and this is linear space because um you only need over one things per item um so it's gonna be linear space because in try you're gonna have at most one note per sorry well at most you're gonna have 32 notes per item uh but you know that's not likely to happen per se so yeah linear time linear space um yeah cool uh i think the trickiest part about this part is this problem is just the visualization um definitely take a look at this um i think the logical part is the tricky part the implementation part you could figure out if you familiar tree it's just that you know if you have a one you want a zero because x or one and zero gives you a one and so forth and reverse uh otherwise i think that's the logic that i would go with um yeah uh that's all i have for this problem let me know what you think hit the like button hit the subscribe button join me on discord and i will see you tomorrow bye
Maximum XOR of Two Numbers in an Array
maximum-xor-of-two-numbers-in-an-array
Given an integer array `nums`, return _the maximum result of_ `nums[i] XOR nums[j]`, where `0 <= i <= j < n`. **Example 1:** **Input:** nums = \[3,10,5,25,2,8\] **Output:** 28 **Explanation:** The maximum result is 5 XOR 25 = 28. **Example 2:** **Input:** nums = \[14,70,53,83,49,91,36,80,92,51,66,70\] **Output:** 127 **Constraints:** * `1 <= nums.length <= 2 * 105` * `0 <= nums[i] <= 231 - 1`
null
Array,Hash Table,Bit Manipulation,Trie
Medium
1826
1,913
hello guys my name is arsala and welcome back to my channel and today we will be solving a new lead code portion that is maximum product between two PS with the help of the JavaScript we will be following this question so the question says the product difference between 2ps a b and CD is defined as a into B minus C into d for example the product difference between 5 6 and 2 7 is 5 into 6 minus 2 into 7 and the output is 16 given an integer Arena through the rules four distinct indices uh w x y z such that the product difference is between nums W and nums X and numps Y numz is maximize return the maximum such product difference so actually what they are asking us that uh we have to return the maximum differences between four numbers so first of all we will be taking two maximum number and two minimum number and then we will return the their differences so how we will be approaching that take first 2 max nums from the array and take first to Main nums from the array okay so that's the approach here because when we will taking here first rule minimum number and first to maximum number and then we will if you multiply two maximum number uh Max minus min will give us the Max difference okay so this is all the approach here so let's start solving this question guys so in here you see that we have four two four five six seven and we just have to take two minimum number and two maximum number to get our answer and we will subtract those so how we will we are going to approach that's the trick here and it's quite simple I will tell you how we are going to oppose so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel and let's start solving this so what I will be doing here is I will say that my result red result is equal to first of all I will sort this array so let's solve this array um num slot sort and a b return a minus B so when I sort this array what will be I what will I get here is if I sort this example and comment this will give me 2 4 5 6 and 7. similarly in second example if I sort this at e what I will be getting um two four five seven eight nine seven eight and nine so I just have shown you how after sorting the array they will look like so the approach here is that I will be targeting the targeting first two element which will be my minimum number and first last two element which will be by maximum so that's the all the approach here so let's do that so if you see here if I take two numbers from here and two numbers from here this will be my maximum number and this will be my minimum number similarly In Here Also these two are my minimum number and these two are my Max number so you can see that the output is coming similarly like this only first there are this and second pairs are this so let's do that and return that result we got length and gtn minus one into result um result dot length minus two and this whole will be subtracted from result 0 into the result 1. okay so let's approach here and let's take some brackets here so that we can Target them individually and let's make it put here and let's add bracket here on the whole thing here now let's look around the code and hope you have understood the concept here before so you see we have got a answer there let's apply for example number two as well and run the code for that as well so they see that the r code has been running successfully so this was all in the question I hope you have liked the video hope you will subscribe to the channel if you have any doubt ask in the comment section thank you guys for watching the video see you next time
Maximum Product Difference Between Two Pairs
make-the-xor-of-all-segments-equal-to-zero
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`. * For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`. Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**. Return _the **maximum** such product difference_. **Example 1:** **Input:** nums = \[5,6,2,7,4\] **Output:** 34 **Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4). The product difference is (6 \* 7) - (2 \* 4) = 34. **Example 2:** **Input:** nums = \[4,2,5,9,7,4,8\] **Output:** 64 **Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4). The product difference is (9 \* 8) - (2 \* 4) = 64. **Constraints:** * `4 <= nums.length <= 104` * `1 <= nums[i] <= 104`
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
Array,Dynamic Programming,Bit Manipulation
Hard
null
37
hey everybody this is larry this is day 21st of the august record daily challenge hit the like button hit the subscribe button and join me in discord let me know what you think about 280's problem oh now it's a dugo salva uh okay to be honest i wrote a really optimized version of relatively sudoku self like maybe a long time ago uh it has been a while though to be frank maybe even like a decade so i don't remember if um yeah uh so i'm probably gonna just do the normal uh what's it called branch and bell and then kind of see if that's fast enough if it's not then we'll figure out what to do there is a lot of um what's this iphone there is a lot of literature about sudoku salvador so i'm not going to really do that much explaining if you want to search something i think dancing links is the recommendation by canoe um but i haven't touched that in so long like maybe literally a decade so uh so i really don't know if i am able to do so i'm not gonna do that one but i am gonna try to do as best as i can um the python before sulfur so let's without further ado uh so yeah so i mean this is just backtracking it's just me trying okay let me put in one then one two dot um so it's just about kind of try to figure out how to do that in a smart way so okay so let's get started okay so okay how do i want to get started this is gonna be fun uh there might not be that much of me explaining because i think every like it is just backtracking which is another way of saying recursion with a lot of tracking there is going to be only one solution so yeah i mean it's a little bit awkward because this can be as bad as the test cases that they give you but we'll figure it out we'll play around with it modify the board in place is kind of silly though but it's fine um okay i mean there's a lot of ways to do it but i'm just gonna um just i guess n is equal to nine okay and now let's just do okay so then now we keep track of each row column and whatever and let me wait maybe this time we'll use a bit mask okay i guess i got done here in the same loop and here l else number is equal to port of x y minus or just the end of this and again we'll just minus one so that it re-index from zero to eight and then rows this is x-row wait did i mess this up oh yeah no this is right this may be a little bit of a boring video to be honest and apologize for that but you know this is what this is uh which box is this so zero one two three four six so how do we wanna map this box i forget how just this goes hmm oh yeah so i guess x divided by three and y and three is equal to coordinates and then u times now we want to convert this such that each row is so that's the box coil in it right yep okay so then now to convert that to number it's just one of these times three right what do we want to do rose kind of three yeah okay makes sense oops okay so now we set up the constraints and then now here's the recursion right um okay let's just call it i don't know naming things are hard i usually just type go for that reason it's not a great name but it's just what i do because i want to focus on solving the problem and not naming things and with index and that's good enough for me i think yeah okay hey then we're done uh we're good assuming that we checked before do we check after i guess doesn't really matter so that's no we should check before so that means that okay and then let's just say answers go to none let's just we'll figure out how to update the board thing later maybe we don't have to we'll figure it out okay let's just do this for now and then we'll see and then here um okay current x y is equal to k of index this is the cell that we care about and it should be a period so yeah so then we want to go index plus one is the recursion but now we want to try for the next number first so let's just go for attempt maybe and range up from zero to eight and then what happens if row sub x and um we'll have to do something about this fight but that's fine okay so this is good so boxes you go to then we want to do this recursion up really should okay fine um this way yeah sorry usually i solve this life as you can see i've i usually say that but this one's been going over a long time so i usually stop this live so it's a little bit slow watch it on 2x or whatever you need to do this is clearly going to be implementation problem and it's clearly going to take a while so settle down and settle fun have fun and then we'll see what happens uh yeah you could also do an n knot on the other thing um yeah except for if sound will return i think that should be good but maybe just in case and now we because it put of x y is equal to um string of attempt plus one i guess we can make this back to a period just in no i don't know if this is good to be honest because usually i don't like doing it in place but we'll at least kind of see if this gives us a relatively responsible answer and then we'll see and you can plug this into your sudoku checker and the other one i think i guess we can also do a show diff to kind of see i mean so i guess for this one it looks good but again it's going to be about the running time and stuff like that so i don't know if this is fast enough but let's give it a summer just i'm not confident this at all um there are potential typos but we'll see oh wow okay that's actually surprising to be honest i was expecting when i saw this problem i was expecting to spend all night on this but i guess and maybe thankfully like i said though um this problem depends on the test cases and they can make the test cases as complicated as they one so this is kind of this means that their test cases are a little bit on the easier side which i am thankful for because i don't really want to spend all night on this problem but uh yeah in terms of complexity this is good this is tricky i do not for this exponential exhaustive search stuff i always find it a little bit tricky to analyze it because this exponential solution but there's also a lot of inherent uh branch of bounding that is in the constraints of the problem which i always find a little bit uh tough so i don't know what to tell you um but there is that said a lot of literature in this so i definitely recommend just looking it up uh we want i don't know if i recommend this as my salute as a good solution but this is my solution so um you know take a look at this is just to go over the solution real quick this is just a setup this is the basically the rows for each row what numbers we use for each column what number we use for each box meaning one of the you know three by three boxes uh what number we used and then here we just kind of pre-fill kind of pre-fill kind of pre-fill um the constraints that we have and here i just kind of pre-process and here i just kind of pre-process and here i just kind of pre-process going from left to right from top to bottom or the spaces that we have to care about there's actually a smarter way to do this but i was just you know i was thinking about crossing that bridge when i get there and oh thankfully i didn't need to uh but in this case yeah um and in this brute force i just basically go for it one at a time each empty space at a time if we reach the end then we're good we set values equal to true then we return otherwise we look at the current cell that we're looking at including figure out the box and then just put first um a number from zero to eight which we converted from one to nine and here we gave it a try so basically this is saying if this number is not used in the row column or the box or an n of those three things those three fingers end together then we then yeah then we just order it otherwise we do a recursion on the next uh so if it's good then we set this to the cell otherwise we go to the next cell uh actually then you go to the next cell otherwise you just try the next number and this is recursion this is flipping it on to true this is flipping into force um if you're not familiar with bit mask i'm going to go over it in another video because i think i go over it a lot so if you find another video on bit mask that i go over i actually go over a lot but yeah that's all i have for today uh stay good stay healthy have a great weekend hope you know you do the contest with me uh later on i'll see you later have a good night bye
Sudoku Solver
sudoku-solver
Write a program to solve a Sudoku puzzle by filling the empty cells. A sudoku solution must satisfy **all of the following rules**: 1. Each of the digits `1-9` must occur exactly once in each row. 2. Each of the digits `1-9` must occur exactly once in each column. 3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid. The `'.'` character indicates empty cells. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\] **Explanation:** The input board is shown above and the only valid solution is shown below: **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit or `'.'`. * It is **guaranteed** that the input board has only one solution.
null
Array,Backtracking,Matrix
Hard
36,1022
162
hey everyone welcome back and let's write some more neat code today so today let's solve the problem find Peak element we're given an array of integers and they don't mention it here it's mentioned all the way at the bottom of the description but it's a very important fact and it is that any two adjacent elements suppose a number at index I and number at index I plus one these are never going to be equal so any adjacent elements in the array are not going to be equal that's a very important fact for this problem so I wanted to mention it at the beginning we want to find a peak element within this array a peak element is kind of how it sounds so imagine that there are three elements the peak element is the one that is greater than both of its adjacent neighbors now it's possible that there could be multiple Peak elements that's okay we can return any of them so we could return this one or this one now what if our array looks something like this three two one at first glance there aren't any Peak elements in this array but the way they Define Peak elements these endpoint values suppose three it's greater than its right neighbor but it doesn't have a left neighbor so can this be a peak element well the answer is yes any endpoint value like three is implicitly assumed to be greater than its neighbor if its neighbor doesn't exist so if it's left neighbor doesn't exist three is considered to be greater than its left neighbor for one since its right neighbor doesn't exist it's assumed to be greater than its right neighbor now it's not greater than its left neighbor so this is not a peak element but three is a peak element it's greater than this and it's greater than this given those facts we are guaranteed that there's going to be a peak element in this array our goal is to find it'd be pretty easy to do with a linear scan but they actually want us to do better we want to do this in log n time are there any algorithms you can think of that are login time well pretty much the only one that would work in this case is binary search but is it even possible to run binary search on this problem well let's go back to basics and think about what binary search is as an algorithm we have an array suppose one two three one usually we have a left and right pointer we calculate the Midway Point let's say this is the Midway point we have a pointer here we check is this guy a peak element check its left neighbor well it's greater than it's left neighbor check it's right neighbor it's not greater than its right neighbor so we know for sure this is not a peak element but the idea behind binary search is that we should be able to eliminate half of the search space every single time we should be able to either say okay we know for sure there's no solution on this side so we're going to search on this side or we should be able to say the opposite we know for sure there's no solution here let's search over here but we can't really say that with this problem there could be a solution here or here and it's actually possible there could be a solution on both sides of the array so let me say this slowly this is going to be a modified binary search where we don't necessarily have to eliminate half of the search space every single time we're just looking for a single Peak element so we just have to be sure that the side that we decide to search on whether it's this side or this side we have to be sure that the side does have a peak element maybe there's a peak element on both sides doesn't matter we just have to be sure that there is one on the side that we're searching if this is not a peak element how do we know which side is guaranteed to have a peak element well let me show you a very simple example let's suppose that our array was monotone chronically increasing so these points kind of represent the values of our array is this a peak Element no is this one yes it is because it's greater than its left neighbor and it doesn't have a right neighbor so this is a peak element so if we were running our binary search on this array and we looked at this point and we saw that this value is not a peak element so we're not going to search here which side do we want to search on the left side or the right side we're going to go on the right side because even though we can't see the entire array we see that it's right neighbor is greater than it so maybe this is a peak element maybe this point doesn't exist and the value is actually somewhere down here so we know this is not a peak element but this is greater than its left neighbor and it's also greater than its right number that's a possibility but even if it's not true even if this value doesn't exist and it's actually all the way up here look it's still guaranteed that there's a peak element because all the way at the right either this is going to be monotonically increasing which guarantees that there's going to be a peak element on this side of the array or it's not monotonically increasing which means one of these points suppose this one is going to be down here or maybe you know there's a few more points and one of those is going to be below so like this one would be all the way down here and in that case it's also guaranteed that this is a peak element as well as this being a peak element can you kind of see the intuition out either this portion of the array is monotonically increasing which guarantees a peak element or it's not monotonically increasing which means that there's going to be a dip somewhere which also guarantees that there's a peak element and that's true because we know for sure that this is not a peak element but its neighbor is greater than it so it's already increasing here and it might keep increasing or it might dip somewhere now the opposite could have been true as well it could have been going downwards it could have been monotonically decreasing so if we looked at this value and saw it's not a peak element which side are we going to decide to search on this side because its left neighbor is greater so we're guaranteed that there's going to be a peak element here because it's monotonically decreasing which means all the way at the left is going to be a peak element or there's going to be a dip somewhere maybe here or maybe here which guarantees that there's going to be a peak element so if we are running binary search and our mid value suppose in this case over here is not a peak element we're going to search on the side that has a neighbor value that's greater and we're guaranteed to have a neighbor value that's greater because if we didn't if this was like one for example and this is 2 and this is one then by definition this is a peak element so if this value is not a peak element we're guaranteed that one of its neighbors are going to be greater than it and that's the side that we're going to search on it's really that simple I know it's probably not simple to come up with but once you understand it does make a lot of sense so now wrapping our binary search up we're going to take our left pointer and shift it to be mid plus one so it's going to be over here now and then we're going to recalculate the mid pointer to be left plus right divided by 2 which I think is going to be over here so then we're going to check is this the peak element we're going to compare it to its left neighbor it's greater we're going to compare it to its right neighbor it's also greater so this is the solution we return the index in this case I believe yep over here and since this is binary search it's running in log and time constant memory so now let's code it up so this is mostly going to be a cookie cutter binary search we're going to initialize our left pointer to be zero our right pointer to be all the way at the end length minus 1 and then we're going to have our while loop while our left pointer is less than or equal to right we know for sure that we're going to return within this Loop so we don't really need to put like a return statement out here so I'm not going to bother with that but we're going to calculate the Midway point we could say left plus right divided by 2 but it's possible that overflows a way to make sure that it never overflows is to do it like this basically take the distance between right and left which is right minus left divide that by two and then add that to the left pointer this is basically another way to calculate the Midway point that just guarantees that it's not going to overflow most of the time you won't need to do this in coding interviews but I think gets helpful to know how to do it now we're going to check is the left neighbor greater than the value at index M how do we check that well basically check the value at index m is less than its left neighbor at M minus 1. if that was true we would say we're going to search on the left side so we say our right pointer is going to be mid minus 1. now there's one catch here there's one Edge case what if m is equal to zero in that case is it greater than its left neighbor no so we are going to check that m is greater than zero it's not equal to zero it's greater than zero and this is true that also helps us because then we will never get an index out of bounds error here and we can do the same thing to check if it's right neighbor is greater so I'm going to copy and paste the above and just change it up a bit instead of checking if m is greater than zero we're going to check if m is less than the rightmost position of the array which is length of nums minus one and the value right of it which is not M minus 1 it's M plus 1 is greater than it so if this is true if it's right neighbor is greater that means we're going to search on the right side so we're going to say left is equal to M plus 1. so we have the two cases where we're either going to search on the left side or on the right side but if we don't do either of these that means we for sure found the solution so else is the case where we found the peak element and we want to return the index which is M so that's the entire code now let's run it 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 neat code.io it has a ton of free resources code.io it has a ton of free resources code.io it has a ton of free resources to help you prepare thanks for watching and Hope hopefully I'll see you pretty soon
Find Peak Element
find-peak-element
A peak element is an element that is strictly greater than its neighbors. Given a **0-indexed** integer array `nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to **any of the peaks**. You may imagine that `nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array. You must write an algorithm that runs in `O(log n)` time. **Example 1:** **Input:** nums = \[1,2,3,1\] **Output:** 2 **Explanation:** 3 is a peak element and your function should return the index number 2. **Example 2:** **Input:** nums = \[1,2,1,3,5,6,4\] **Output:** 5 **Explanation:** Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1` * `nums[i] != nums[i + 1]` for all valid `i`.
null
Array,Binary Search
Medium
882,2047,2273,2316
133
Welcome to the new video of the state assigned to and today we are going to see problem number-34 line 7530 follow graph so problem number-34 line 7530 follow graph so problem number-34 line 7530 follow graph so tell us a little about this problem so that we can refer to given reference journey no dinner connected and a graphic and it Anytime without can happen, we can do this deep copy i.e. returning the loan. What is customer edit copy i.e. returning the loan. What is customer edit copy i.e. returning the loan. What is customer edit copy? It is as if we have given you a graph, now you have got an exact copy of that, which means like you have a piece of bread and that is a piece of another bag, so separate them. -If it is different then I will create the second one separate them. -If it is different then I will create the second one separate them. -If it is different then I will create the second one using fast in exactly the same. Now tell us how Ignore Dinner Graph Container Valuable List Play List Nodal Officer will be appointed from our curtains so his and hers which is not on it is connected to two places ok If yes, then see this as an example: Example 1. Let us also explain see this as an example: Example 1. Let us also explain see this as an example: Example 1. Let us also explain what is written here. Just like you have given us the DJ list written here, it is being made in this way that you can figure out where exactly A is coming. Now you will think that Print it Edison, you don't have to do this, it is a matter of fact that by doing this it will turn green because it is easy to make it Chinese, we have what we have not printed it, we have made a plan for it, how I have already written it in paint. It is a waste of time in writing everything, so we have made a drawing there, I will serve something so that it is visible, so I am looking ahead, actually we have the original graph, this is less, I am 1234 and Look, there is no direction, so if you believe that it is directed from both the sides, it can be brought from anywhere, then I do not want to do this, from where this cross is placed, it does not mean that look at the color, agree, it is exactly this from both the sides. I have picked it up, okay, that means the piece of bread is alone, I have picked it up from here and kept it here, no, don't do this, no, what we have to do is break it into pieces, like hair, it is okay. Free has come here is the tooth, after all, we don't have to do this, we need exactly the bean, details 1234 and also this color has not changed, a new space has been created, that is, our glue in the new place, we say that the bean has to be made a big bean. For a model like scheme, I will not do that by removing the satire from the old car and take it apart, not by buying new tires but by buying exact samples, it means that we will have two vehicles. It can be said that so what are we going to do in this? This is the second question, what is the definition of a simple cyclone and not just print it? I have explained it, so what will we do, we will update it. How did our journey actually start? Do we have old notes lying with us and new notes can we create? Will take my tongue in the starting Okay now what should we do Check the forest if it was not inside the snap So what will we do in the starting We will map the old forest to the new building Okay with the closure More like We will create a new one, we will create a new note, it has value but the ATM will map it, now what is it connected to the parties, so for now, let us see what is happening with you, then we will reach two * What will we not do like this? Look at one. will reach two * What will we not do like this? Look at one. will reach two * What will we not do like this? Look at one. 420 of Angry Birds from 2842. It is not like that we will pick up power two from here and put it here, neither of ours, this is what we have initially made with us. Okay, forget all these, now look at two. Hi. That Octo is there, it is pointing to two Never Pads, this Vansh 3513 cannot be the old ones, but one thing is that we have time, we have got our forest, so we will attach it to the forest, it is okay, now I will run it and see. So it's not working, I'm working, that white color is working, isn't it? If you're a boy, then you will be attached to us, and how will it go with whom from below, it's okay with three, it's a bad omen, so wait a little, I'm your friend. Look at this, there is a connection with Urban, there is a connection with Ghrit, there is a connection with Ghaghra, so we will take the initial piece first because with 2019, this is what I am searching here because it was with and two, so with both. We will have to make already created and 13, which is connected with HR as well as with two, which means that this director lemon can be anything in both the countries, so the same thing happened, both the sides refused. Now the charge is that it is connected and also take four at this time, one is also with China, right, one thing is left from A, one is connected, with the thought, we will keep on sinning and will go back and that country is also closed. With and also with which ultimately our plane will become, it is such a simple thing, isn't it, and the time complexity of it is Ghee Ad Job, but it must be understood that we are traveling here through the match and its code word is I. Let me show you, okay, this is the accepted result, isn't it? What else is there in this? I have written 'and two', you is there in this? I have written 'and two', you is there in this? I have written 'and two', you can write any name in it, create it now, 'old to new', now the time has been now, 'old to new', now the time has been now, 'old to new', now the time has been changed to a different function, the toy is doing videos. Actually, we are there, if we look at that thing, as I am saying clone, then if it is kept chronic, then we are cleaning it. If this node is in vote, that means we have time, it is already kept inside us, let me clean it, become what it was. If it was kept earlier, then do we not need to create a new topic, it means I have created the initial chapters, it is okay, but whenever the time is created, whatever is already there in you, we have mapped it from Anu to the appointed one. If we already have this thing, it means that a copy of it has been made, then what will we do at that time, we will do the routine and 2nd, what will we do with the photo and if we don't have it, what should we do? Create a copy. The note will be of copy. For this note, I have placed it on the glass define here. Value has to be given in it and the naval which is there is naked. If there is nothing initially then we had gone to Delhi from us. Okay by default there will be ribbons in it so we have given the person a cigarette. To do this, the value of this note has gone, now we have made two Renukut equal to two and make profit. Now we are making a gap. Okay, from fold to new, we are going to check the number. So much work has been done, this will work when we We will call, see, both are for me but SIM is not difficult, what are we going to do in that, we have to call the loan number, the reason for calling is to create a copy, it is not a cigarette, then you are a cigarette, then what should we do and Will paint because now we have new notes also appointed when nano twist is connected then copid nipples up and daughter end and inside that we had added this number and we will return it finally our copy was created and when initially how will our initial be said So if it is created for us, then we will return it to airplane mode, then the note which we have here, we need this function, it will call if there is a note, if there is no note, then as if this is this or this, if you do not put it, then an education will come that if If there is a note then what to do if you return these then run it and submit it and show it, then I left it and this was the code which I told you, so I kept it in my mind, see, success came and it was very fast too, right. The whole matter is to run it and see it once, it is not very difficult, you just have to connect it and when to call the function, you will have to see all this, I am in the next video, how you are watching it. care by
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
118
hi everyone today we are going to solve the little question Pascal's triangle so you are given integer numerals Returns the first nominals of Pascal's triangle in Pascal's triangle each number is the sum of the two numbers directly above it as shown so let's see the example you are given numerals equal 5 and the output is like this now actually this picture so in the first row you can see one because uh there is no number on the left side and the right side because this is a fast row so we don't do anything and then look at the second row so from this position and there is no number on the left side but you can see the one on the right side so that's why this question is one and the same thing from this position you can see the one on the left side but there is no number on the right side so that's why this position is also one and I look at the third row and from this position so um there's no number on the left side but you can see the one on the right side so that's why this position is one and I look at this version Center of Southern roll and now uh you can see uh the one on the left side and then you can also see the one on the right side so that's why a total number should be 2 here and then from this position and you can see the left and you can see the one on the left side and there is no number on the right side so that's why this position should be one yeah and their videos are say same thing and then in the end we can get this uh Pascal's triangle and this question is actually very simple um so okay let's look at the force or a fourth row and uh fourth row has like one three one because uh from this position uh you can see the one on the right side but there's no number on the left side so that's why this portion is one and from this position 1 plus 2 and 3 from this position 2 plus 1 equals three and then from this question one plus uh there's no value here so that's why this portion is one and uh I think uh these three position from this three position uh it's easy because uh um you can see the numbers on the like a left side and the right side but how can we um so how can we calculate the uh on the like edge of both sides um so because there is no numbers here and there is no number here so how so I think a simplest way is um just add zero here and here so um when we calculate the uh e calculate each position in the fourth row add zero to the head of surgery and end of third row so that we can avoid the like out of bounds or something unexpected error so zero means nothing so that's why um if it's equal to like there is no number here and so that in this case 0 plus 1 and then one plus two and three and two plus one and three and then one plus zero and three uh one so I think uh G 0 makes the program easier for us so that is our basic idea to solve this question uh with that being said let's get into the code okay so let's write Circle first of all initialize the result variable with like a 2d array and a one in the start looping for underscore in Lynch and the num rows minus one and first of all create a row with double zero so let's call it like a dummy the middle we call 0 plus desert -1 Plus -1 Plus -1 Plus zero so this result -1 is so this result -1 is so this result -1 is um uh the row right above current row so if you are in the second row uh which this means uh like a fast row and the other double zero to hit and end and then initialize the row with empty list and we need another for Loop for I in length and the ranks of um result minus one because we have to add numbers and the but we need a plus one to reach the end of zero this one and then after that low dot append and the calculation is very easy just a dummy row and I plus dummy rho I plus one and then after that just add a row to result variable so let's dot obtained and they're all yeah actually um that's it after that just return result variable yeah so let me submit it looks good and the time complexity of this solution should be a order of n squares because uh we iterate through all rows and which is a n and um another we have another for Loop to iterate through all numbers in your row so which is a n so n multiply n which is a o n Square and space complexity is also order of n squares because we have a 2d array yeah so let me summarize step by step algorithm this is a step-by-step algorithm of this is a step-by-step algorithm of this is a step-by-step algorithm of Pascal's triangle step one initialize 2D array with one Step 2 start looping create a dummy row with adding two zeros as the numbers on the left and the right step 3 return to the array yeah I hope this video helps you understand this question well if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Pascal's Triangle
pascals-triangle
Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** numRows = 5 **Output:** \[\[1\],\[1,1\],\[1,2,1\],\[1,3,3,1\],\[1,4,6,4,1\]\] **Example 2:** **Input:** numRows = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= numRows <= 30`
null
Array,Dynamic Programming
Easy
119
491
hey everybody this is Larry this is actually me doing day 20 of delete code daily challenge hit the like button hit the Subscribe button drop me on Discord let me know what you think about this poem another one that I haven't done so yay 491 non-decreasing done so yay 491 non-decreasing done so yay 491 non-decreasing subsequence so that's actually what this means there's a subsequence this time uh given in a way nums uh return all different possible non-decreasing different possible non-decreasing different possible non-decreasing subsequence of any given away by these two elements you may return the answer in any order so there's two things here is that you have to excuse me the first observation is that you have to return order um all the different possibilities and as a result um you know that this is possibly going to be exponential right because for um yeah I wonder if they don't make a good kind of differentiation about it uh on what different means um because different could mean a couple of things it could be different on index or different on volume right meaning that or if the number or the sequence is you know one oops um you know is one how many one ones are there right is it um five truths two or is it just one right um and you know that's I know that's the difference between distinct unique or whatever but sometimes it'll be very helpful if they Define it um so that's one observation but that doesn't really change the complexities I just changes to how you set up the other is um given that this uh you know you sing that this case um you know that this is gonna be exponential because um well there's just two to the end minus one uh number of possibilities here right meaning that basically you think about it as a binary number each number is either in or out of the subsequence that you're doing so if this has 20 elements or whatever uh dot then it's gonna be two to the 20 minus one number of subsequence right because that's just all non-decreasing because that's just all non-decreasing because that's just all non-decreasing um so yeah so that's basically the core part and knowing that is exponential means that well we can't really do any better so let's take a look at the constraints and the constraints kind of confirmed that for me in that n is equal to 15 because n is equal to 15 well you know uh that's pretty much all you need because uh like I said there's 2 to the N number plus subsequences and therefore we really can't do any better and 2 to 15 of course is was a 32 000 or something so yeah so that's going to be fast enough even if it times another 15 for you know n times 2 to the 15 or something and N times 10 to 2 to the 8 is usually happening because you have to you know make copies of the array or something like that right so yeah okay so let's say we have an answer and that's the way that we're going to do it's just Booth first right um no let's just say let's just call it uh I don't know because no maybe just fine uh let's just say index and then the last value maybe right something like that uh and it could be up to negative 100 just to be clear so you have to feel a little bit careful and maybe like a the current away and then yeah so yeah if num sub index is greater than or you go greater than you go to less than we can append numbers of index we do a recursion and then maybe pop in it something like this I don't then we also want to just uh go anyway like don't be caution without it right uh and then at the end or maybe not the end yet but and then another thing that you want to do is check whether the index is equal to end then we have to copy this to uh that's pretty much it keeping in mind that this thing is intentional so that makes a copy otherwise um you're going to copy a pointer and then uh well maybe we don't even go that far so is that not uh oh whoops this should be last that's why and also we didn't quite a function at all so that's kind of hard okay still well I mean did I just sort it no you have to return the answer in any order um hmm so I think this actually settles it even though I didn't really look for it that deeply um in that they have to be unique right um yeah because I think I've returned the same thing multiple times which is why uh this is wrong but yeah also maybe if length of current is greater than zero so technically uh with at least two elements are actually greater than two then oops maybe that's what I'm missing maybe that's a different thing no but still it's still uh the duplicates I suppose so yeah I mean that's also obviously fine um we just kind of have to change this into a set and uh and now yeah and then now we don't have to do this because it already makes a copy of it and that's pretty much it right let's give it a submit 10 25 yay uh yeah I mean what is complexity here uh we already kind of talked about it um it's going to be so this is kind of roughly speaking to the end um times n because we have to make a copy of the thing uh yeah Dan so yeah so two to the end times n and that's pretty much it um of course given that is 15 it should be good uh yeah the reason so a couple of minor things one is that we have to just check that is length two which we have to do here um we convert it to a Tupelo because a topo allows us to kind of use a set that's just the way it is um because it's um immutable you can also use a floated Frozen uh maybe if it wasn't something I could be wrong with that one but yeah so that's why it gets rid of it and at least on lead code it converts the turbos to an oil checks the turbos of a list for the independently even though in theory maybe you should change it back from the table to a list if you want to be uh really careful or whatever um what else is there I think that's pretty much it I mean this is just really straightforward backtracking otherwise something that you really should we practice on is something that people definitely give interviews on so yeah um that's all I have for this one let me know what you think I'm going to go to bed so stay good stay healthy it's a good mental health I'll see y'all later and take care bye
Non-decreasing Subsequences
increasing-subsequences
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\] **Example 2:** **Input:** nums = \[4,4,3,2,1\] **Output:** \[\[4,4\]\] **Constraints:** * `1 <= nums.length <= 15` * `-100 <= nums[i] <= 100`
null
Array,Hash Table,Backtracking,Bit Manipulation
Medium
646
309
uh hey everybody this is larry this is day 29 of the july lead code daily challenge did hit the like button to subscribe one drummer on discord and let's get at it best time to buy and sell stock with cooldown say you have an away if elements the price of a given stock in a given day design algorithm to find the maximum profit you get may complete as many transactions as you like uh buying oneself define restrictions you may not consume multiple transactions at the same time after you sell your stock may not buy the stock the next day okay so the way that i would probably think about it is just dynamic programming because that's just the way that um the pattern goes uh so how would i think about this right so basically at every action so let's break down a few functions but let's start with pi with an index um okay and then auto set n is equal to prices for length of prices um yeah if index is equal to n then it's returned zero because we're not doing anything um otherwise let's see so now at this index we have two options right we have we want to buy or we don't buy so we buy we so happens when we buy that means that um we paid the cost so negative prices of index is the cost and then we sell it at a later date index uh plus one and so forth you could sell the same day i suppose but that's just weird um so then that means that your cost function will be you want to maximize um selling at index plus one or buy at index plus one that means that so yeah so this is the okay actually let me break this down a little bit right so uh so there are two possible best way right so uh best profit buying that means that we buy this and the cost of this buying is you go to uh reselling it in the future plus the cost which is this thing and it costs us price of index right uh press profit not buying is just you go to buying of index plus one right and then we just take the better version of it so we're just doing it with recursion right now uh we will do the dynamic programming before uh or memorization part in a second but this is how i would talk through the logic one step at a time okay let's go sell right so okay so sell means that you have uh you have a stock already right and that's factored in the cost um so again if index is equal to n then we returned zero that means you messed up and you didn't sell so you kept it uh otherwise uh the selling price i want to say it's cost but i guess it's not really it's the price i just got prices you go to prices of index because that's how much you get it if you sell it now right so best profit selling this uh let's say we sold it right then when can we buy again well we can only buy at index um you could maybe do right it don't function for cooldown but i think it doesn't really matter so when you sell you have to buy a disk so you skip the next index so it's buy at index plus two uh plus the price and the best profit not selling is just to go to well let's consider selling it tomorrow instead which is index plus one and then now we just take the max of these and there will be a we probably have to fix uh a little bit things but that's probably my general thing for now um and for example this uh this index plus two means that this may go over n so let's uh change that to here and i think that we could probably start playing around with it and then let's just return bi sub zero um yeah just wanting to see if it works it looks okay let's play another one another number um i don't know and just maybe one element um and of course this is not gonna be fast enough uh for big ends because uh i don't know what n is actually but let's say you have you now this is five right five elements so let's say we have a lot of these uh this will probably time out yeah uh but because of the formulation that we have now we can think about um adding memorization to it right the key thing to note is that for this by function uh you just you only take one input which is the index and index just goes from zero to n minus one uh same for cell so that means that uh they're at most and each of these do all of one constant work so this that means that this is going to be linear space uh so then let's just buy cash is equal to uh which doesn't matter times n and by cache exists maybe as you go to false times n and then we do the same thing for cell and then now we just have to put it in which is if the index uh or if buy cash exists index is equal to true then we return the buy cash of index otherwise at the very end we set the buy cash index is equal to this thing and then we return it and we also set the access to true we do the same thing for the cell portion so yeah sometimes i do have typos so i'm not confident per se but conceptually at least album-wise it conceptually at least album-wise it conceptually at least album-wise it should be okay uh not even so yeah so it went pretty quickly relatively so let's submit it and give it a go cool yeah so what is the running time again um for this function by we only call it at most and or the only n unique uh or n plus one unique variables i guess uh that could be possible and each one costs all one time so it's gonna be of n total uh for all the buys and same thing for all the cell so it's gonna be linear time and linear space uh cool uh and you could actually um you know convert this to bottoms up now that you're familiar with this and also um just dynamic poke or uh you could optimize the space of that uh it'll be much more efficient but yeah uh noting that it only takes the index plus one and index plus two here in this case but yeah that's all i have for this problem let me know what you think hit the like button subscribe button and i will see y'all tomorrow bye
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
35
welcome back everybody today we're doing problem 35 searching insert position and this time we're going to be doing it in javascript this was a problem given by amazon in a coding interview now let's read the problem and then we're going to figure out a solution as usual give it a sorted array of distinct integers and a target value return the index if the target is found if it is not found return the index where it would be if it were inserted in the correct order now you must write an algorithm that's going to be a runtime complexity of o log n okay so let's actually go through the solution now i am going to go through this example here just so you understand what we're doing so one three five and six now one thing that is very important to note is i cannot seem to find it uh given this sort is already there we go so given a sorted array now this thing is very important because if the array is actually sorted i'm able to split it in half take the number either from the left or right it doesn't really matter and i know that everything on the right side of this element that i took is going to be bigger than the element itself right so i'm just going to write it here bigger and also this is telling me of course since it is sorted in the correct order that everything on the left side is going to be smaller so small and this is going to give me the opportunity to see if i'm searching for 5 i'm going to take the right half and if i'm searching for something for example less than 3 i'm going to take the left half so if i'm searching for 5 here since this is going to be the target value i am going to take the right half of 3 and i am going to be ending up with 5 and six all right now i can take the half of these so two elements and i'm just going to take the first one i'm going to check is the first one the element that i'm searching for yes so here i'm just going to return five now keep in mind that if it's not or if this was quite bigger now if i have one two three five six eight and here i'm going to say nine and i'm searching for let's say something big i'm gonna go with nine now nine is going to be my target so let's just write it down so we know what we're searching for target and i'm going to take the middle element and the middle element is going to be 5. now i know that i'm searching for something bigger than five that is why i'm going to take this thing over here and in the second iteration i'm going to have six eight and nine okay so now i'm still searching for something bigger than the middle element because the middle one is going to be eight and i again i'm going to take the right part of this which is going to be nine and then of course i'm just going to return so that's pretty much what we need to code up all right let's go and try to see it in code that's going to get i think a bit brighter the first thing that i do want is to keep a low pointer and a high pointer in order for me to actually change the borders so i'm going to say just start or i can go left and right i think left and right is going to be better left is going to be equal to zero and the right is going to be numstot length minus one once again i do want to have the first element over here and for some reason i'm not drawing i want to have the first element here and you're going to see it in code far better but the first element and the last now if i take the first plus the last divided by two i'm always going to take the middle element and if i move the left border to the right or the right border to the left i'm actually able to sustain the borders make them either smaller or bigger and of course i want them to make them smaller each and every time they're going to be two times small as the previous one and that is what is going to make it a lock and run time complexity all right in order for me to establish the loop i'm just going to say while and i'm gonna write well left is less or equal than right and now we need to create the middle element so that's going to be the middle point well i can just say mid or middle let's go with the middle element this is going to be left plus right divided by two and since this is javascript and it's going to give me 2.5 javascript and it's going to give me 2.5 javascript and it's going to give me 2.5 i'm just going to say my trunk over here just to be safe all right and now i need to check so if the numser middle element is actually equal to our target obviously i have found it and i am just going to be returning as you can see here the index two because i have found five now this is the best case solution right i'm just going to say return middle element this is going to be the index that's going to be pointing to our middle element since that's what we're required to return and here is the interesting part this is the borders now i'm going to check if nums of middle element did i write this correctly yes so if nums of middle element three for example is bigger than five and actually let's go with the example if three is actually going to be smaller than the target i need to put the left border above three so this is going to give me five and six because again six is not going to move only one is going to move on the place of five so if nums of middle element is actually bigger or equal then no actually not equal i don't want to write it if notes of middle element is actually smaller than the target then i need to say that our left side is going to go forward meaning this my left is going to go not to the middle element but one step further and keep in mind i'm going one step further because i have already tried to find if the middle element is actually the target meaning that it is not that's why i'm just going to skip it and else i'm just going to say right is going to be equal to middle element minus 1. if i have not found anything right no matter how big the array is i am just going to return left and i'm going to be returning left because i have found the place where the target would be all right let's run the code and see if this is going to work good use example test cases and hopefully everything is going to be all right well that was the problem explained and coded in javascript thank you for watching and if you have any questions leave them down below 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
674
all right guys so let's talk about longest continuous increasing subsequence so you are given an unsorted array of individual numbers and you just have to return the length of the longest continuous increasing subsequence and the subsequence must be strictly increasing so this is the definition of continuous increasing subsequence so i'm just going to talk about the example one so right over here so i copy the question to the notebook and i'm going to say i and j so i'm going to say rng and i would just keep traversing the nums array and if the nums j is greater than the minus one then i will uh move on the next index so for example three and since uh three is greater than one right so i move j to the next one and three is greater than five so i move to the next one as well uh as well but phi is greater than four right so here it actually is not continuous subsequence so uh before i break right i need to set my max lens so okay so i do have a max then and to uh to store the value so it should be j minus i right but the index is starting from zero right so we need to uh plus one right because the length is the minimum of length is one right so that would be the math and let's just start coding and i equal to zero and j will equal to something i'm going to put a question mark and also match length and next time we go to question mark as well so i need to try verse so i need to traverse the array right so j will be the uh the index uh which they reach the nums array so i need to traverse my j pointer and keep checking do i have to how do i validate my value with well with the neighbor right so i'm going to say well j is less than num star then this has to be uh value for sure right and also nums j is greater than num j minus one if this is true and i'm going to say um j plus for sure right but before i plus i need to make sure i record my length right so that would be max for max um max lens um and also my um my math j minus i plus one right okay so let's think about where should i stop on j so j uh j shouldn't start from the beginning because if j starts from beginning then i and j are comparing the same index so i'm going to say j stop on the second index which is i plus one and the max length for uh for the initialize state i'm going to say one because if the array is repeated right then the nums okay so the next line the return value is actually one so i'm going to initialize to one so what if this if then it's not valid so imagine if you break out the loop right here right so if you break up a loop right here you need to re-initialize you need to re-initialize you need to re-initialize you need to initial your i so your i will become here and j will become here so uh let us start coding so i will become j and j will plus then you just have to return next length and this is pretty simple and straightforward and just think about how to draw on the paper so make sure you don't have a mistake and let's just run it and there will be a solution and let's talk about time and space for the space is actually all the one because you are not uh giving space in this question and also for the time is all the fun right because you traverse every single element inside the array and uh and i think this is pretty standard and if you like the video please press the like and thumb if you want it and subscribe if you want as well alright peace out
Longest Continuous Increasing Subsequence
longest-continuous-increasing-subsequence
Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing. A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., nums[r - 1], nums[r]]` and for each `l <= i < r`, `nums[i] < nums[i + 1]`. **Example 1:** **Input:** nums = \[1,3,5,4,7\] **Output:** 3 **Explanation:** The longest continuous increasing subsequence is \[1,3,5\] with length 3. Even though \[1,3,5,7\] is an increasing subsequence, it is not continuous as elements 5 and 7 are separated by element 4. **Example 2:** **Input:** nums = \[2,2,2,2,2\] **Output:** 1 **Explanation:** The longest continuous increasing subsequence is \[2\] with length 1. Note that it must be strictly increasing. **Constraints:** * `1 <= nums.length <= 104` * `-109 <= nums[i] <= 109`
null
Array
Easy
673,727
547
in this video we're going to look at a legal problem called number of provinces so there are a number of cities some of them are connected while some of them are not so if city a is connected directly with city b and city b is connected directly with cdc then the city a is connected indirectly with city c right so you can see here a province is a group of directed or indirectly connected cities and no other cities outside of a group so you're given a n times a matrix is connected where is connected at i at j is equal to one that means it's connected right and if i city and i've uh j city are directly conducted that means that is connected i j is equal to zero so return total number of provinces right so you can see that we have city one is connected city two but city three is not connected to anything so we're returning how many provinces are we uh do we have in our graph right so you can see that this is one province and this is just a separate province here so you can see here we have a 2d array and then the first basically represents that for the first element that we have right in this case it's connected to itself and also the second element right so that means one represents true right represents that it's connected to the second element which is two node two and it's not connected to node three right and then you can also see that um we have one zero so that's the same thing for two right it's connected to node one but and it's also connected to note 2 itself but it's not connected to note 3. and for an o3 the last one you can see that node 3 is not connected to node 0 uncertainty 1. it's also not connected to node 2 but it's connected to itself so we can see that we have a total of two provinces that we have right so as you can also see here uh we can also have something like this where they're all not connected and basically you can see that one is connected to itself two is connected to itself three is connected to itself as well right so these index represents these nodes uh represents referring to those nodes right index zero represents node one index two represents node two sorry index one is represent o2 index three is our percent of three right and it doesn't have to be this way we can also rename it to zero this is one this is two right it doesn't really matter but we just wanna know based on this how many knows how many provinces that we have in this case we have three right this is by itself right so how can we solve this problem so to solve this problem what we can do is we can use unifying and a couple of videos ago i talked about how we can implement unifying what is union find um and how this unifying works so if you haven't watched that video i can uh i'll put a link right here and so that you can watch it but basically one way we can solve this problem of course you can do a bfs or dfs way but in this case we can use unifying to solve this problem so basically unifying supports two operation uh one is defined so basically that find function is trying to find the parent node of the subset right and then we also have a union function that basically unions two subsets right it takes two notes from two different subsets and we're gonna union them but if their parents is the same then we're just going to not perform this operation right uh we have to have two nodes that have the different parents so how can we use this to solve this problem so in this case what we can do is we can be able to union them right in this case once we union them together right so you can see here uh once we call this function we basically pass in the size of the union so we define a constructor of unifying we pass in the size of the currently um the size of the 2d array right how many rows we have that represents how many nodes we have right so that's number of nodes and then based on this 2d array we're going to traverse this 2d array and then for each and every single node we basically just form that connection right because here you can see no one is connected to one right no one's connected node two where no zero is connected no one right so it doesn't matter how you say it but basically you can see that the second node is connected to the first node and then the third node is not connected to the first node so we don't form that connection right so we can do that we can use call the unifying function right so we can keep it separate so now let's try to implement this so basically i'll create a union fine instance of unifying so passing is connected dot length so that's how many nodes we have and then what we're going to do is we're just going to iterate or traverse the 2d array so let's make it a variable coin and basically you can see that the number of rows the number of columns the same so we can just iterate in times in right so what we're going to do is that for the current element right in this case for the current element is connected to so the i the no i is connected node j right so what we're gonna do is that we're gonna form that connection if it's true right if it's a one is true so if it's connected at i at j is true then what we're going to do is we're basically going to call union find dot union right we're going to form this connection right these are the nodes if this is equal to a one we know that this is true there is a connection so we're gonna union that connection and at the end we actually have a uh we actually have a basically a number of components basically like a counter right if you don't know what this if you're kind of confused about what this class does i highly recommend to check out that video about the unifying data structure that i did basically this number of components is there to keep track of how many components how many disjoint subsets that we have um and you can see that after we union them we basically decrease the number of components right that we have because you union two separate components together now it's forming as one so we decrease the number of components that we have right so at the end we're basically just going to return uf dot number of components right so now let's try to run our code let's try it with a few more example so here you can see we have our success
Number of Provinces
number-of-provinces
There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`. A **province** is a group of directly or indirectly connected cities and no other cities outside of the group. You are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if the `ith` city and the `jth` city are directly connected, and `isConnected[i][j] = 0` otherwise. Return _the total number of **provinces**_. **Example 1:** **Input:** isConnected = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\] **Output:** 2 **Example 2:** **Input:** isConnected = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\] **Output:** 3 **Constraints:** * `1 <= n <= 200` * `n == isConnected.length` * `n == isConnected[i].length` * `isConnected[i][j]` is `1` or `0`. * `isConnected[i][i] == 1` * `isConnected[i][j] == isConnected[j][i]`
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
323,657,734,737,1085,2206
1,801
hey everybody this is larry this is me going with q2 of the uh weekly contest 2.3 uh weekly contest 2.3 uh weekly contest 2.3 uh number of orders in the backlog so this is just a simulation um you have to do things in a heap i think that's the biggest part um i actually had a what did i do oh i had a typo that's why but um that somehow passed through examples so i was fortunate and also sad um but the idea is just simulation um and using a heap i use the sorted list but it's the same idea as a heap um but the idea is just matching up and having um keeping track every step of the way um okay for example and actually i think this is a problem uh or that i problem uh or that i problem uh or that i saw on saw on saw on uh let me go i think i did i write an editorial about this one uh let me take a quick look um i guess it doesn't matter but um but yeah the idea is just using uh sorted list as a heap um but for every amount let's say you know we have an order coming in and we just simulated right we go okay you know this is actually just simulation and it's pretty straightforward as a result using a heap or sorted list or whatever you like um but yeah while amount while we have orders to fill um you know if it's a buy order we look at the sell side and we basically take everything that we can sell um where the max the price is where the sale price is uh cheaper than the price that we want to buy and we do that we remove the first element which is the top of the heap if you do it that way we just keep track of the number of trades that we've done and then we remove it from the amount and also p amount but the idea here is that okay if um yeah if there's any stock left um then we put it back into the sell order um and if this is not true then this is you know this is going to keep going and then we just keep on going through the heap in that way so yeah and then the same idea with the buy side as well so this becomes an implementation thing where you know instead of the smaller you get the bigger and you just have to be careful about the signs and at the very end you just sum up all the leftovers on the buy order in the cell order and then you mod it uh you also mod it in between it's fine uh but yeah i had an issue where i had a type of very silly mistake where i put the p price instead um but yeah uh otherwise pretty straight forward problem maybe i think but um but yeah um so going over the complexity this is going to be all of n orders that's just the for loop um here um the key thing to note about these heaps is that for each of these order it can only be inserted into the heap once or mine uh removed from the heap once right um because in every order if you look at this independently um you know each order we're going to be insert once or we moved once if we remove this um and then add it back on later then we never removed we never add the buy order right so that means that either one of these has to be true so that means that in advertised and on average each order will be added and removed a constant number of times and because of this and you know that the sort of this that heap operation it's going to be log n uh so each loop would each order will take log and time oops so in total it's going to be of n log n time in terms of space we have linear time for the two heaps uh and that's basically it uh and i use sort of list as a heap sometimes because uh i don't know i'm lazy uh it's a little bit slower i think but you know as long as you're not doing anything too crazy inside usually it's good um don't take my word for it though so try it at home um that's all i have for this problem let me know what you think i had a typo so that was a 35 minute penalty but yeah uh i will see you or you can watch me stop it live during the contest next this is on the lead code i think but uh okay there's a lot of reading there let me just do some binary search i think type this example is fine oh my god okay which one is pie 0 is 5. what do we return the pressing order orders from the input okay also mod i have to remember to mod so hmm this is okay something like that oh man that i misunderstood the problem oh i think i was thinking about the other part let's see yeah i just have to add these um because i didn't need this executed then it's fine i'll keep it in there for price amount and buy amount six and 84 okay that looks good huh maybe i misunderstood this farm i thought i was good i watched it a little bit maybe let's see how do i get 66 or 22. i misunderstood this hmm why do i have 66 this is why does it sell did i mess up somewhere ah i messed up copy and paste okay that is just silly this is what happens when you copy and paste and or mentally and then you messed up ah silly stuff yeah thanks for watching uh let me know what you think about this farm it was good bad i don't know uh this was a interesting contest uh let me know what you think uh hit the like button hit the subscribe button join me on discord ask me questions here there wherever you like and yeah have a great week have a great time uh stay good stay healthy stay well and to good mental health i'll see you next time bye
Number of Orders in the Backlog
average-time-of-process-per-machine
You are given a 2D integer array `orders`, where each `orders[i] = [pricei, amounti, orderTypei]` denotes that `amounti` orders have been placed of type `orderTypei` at the price `pricei`. The `orderTypei` is: * `0` if it is a batch of `buy` orders, or * `1` if it is a batch of `sell` orders. Note that `orders[i]` represents a batch of `amounti` independent orders with the same price and order type. All orders represented by `orders[i]` will be placed before all orders represented by `orders[i+1]` for all valid `i`. There is a **backlog** that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens: * If the order is a `buy` order, you look at the `sell` order with the **smallest** price in the backlog. If that `sell` order's price is **smaller than or equal to** the current `buy` order's price, they will match and be executed, and that `sell` order will be removed from the backlog. Else, the `buy` order is added to the backlog. * Vice versa, if the order is a `sell` order, you look at the `buy` order with the **largest** price in the backlog. If that `buy` order's price is **larger than or equal to** the current `sell` order's price, they will match and be executed, and that `buy` order will be removed from the backlog. Else, the `sell` order is added to the backlog. Return _the total **amount** of orders in the backlog after placing all the orders from the input_. Since this number can be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** orders = \[\[10,5,0\],\[15,2,1\],\[25,1,1\],\[30,4,0\]\] **Output:** 6 **Explanation:** Here is what happens with the orders: - 5 orders of type buy with price 10 are placed. There are no sell orders, so the 5 orders are added to the backlog. - 2 orders of type sell with price 15 are placed. There are no buy orders with prices larger than or equal to 15, so the 2 orders are added to the backlog. - 1 order of type sell with price 25 is placed. There are no buy orders with prices larger than or equal to 25 in the backlog, so this order is added to the backlog. - 4 orders of type buy with price 30 are placed. The first 2 orders are matched with the 2 sell orders of the least price, which is 15 and these 2 sell orders are removed from the backlog. The 3rd order is matched with the sell order of the least price, which is 25 and this sell order is removed from the backlog. Then, there are no more sell orders in the backlog, so the 4th order is added to the backlog. Finally, the backlog has 5 buy orders with price 10, and 1 buy order with price 30. So the total number of orders in the backlog is 6. **Example 2:** **Input:** orders = \[\[7,1000000000,1\],\[15,3,0\],\[5,999999995,0\],\[5,1,1\]\] **Output:** 999999984 **Explanation:** Here is what happens with the orders: - 109 orders of type sell with price 7 are placed. There are no buy orders, so the 109 orders are added to the backlog. - 3 orders of type buy with price 15 are placed. They are matched with the 3 sell orders with the least price which is 7, and those 3 sell orders are removed from the backlog. - 999999995 orders of type buy with price 5 are placed. The least price of a sell order is 7, so the 999999995 orders are added to the backlog. - 1 order of type sell with price 5 is placed. It is matched with the buy order of the highest price, which is 5, and that buy order is removed from the backlog. Finally, the backlog has (1000000000-3) sell orders with price 7, and (999999995-1) buy orders with price 5. So the total number of orders = 1999999991, which is equal to 999999984 % (109 + 7). **Constraints:** * `1 <= orders.length <= 105` * `orders[i].length == 3` * `1 <= pricei, amounti <= 109` * `orderTypei` is either `0` or `1`.
null
Database
Easy
null
12
everyone welcome back and let's write some more neat code today so today let's solve the problem integer to roman recently we solved the opposite problem roman to integer i'll link to that somewhere in the top right if you want to check out that solution it's a pretty similar problem in this case though we are given some integer value for example maybe we're given the integer 9 and we want to convert it into the roman numeral representation of that number in this case that happens to be x before that x comes an i so based on this table that they conveniently gave us x is the number for 10 and i is the number for one you know that's what these individually these letters represent those numbers but when you combine them they are nine and why is that well there's a rule in roman numerals you know the straightforward explanation for how numbers work with roman numerals is it goes largest to smallest right so if we wanted 1 500 uh we'd put an m and then we put a d right this is 1000 this is 500. if we wanted 2 500 we'd put 2 m's right m and then a d for 500 right this is 2 500. but there are some special rules where actually the smaller character you know the symbol with a smaller value can go before the symbol with a larger value and it only works in a few specific cases and those cases are described below with these three bullet points so an i can go before a v which is the number five and if it does go before v so if we did iv that would be the number four if i goes before x that is the number nine so it's a special case right and there's a few more special cases and x can go before an l and that will make the 50 turn into a 40 or the x can go before a c and that will make a hundred turn into 90. and there's one more case here c before d is 400 c before m is 900 so if we didn't have these special rules the problem would be really easy because what we would do is you know given any number let's say we're given the number 1500 what we would do is first divide this number n that we're given by m and by m what we mean is a thousand because that's the numeral you know that's the value for m so we divide 1500 by a thousand and what we would get is we would do this with integer division and we'd round down so when you uh divide this by a thousand we get 1.5 uh divide this by a thousand we get 1.5 uh divide this by a thousand we get 1.5 but we're gonna round down to one this one tells us how many m's need to go in our results so we'd put one m in our resulting string now if we of course if we had 2500 right this was 2500 then we'd get two and then we put two m's in our result we pretty much continue this uh once we've done the thousands place you know we'll take this n and then mod it by a thousand to basically eliminate the thousands place right because we don't need to look at that anymore we don't care about that anymore so by modding it by a thousand now we get to uh 500 is remaining right we already put one m in the output next we want to see how many 500s go into it so we uh we go to the next room roman symbol and of course the order that we do this does matter we're going to start largest to smallest right because that's how we build the output string so then we're going to do the same thing with d right 500 divided by 500 is just going to be one uh so then we can put one d in our output so this is going to be the entire result because uh you know if we take 500 now mod it by 500 we're going to get zero remaining so we can basically stop right we've found the result now so this would be really easy if we didn't have these three special cases below it would just be a while loop doing what i just described to you where we iterate through all the symbols from largest all the way to the smallest the only complication that these special cases give us is that we have some special rules that we're going to insert into this list of symbols basically for our purpose of this function this table is incomplete right because we have some rules down here that describe to us that c m is 900 and c d is 400 and there's a couple more rules so i x is 9 i v is four and remember how we do need to iterate through these in the correct order like from largest to smallest so basically to this table we're going to be inserting this 900 in between these two we're going to take this 400 symbol insert it between these two and you know etcetera this 90 is going to go in between these two because we want to maintain the order we want to iterate through them largest to smallest and so once we have made that modification to this table and we have the correct table then the algorithm is pretty straightforward right we'll just do the entire while loop stuff that i described previously we're going to divide this and then mod it just to know how many of these characters we need to have in our output and you know let's say we just had the number 900 as the input right what would we do we'd first try dividing it by m by a thousand right this divided by a thousand is going to be zero right that tells us that zero m characters are going to go in our result next we wouldn't try this number we wouldn't try d for 500 next what we would try is this because cm is another way of writing 900. so next we would try dividing this by 900 we'd see that it'd be one so that means we need to add one occurrence of this string it's not a single symbol this time so this string cm is going to go in our output and then we'd continue to build that output string the roman representation of whatever integer that we're given so that's the entire idea now we can get into the code okay so now let's get into the code as you can see i've pretty much you know completed this entire function this is really the hard part writing out this entire table i wrote it as a list of smaller lists right a nested list where each list is just a pair of the roman string mapped to the integer the reason i did it with a list instead of a hashmap is because we do need to do this in the correct order in this case it's sorted in ascending order so we're going to iterate through this list in reverse order so let's build our result which is going to be a string and then let's iterate through this list in reverse order we're going through a pair of values the symbol and the value and we'll iterate through this in reversed order we can do that like this in python and now we're actually going to be processing this so we have some number that we're given right we want to know uh does the current value that we're at uh you know whatever symbol it happens to be does it divide this value if this is zero maybe we were given an integer of 400 and we're trying to divide it by a thousand uh this is integer division in python by the way if we're trying to divide it by a thousand we're going to get zero that means that this symbol is not actually going to go in the result but if it's not 0 if it's greater than 0 then that symbol is going to go in the result which is why we have an if statement here so if it does go in the result we want to know how many times is it going to go in the result that can be our account so num divided by val just doing the exact same thing again maybe it's one maybe it's two maybe it's three who knows whatever it is we're going to store it in count so that's going to tell us how many times we want to add this symbol to the result in python you can actually take a string that's what sim is going to be whatever that string is i iv whatever and you can multiply it by an integer in this case count and what that'll do is they'll just basically take this string and create this many copies of it and then append them together so it works out conveniently for us we want maybe two copies of this string and we want to take those copies and then add it to the result so we can do that just like this and last but not least we want to potentially update this number right if it was maybe 1400 and we you know we counted okay there's we want to divide it by a thousand right there's one thousand here next we want to mod this by a thousand because we don't care about the thousands place anymore we just want the remainder so that would set the remainder to 400 so that's what we're gonna do we're gonna take the num mod it by uh whatever value that we divided it by previously and then set that equal to itself so that we can use the updated value in the next iteration of the loop and yeah that's the entire solution uh pretty short then we can go ahead and return the result the hardest part is just typing out this entire table let's run it to make sure that it works though and as you can see on the left yeah it works and it's pretty efficient so i hope that this was helpful if it was please like and subscribe it supports the channel a lot consider checking out my patreon where you can further support the channel if you would like and hopefully i'll see you pretty soon thanks for watching
Integer to Roman
integer-to-roman
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. **Example 1:** **Input:** num = 3 **Output:** "III " **Explanation:** 3 is represented as 3 ones. **Example 2:** **Input:** num = 58 **Output:** "LVIII " **Explanation:** L = 50, V = 5, III = 3. **Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV " **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= num <= 3999`
null
Hash Table,Math,String
Medium
13,273
581
hi guys hope you're doing great a today's question is shortest unsalted continuous sub-array given an integer continuous sub-array given an integer continuous sub-array given an integer array you need to find one continuous sub array then if you only sought this sub array in ascending order then the whole array will be sorted in ascending order too you need to find the shortest such sub array and output its length so for example here the given array is this so the output is 5 because if we sought 6 4 8 10 and 9 in the ascending order then doing 15 are already in there globally sorted positions and that is why the answer is 5 because that is the shortest sub array that we need to sort right so summary means it's like a continuous every which does not mean any random elements from anywhere in the array it means like a continuous set of elements in the array right ok so yeah the length of the input array is in this range 1 to 10,000 the array is in this range 1 to 10,000 the array is in this range 1 to 10,000 the input array may contain duplicate so ascending order here means less than equal to alright so this question is a slightly tricky one because we cannot just use a sorting algorithm to sort all of them you know and get the answer that would not be a very good solution if we try to exhort it and then track each element where it was and then find out what is the minimum number of elements we had to sort so that will be high on the time complexity and space complexity boots and if we were to find a solution which does not have that much we just have to apply some simple basic logic here which is that we have to find that first element right who which is the beginning of the unsorted array and obviously the last element which is the end of the unsorted array or the sub-array which we have or the sub-array which we have or the sub-array which we have the sort in order to make the whole area sorted right so now since we want to sort this entire thing in ascending order and the answer depends on that to find that first element what we have to do is that if we are saying that this has to be sorted in the ascending order we traverse the array from the left to the right and find that first element or we can call it like a tipping point where it's not in the ascending order right so for example 2 6 this is in the ascending order but as you can see 6 drops down to 4 which is not the ascending order right so we find that minimum value which we are able to encounter in this way so like 6 and 4 okay so we record for right then 4 and 8 are in the sending order 8 and 10 are C and D ascending order but 10 and 9 are not so the value after dipping is 9 but that's more than 4 right so we don't bother recording that or we don't update the minimum that we were recording similarly we start from the right to the left and you find the first rising or we find that rising value like right which is not supposed to be the way it is right for example if we talk about 15 and 9 so this is in the descending order which is expected so it's great 9 and 10 this is not in the descending order right so we have to record 10 here right and you want to find the maximum value we can find in this way now this is in agent and are in the descending order for 8 descending 6-4 are not right but then 6 is not 6-4 are not right but then 6 is not 6-4 are not right but then 6 is not greater than 10 so we just keep it 10 and that's it so now we have found that 4 and 10 are those points where things start to go wrong in the area in terms of the sorting right so what we do is that we try to see that where will I have to place this minimum element and the maximum element which are not in there right places obviously because of the order where do I place them where do I place the Z minimal element and why it's necessary to record the minimum one is because if there is any other element which is more than that it will obviously come after that and we the only bother here to find that length of the surveilling right so if I am to place four somewhere it will obviously be placed before six and that is why that will sub-area would and that is why that will sub-area would and that is why that will sub-area would have to be sorted so we don't care about bigger ones right so this minimum value we start comparing it with the elements starting from the start from the 0th index and whenever we find a value which is greater than this right so let's say if we are searching for 6 right so if we find all right we'll be in this case we'll be searching for free so 2 is already smaller than 4 it means it's already in its right position but 6 is greater than 4 right so that would mean that this is the index from where our sub area would start and similarly when we try to look for 10 like values which are more than 10 which are less than 10 right so 15 is not less than 10 but 9 is right so it means 10 would come over here and that is why this would need to be shuffled and this is the end of the continuous sub-array which we will the continuous sub-array which we will the continuous sub-array which we will have to sort right so that's how we find the two positions and we just return the answer that is the difference between that plus one because it's all along space so let's try to implement this it's very simple to implement but it's a really good question it helps think about the whole problem solving in a very different way so let's just get started okay so as I said we need to have a minute which will be in teacher toured we want to initialize them with extreme values because you want them to be updated the very first time we see a value right so we just do the opposite okay yeah now will travel through the array starting from zero I less than now start then nums dot length minus 1 because we compare it with the I plus 1 element so we do not want to go index of those bombs yeah okay so now we have to check that if the number 5 so we expect it to be in the ascending order right so if at any point I is greater than nums of I is greater than none of I plus 1 we have a problem correct because that's not the ideal way in ascending sorted array so we have to yeah so we have to just update min with whatever is of min former number I plus okay science that's all after that we'll start from the end right now in Scotland minus one and we'll go till I is greater than 0 not equal to because will again be doing I minus 1 I minus okay so here if again now since we are traveling in the reverse order we expect it to be in the descending order so if my lumps of I should ideally be more than nuns of I minus 1 but if it is less than nuns of I minus 1 right then we have a problem so we just calculate max in silver fashion three maths dot max of max coma numbers of pi minus one yeah okay so now we have the min and the max values now we'll just compare like we will just again start from I equals to zero I less than on stood length - sorry zero I less than on stood length - sorry zero I less than on stood length - sorry no struct length yep and I plus okay and we have to check that if nums of I is more than the minimum right then it means that it is not in the right place okay and just as we find an element which is more than the minimum that means that it starts like that's the starting point of the continued sub area that we'll have to sort right so we just record that so let's take our and we just yeah so we'll just have to assign I do it okay and then break so our search is complete for this and similarly we will also have to start or from the back right so you have to do no sorry then minus 1 and I is greater than equal to 0 plus sorry I - - and just to 0 plus sorry I - - and just to 0 plus sorry I - - and just as we find that this element add nums of I is less than max right so then it's not correctly placed right yeah then R will be equal to by we have to break right and then finally we can return so if L if R minus L because our will always be greater so if R minus L is greater than 0 ok or maybe just equal to 0 square greater than equal to 0 then it's a R minus L plus 1 ok otherwise it's a zero so we don't want to present viewed values that's fine okay let's see that works oops oh yeah we need to initialize them so I guess that's because we are using this shouldn't be yeah okay so the time complexity for the solution is o of n because although they are traveling through the array four times but it's still like n plus n which gives us go of N and the space complexity it will be off one because we are not using any extra collection just two or three variables which is still a constant so I hope you guys enjoyed this video and find it really helpful if you do please like share and subscribe keep coding thank you guys
Shortest Unsorted Continuous Subarray
shortest-unsorted-continuous-subarray
Given an integer array `nums`, you need to find one **continuous subarray** that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order. Return _the shortest such subarray and output its length_. **Example 1:** **Input:** nums = \[2,6,4,8,10,9,15\] **Output:** 5 **Explanation:** You need to sort \[6, 4, 8, 10, 9\] in ascending order to make the whole array sorted in ascending order. **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 0 **Example 3:** **Input:** nums = \[1\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` **Follow up:** Can you solve it in `O(n)` time complexity?
null
Array,Two Pointers,Stack,Greedy,Sorting,Monotonic Stack
Medium
null
253
okay so lead code practice time so two goals the first one is to see how to solve this problem and then we also put some solid code here and the other thing is to see how to behave properly in the interview so let's get started so remember the first thing in the interview is always to try to understand the problem uh if there's anything unclear please bring up a question to the interviewer to ask him or her to clarify and also um think about the ash cases at the very beginning so let's take a look at this question so meeting rooms 2 the given array of meeting time intervals terrible intervals where integral i is equal to star i and return the minimum number of conference rooms required okay so if you have 0 30 5 10 15 20 then we need two uh two conference rooms to schedule the meetings without conflict okay like for this one we need only one all right so i think the first question is suppose there are two meetings uh one meeting and at 10 and the other one starts starting and uh do we consider this as a conflict um i would say this one i think this won't be considered as conflict let's assume that's the assumption and let's see the constraints so we have start i smaller than i so make sure so for sure that each meeting has a start time smaller than the end time and we have at least one meeting okay i think i pretty much understand what the problem is um i think there isn't too much of the ash kiss to consider but if you want to definitely think about some match case for i think if the if there's only one meeting could be on ash case like we can we don't need to write any processing code for that kind of task case so having said that the next one is for us to find the solution for it so what is the solution so remember that we can separate the conference start time and the conference end time into separate arrays so one is the start time array and one is end time array and we are going to sort it separately so first one we are going to have 5 15 for example when we take an example when we look at example one and the second one we will have 10 20 and 30 after sorting so the thing is um for a given so for and for a given end time uh we just need to see the number of the meetings that comes before it um so the thing is like this so we are going to iterate through the so we will have a separate index for the end time and starting at zero and then we keep track of the number of uh start time that comes before it so there are two of it and then uh when it arrives at 15 that means that one meeting has end and the other one just started so 150 since 15 is larger than 10 we are going to move our in an index to the next step so it's something like we try to keep track of uh for a certain ending index we keep track of how many meetings are before it um uh before it's um so yeah so the general idea is for a certain ending time you see how many meetings are that comes before it but not before the previous meeting so that's pretty much the general idea and the run time is going to be um all of unlock and suppose there are n intervals here because we need to do sorting for uh the separate start time array and the end time array so having said that let's do some coding so in the coding part care about your correctness wise and the speed don't be too slow and also the readability all right so first of all you have the start time uh so this would be the new uh let's say uh int meeting no is equal to intervals dot uh lens all right so it's going to be new in uh meeting um okay and then the end time is going to be new it's this is the 18 num all right so we are going to sort it so it should be arrays dot sort sure okay so where is the story start time and the arrays dot sort this is end time all right so having said that you have a variable which is called max uh the uh let's say required meeting room let's start with zero and uh we will have the end time idx let's start with zero and uh sure so well uh so let's say we also have the start time index it is for the use case to iterate through the start time array and the end time array so well the start time index is smaller than uh required material sorry uh smaller the meeting room numb meeting them and the end time index is smaller than the meeting uh let's say we have like the current meeting room no that's equal to zero so well this one is true um i always say if the interval starts time sorry it's not the intervals it's actually the you're just trying to compare the start time and the time so if um starts time uh start time idx is smaller than uh the end time idx that means that we need to plus the current meeting room number otherwise uh we actually we otherwise we actually don't if this is small it is smaller than we need to move also move the start time idx otherwise it means that the start time all right so i think i'm this is this should be the reference okay so other uh this is and the time and okay and the time index so otherwise it means that the start time of this meeting is cut that comes after or just about the same time about the current end time meeting end time so in this way we need to do is uh we will need to plus the end time uh index address and we don't really uh then we need to i see so we need to minus the current meeting room no because we have just a free day room uh because one meeting just end just ended and we will make sure that we keep track of the record meeting room num as equal mass dot max and uh what it says this should be the car meeting room now and finally we will return the record meeting room number all right so um let's see um yeah so let's see for this one let's do some testing so let's for see for this input example first of all we have the start time as 0 5 15 and ended time as 10 20 30 and the start time idx starting at zero all right so i'll just copy paste everything here so we will have this and this all right so uh when start time so when we start time idx and time ideas are both equal to zero and uh we see that um start time idx is so the first start time is smaller than the current end time so we are going to plus the current meeting room which is equal to one and also required meeting room is equal to one at this moment and the next time so and also plus the start time index and next time we see that 5 is still smaller than 10 v uh plus the current meter number and then we plus the start time index and also we increase the we set the required meeting room numb as two at this moment and for the next one which is 15 it is larger than 10 so it means that um so actually when we when it comes to a it is a new meeting and uh it means a new meeting just started and then another meeting just ended so we shouldn't just uh minus the car meeting room that's because if so it means that we only need one meeting room but currently we need two meeting rooms so that's the that's about we definitely need to fix so let's see how they do it so if the start time index is so it means that so we need to if the uh if it is smaller then of course we are going to uh plus it otherwise it means um it means that the start time comes okay so it means the start time which is the 15 that comes after it so um i'll say so if it is so zero five two meeting room for sure uh no problem and then the fifteen is larger than ten but we don't really need to we don't really want to minus the current meeting room so how to um actually so how so this else branch is for sure not actually true so when we encounter a meeting that should end the current meeting then we should so if the so a plus the meeting room number um okay so actually i think i need to change to another way to write this so it should be in i let's say starts time index is equal to zero and the start time index is smaller than um meeting num and the plus the start time idx so uh if the start time idx is smaller than the end and time idx that means that we need to we could we need to plus the current meeting room so otherwise um it means it comes either after or okay it means it cuts it means this meeting comes before they sorry comes after the current end time index so we will need to um it should be like it should be plus the uh let's say if we just the same play plus the current meeting room because we just start a new meeting started a new meeting and if this one comes after a something okay it should be something like this well the car well the start time idx is larger than uh the end time idx it's time for us to move the end time idx and at the same time e minus the current meeting room number and at the same time we will need to set the required meeting room number okay yeah i think this should be the right version let's see so for this one uh let's say we reset everything to be zero and then we so for the first one plus the current meeting room number and uh well so and also we see that the start time is smaller than the end time so the while loop is not going to be stepping into the next time uh we plus the current meeting room number and at the same time you update the required meeting room number when start time idx is equal to 2 so we encounter 15 which is lesser than 10. first of all we will increase the current meeting room and we will use a while loop here um so the well up here is going to iterate through the end time index until it hits a number that's larger than 15 which is 20 so well this one i will plus the entire index and also minus the uh current meeting room which is equal to two now okay so well this one is like so it should be larger or equal or just larger so well start time is larger or equal to the end time we can just remove the okay so while the end time if the end time is smaller than the start time that it means we it's the median is finished if it's equal it means definite he is finished as well okay so i think this piece should be good let's give it a shot start time idx uh where it will start on my days it's already defined here okay so some compile arrow and the time okay so okay this is a typo here so this one it is uh what is that it's like index out of the boundary well start time idx is larger or well the start time idx is uh larger or equal to how could that be index out of the bone how could that be index out of bound because so what's the task is it's 0 10 0 35 10 15 20 uh which is exactly this one um so let's see 10 20 30. so start time well start time idx is larger than the end time and the time idx then i will need to plus the end the time at the x and minus primitive so this is complaining about which lines 38 all right so this is complaining line 38 but how can it be array index of the bond exception index three out of the bond for length three it shouldn't be so oh okay so actually i haven't given this uh yeah my bad so i haven't really done anything for it so in start time and the end time so for uh inside is equal to zero i smaller than meeting um plus i so starts time i is equal to intervals i zero and the time i is intervals i and this is one all right other than that i cannot really think of yeah other than that i cannot really think of anything that's that shouldn't work all right so i forgot to initialize um the start time and end time which is my thoughts i will still fit so let's give it submission all right so now it's accepted so regarding the task is set up um i would say setups set up some meetings with overlap or more than one meeting with overlap um and also more than two meeting with overlaps and also submitting now overlapping i would say that should be good enough regarding the task coverage so that's it for uh this uh coding question if you have any questions about this puzzle please give me uh leave me some comments if you like this video please give me a sum up and i'll see you next time thanks for watching
Meeting Rooms II
meeting-rooms-ii
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_. **Example 1:** **Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\] **Output:** 2 **Example 2:** **Input:** intervals = \[\[7,10\],\[2,4\]\] **Output:** 1 **Constraints:** * `1 <= intervals.length <= 104` * `0 <= starti < endi <= 106`
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied. If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
Medium
56,252,452,1184
380
hey everybody this is Larry this is day 16 of the leco daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's PR and today's uh video and all these things uh we'll just go straight to the pr this time I'm a little bit tired I'm trying to take a nap but I will do an extra prom in any case but uh yeah I don't know I it's just very cold here in New York it is um like 25 26° which is like3 or 4 like 25 26° which is like3 or 4 like 25 26° which is like3 or 4 Celsius uh and I just came back from running about 4 five miles something like that and which is not that much but it's so cold my I'm just not in shape for it I guess um trying to do it in a t-shirt which also didn't help uh but t-shirt which also didn't help uh but t-shirt which also didn't help uh but anyway that aside so I'm just trying to get this done so let me know in the comments if anything is crazy um today's p is 380 insert delete get random of one so okay let's see what this means Implement insert of value is it like um is it set okay remove get random get a random element from the current elements yeah I mean I think there a couple of ways we can think about it um how do we want to do it I mean I think we move is a little bit tricky as well a oh one huh so the get random thing right I think to uh I guess average of one is not the same as okay I think I have an idea um okay yeah um this is kind of a tricky one actually I think I mean it's only a medium but I think a lot of the difficulties on the analysis and the analysis is on the complexity and average is really average is such a weird thing to say because it's not really a precise term even though maybe it is what most people mean anyway when they say amortized right um and am amortization I'm GNA try something uh and then we'll go over it in Metro back but really to be honest um just to kind of go over my thought process a little bit it's just that I kind of figure out quite a few things in my head to kind of see what worked uh the number one thing that I wanted to do was the get random part right get random to make it all of One um you really an idea uh let me actually get a random thing real quick I forget the exact um the python random um uh um yeah I forget Python's uh random API is what I meant to say right so you want to write something like this like o and of n um because then now you get a thing right so then from here I'm like okay so you need a list of stuff so that you can kind of have random assess right if you have if you do anything else any most and any data structure where you do not have random asss this is not going to be a constant time and it might not even have um you know uh um it might not even have you know an idea about uh constant time because you know may be a little bit messy okay so what does this mean right so then now that means that I have to have an away right so that's why I was like okay so here I'm like okay maybe I have a self. is equal to self and then you know then we could just do like end is you go link of self. away um then we take is this inclusive actually I don't know uh inclusive okay it's actually weird but maybe not I don't know if it's weird or not but yeah we take a all is you go to do and then we just return soft. of all right uh I mean that by itself obviously makes sense straightforward easy uh but now we have to do the thing right so self. insert we would maybe have something like this like a pen value uh and then we move this maybe right uh we moove well something like that I don't remember but however um and it could be negative okay fine uh but yeah obviously uh is this a pen yeah I mean OB obviously there a couple of issues here this is not done just and I know that it's not done just to be clear um the obviously this is going to be a set so we need to fix this to be a set right so let's fix that real quick so maybe we have like a scene type thing we keeping a set and then now we have sub. scene. add value or something like that uh or like you know if value not in sub. scene then we add it which is what we do right that's fine right and then we moove over it's going to be the same with value not or if value is in scene then we actually do removal we do right uh is that right I'm just running real quick just to get I don't forget if this is called remove or something okay it doesn't complain so it looks good even though H gives me wrong answer oh I have to return something with insert and force I guess okay so then now um so if it returns true if the item is not present so that means another way of saying this is return true if this is inserted so that's what we'll do so we'll just return true here and return forse here and then we move this if the item is present okay yeah so that means if the action is done basically right so we you know okay so we one it real quick but uh but the there is a problem with this right this looks pretty reasonable pretty uh pretty good so far but the problem is that of all these things well there's really only one thing that you need to worry about which is the complexity and of course uh this is I mean it's just ini initialization uh insert it's going to be all of one this is all one we're happy uh removal uh this is all of one but this is all of n right we have to find the index in which this is um we have to find the value in which this is in the array and that's going to take linear time so this is linear right and there's really no uh easy way to I mean you could really make it's easy to make a n you know n Square thing right so this is nothing with mization because you could just remove the last element and it just goes through the list and then keep on removing the last element then you get an N Square thing right um this stuff is all of one so that's fine so how do we fix it right well one way that we can fix it is just you know instead of doing this operation we only remove the value later on when we need it so how do we do it so well one is that we get rid of this but then now uh um now here we may actually you know get something that is not in the value or not you know not in the set how do we do it so basically now maybe we could you know we do this so maybe I do a while true just because I don't know maybe we'll change the conditional yeah so then now if this is in s. scene then we can just return this value otherwise what do we do that if this is not in scene that means that we remove this here but we did not remove it here so then now we can remove it here now right so that means that we can do something like sub is to none and then you kind of keep going the problem of course is that this may go Infinity though it's not that bad but it's just that you know you get empty spaces throughout right so like maybe you have like one two 3 four five and then you know you remove this or it's a n not a force and then eventually you know this is going to actually like keep on looping pretty badly until you get a one two and a five um which is you know no bro so easy fix is actually just um set this to the last element and then pop the last element and that's pretty much it unless it is the last element but I think if this is the last element it just doesn't do anything so it should be fine uh yeah and that should be good because eventually well I mean this will only be true if self. scene is um it's at least one element I don't know if we need to worry about that oh that's what they say okay let's give it a spin looks good let's give it a submit so the question you might have is then oh well wow in the past I've kind of struggled with this one it seems like so then the question is well how do you do the math of amortization right well the thing is that here in this removal um and you kind of fill in the I don't know if I made that explicit or clear enough um when you do this you actually fill out from the back so then now you're trimming it size by one and there's no space in the thing right um and the re reason why this is that every time you run this Loop you remove one element or you return a good element right so that means that this Loop will only remove one element or will only Loop the number of removed L limits time and that gives you that average or amortization uh here because now for each value you want to remove you will only remove it once there is some like hm I guess there is actually an edge case though I have to be a little bit careful uh yeah I think this is actually slightly wrong the way that I did it slightly inaccurate and the reason is because I think you can like the way that I did it anyway so maybe I have to like keep the indexes instead maybe that's a little bit better um no I mean the reason is that you could remove and then add and then this Randomness would have actually multiple things they did accept it but this is actually a little bit inaccurate so maybe we needed um another thing which is like um used is you right or like maybe removed or something like that and then here we can just is we return false and then here um man we have to do way more kind of like tracking cuz now we basically have to track um I have to track the index maybe we move this in good enough down here um maybe we I just do it as a set then I'm a little bit lazy I mean there a couple ways you can handle this but that's basically the idea um here maybe we append uh the length of the aray so then now this is the last element then maybe before we insert though oh no that doesn't I kind of keep you still need to use a reverse lookup um so yeah you need to do a index look up or something like this yeah so then like maybe a look up is you go right and then now yeah look up is of uh the value is equal to length of the aray which is the last element to insert and then here um we want to do sub. lookup oh no the look up is fine and then now we have to um yeah so basically let basically we want to say that um yeah you have to handle the case where you remove this but this is not removed yet right so the insertion we would actually have to wow if I meum this is kind of like I mean I don't know they kind of accepted something but U but it definitely still struggle right so if Val is in sub. lookup then what does this mean that means that um we haven't removed the previous yet right um so then now we can actually if this is in s. lookup we can add it to scene we can always added to scene this we just don't do this and we don't aen right so if this is not in s. look up then we do this I think now this should be good um basically now if this is in scene we um we also want to make sure that okay so it is in scene then that means that's good okay otherwise here we want to do we want to delete this right I guess I didn't really need this look up then why did I do it this way oh because so I could do the index but I don't need the index I guess I just needed to do another thing but I keep on confusing myself this is kind of tricky so maybe I could actually make this cleaner by doing it as remove right um so this will contain things that should be removed but not yet right um so then now here maybe we can change if this is not in uh self. removed or if this is INS that removed then we can remove it from the value we don't need this anymore and here is an else because that means that if this is not in removed then this is a new item so then we can add it otherwise this is in the way already and then here we do sub. removed. add the value and here we can actually do uh yeah sub. removed do remove this value all right give a submit yeah that's a way small Nuance case but it still is a thing that's why cost what did I do last time I am curious I guess this thing is pretty high remove is huh the way that I did it last time was removed huh maybe that way is easier I don't know sub dictionary and stuff insert so over in there we know remove then move to index oh huh I guess this way is actually smarter even though I didn't get a onetime errow basically on remove you just look up the index in which it is in the ARR and then you push get it from your back wow all yeah that way is made cleaner so today the way works but it is definitely way more complicated versus the last time I did it um last so this is the code from last time definitely much cleaner basically on removal you just yeah this is way cleaner so this is the way that I recommend it not the way that I did it today but yeah uh this is all just going to be uh constant time I don't even think there's any averaging here that's why it's kind of pretty uh it just kind of you know you keep going I think maybe I got confused by the averaging or like the quotquot hint and then I just try to average in but yeah so two ways to do this but yeah but um hopefully I kind of explain the do process though even though maybe I didn't quite do it whatever today uh let me know what you think it's snowing here in New York tomorrow it's going to be cold I'm going to I don't know just take a nap and yeah that's all I have for today that's all I have for this one let me know what you think stay good stay healthy toal Health have a great rest of the week stay safe I'll see youall later and take care bye-bye he
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
1,785
hey everybody this is larry this is me going with q2 of the weekly contest 231 minimum elements to add to form a given sum i did trash on this form uh i have as you can see i spent eight minutes and two wrong answers um and you can watch me start with live afterwards because the short answer is i misread the prom uh so hit the like button as a subscriber and join me on discord and make fun of me on this forum on discord if you like in the comments as well but basically what i misread was that i thought given these numbers i have to change them so that the goal is to negative four and i did this with a greedy algorithm it's fine it's somehow also luckily or unlucky in my case passed the test so then i was just submitting it uh unfortunately actually it's easier than that you can actually add numbers i think i just didn't read this clearly um because also i think it's just a little bit weird for me um because i thought if that's the case then you don't even need this away you just need the total which happens to be the case but i like i said i misread the problem um so yeah so the formula just becomes this which is okay you have the total which is you know somewhere over the array and then you have to go minus the total and then each number can be at most limit uh you know yeah each number can be limited right so that means that you know it just becomes like for example if the if um if the difference between a go and the total is 10 and your limit is equal to three then that means that you needed to do this four times because it's 10 divided by three um rounded up which is why there's this limit minus one thing and that's the delta term that's the answer um this is going to be linear time constant space linear time because we do this sum operation and constant space because we just have a couple variables um yeah that's what i have for this problem it's actually pretty simple and i feel really bad to be honest a little bit to get two answers so it tells you that you know sometimes if you slow down to read the problem correctly it'll save you time so uh yeah you could watch how i messed up after the con or during the contest next is hmm is not enough okay um um it could not be possible um hmm oops oh whoops what did i do uh chef tested this is not possible i was looking for this that it didn't tell me what the answer should be right um what is this answer it just goes too big it's just negative one i mean i don't know actually would thought about this case but it doesn't and there's no expected answer of course am i missing something let's just go what did anyone get this fight wow a lot of people got this right what am i oh wow i totally misunderstood this problem i told you oh my wow okay that is dumb on my part okay i was solving the one problem okay who am i doing um so basically go minister what don't do wow i totally misunderstood what they were asking yikes hey uh yeah thanks for watching let me know what you think about this prom explanation or whatever uh hit the like button hit the subscribe button join me on discord and i will see you next time bye
Minimum Elements to Add to Form a Given Sum
hopper-company-queries-ii
You are given an integer array `nums` and two integers `limit` and `goal`. The array `nums` has an interesting property that `abs(nums[i]) <= limit`. Return _the minimum number of elements you need to add to make the sum of the array equal to_ `goal`. The array must maintain its property that `abs(nums[i]) <= limit`. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** nums = \[1,-1,1\], limit = 3, goal = -4 **Output:** 2 **Explanation:** You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4. **Example 2:** **Input:** nums = \[1,-10,9,1\], limit = 100, goal = 0 **Output:** 1 **Constraints:** * `1 <= nums.length <= 105` * `1 <= limit <= 106` * `-limit <= nums[i] <= limit` * `-109 <= goal <= 109`
null
Database
Hard
262,1779,1795,2376
628
hello everyone so in this video let us talk about a problem from lead code the problem name is maximum product of three numbers so the problem goes like this that you're given an integer array nums find three numbers whose product is maximum and return the maximum product of those three numbers so given a nums area as you can see in the examples and you have to find out three numbers such that if you multiply those two numbers the product of them is as maximum as possible now the simple intuition for this problem is why not just multiply the three maximum numbers because the three maximum numbers if you just multiply all of them will give you the maximum product as possible now how can you find out the three maximal numbers you can find out the three maximum numbers using uh like you can easily sort out the whole array and then find out the last three numbers in the sorted array if you sort them in a decreasing order or like lots in an increasing order that the last two numbers are the three maximum numbers okay then you can multiply those three numbers and then you can just find out that what is the product of that but whether that's the perfect answer like that's the always answer no that's not the correct answer can you tell me why can you tell me what is one more case in which this whole approach will fail can you think about that let us move down to our drawing board uh let's see that if you have for the previous example if you have numbers like this one two three four five and if you sort them out it will be three the list is in the increasing order in the last three numbers like three four five well multiplied will give you the maximum product that is fine but let's say that the numbers are also like this because they can be negative also in the example okay let's say that the numbers are like this after sorting out the array has numbers like this minus 100 minus 99345 after sorting this will be like this because it is increasing order minus 100 will be the small smallest one and that is the whole numbers after sorting out now if you take the last three numbers the multiplication of last three numbers will be 3 into 4 into 5 but this is not actually the right answer why because these two numbers are pretty large and when we multiply two negative numbers the negative cancel out and they become a positive number and thus what you could like you could have also done is take the first two numbers if you take in the first numbers like this minus 100 and minus 99 and multiply it with the last number possible then this negative will get cancel out it will become 99 into 100 into 5 and that is much bigger than this number because this number the negative will cancel out now you might be thinking okay why not take the first three number itself it can also have like that is also a possible case you could have taken the first three numbers also but as you can see because i want to maximize the product these two numbers will cancel out the minus signs and this will totally become a positive number this would then when being a person number i want a larger portion number now so the largest positive number is the largest one that is the last one so why not take that only because that will actually increase the product by more percentage also it can happen that the third number can be negative as well like if it can be like this minus 98 so if taking the next number can also like decrease your product and can make it negative again so there are two cases actually either to take the last three numbers or to take the first two number and the last number that are the two cases you have to just find out the maximum among both of these cases which is the maximum product that's the answer and that's the overall logic for this problem let us move on to the actual uh code part as you can see first step sorted out now instead of sorting out if you want to more optimize this because you're just finding out actually as you can see five numbers the first two numbers and the last three numbers and based on that you have two options whether to take the first two numbers and the last number and the or the last three numbers so you could have done in o of n you have you got to find out but that would be a more complex code because you have to find out what is the most smallest number second smallest and largest second largest and third largest you have to find that in of n you can all you could have also find it out it will be o of 5 n because you have iterated over this whole array 5 times if i find out those five numbers but i don't think so that much complexity is required like uh because you could have solved this in o of n only of n login for sorting because the constraints are pretty small only i hope you get the point and says after sorting this out it will become a piece of cake you have to just take the last three numbers multiplication or the first number that is with index and the last two number so like the first number second number and the last number that is both of them whatever is the maximum answer is the actual answer i hope you understand the logic and the code part for this problem we are just sorting it out so it is of n log in the time complexity thank you for watching this video till the end i will see you next time until i keep coding and bye
Maximum Product of Three Numbers
maximum-product-of-three-numbers
Given an integer array `nums`, _find three numbers whose product is maximum and return the maximum product_. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** 6 **Example 2:** **Input:** nums = \[1,2,3,4\] **Output:** 24 **Example 3:** **Input:** nums = \[-1,-2,-3\] **Output:** -6 **Constraints:** * `3 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000`
null
Array,Math,Sorting
Easy
152
539
you what's up guys think we're here and you Tecna coding stuff on twitch and YouTube check the description for all my information I do premium link oh problems on my patreon you can reach out to me via discord this is 539 minimum time difference I like this problem I think it's a one that definitely makes you think for them you know the optimal solution is pretty difficult given a list of 24-hour clock difficult given a list of 24-hour clock difficult given a list of 24-hour clock time points hour and minutes format find the minimum minutes difference between any two points in the list okay so the list in this example is 23:59 and 0 list in this example is 23:59 and 0 list in this example is 23:59 and 0 the minimum difference is just adding one minute to 23:59 and then it turns to one minute to 23:59 and then it turns to one minute to 23:59 and then it turns to 0 instead of going all the way backwards that would be like 1439 minutes to do go all the way backwards but the thing is this they don't have that many examples but look at this the number time the number of time points in the given list is at least 2 in won't exceed 20,000 so is at least 2 in won't exceed 20,000 so is at least 2 in won't exceed 20,000 so that means the list can have a ton of time points it can be like this right it could be like you know 10 or and 11 and you know whatever you want you know like 1:30 there's like 0 1 30 or know like 1:30 there's like 0 1 30 or know like 1:30 there's like 0 1 30 or whatever so these this is like a potential list - it could be up to potential list - it could be up to potential list - it could be up to 20,000 different string representation 20,000 different string representation 20,000 different string representation of numbers and what we want to find is the minimum difference between any two points in this list so the minimum difference is obviously still 23:59 and difference is obviously still 23:59 and difference is obviously still 23:59 and 0 cuz it's just 1 minute compared to you know this is like a 60 minute difference from here to here is very long that's like you know 10 hours or more and you know the other ones there's nothing closer than these two right so that's just an example I came up with but yeah that don't really explain that but you can have a ton of these you know strings there's little you have a lot and you want to find only between two points you just want to find the minimum difference of you know two points within the array so how do we do this is not very this is hard this one's hard honestly this is a very difficult problem I think to come up with a the best solution it's not that difficult if you think of like worse solutions like n log n with n space that's not a too difficult of a solution if you use external data structures and stuff like that but coming up with a linear solution with constant time space is very difficult for this problem you have to sit and think about it a lot and what we're going to be using is buckets to solve this problem we're gonna do it in linear time constant space and we're gonna use a bucket array of boolean's so we still consider this constant space because what we're using here is we're gonna now we're gonna loop for each time point and we're gonna have an array of all possible minute combinations so this is gonna be a boolean array of 24 hours times 60 minutes which is fourteen hundred and forty different points within this array each different point represents a different it's all possible times right one minute up into 1440 minutes is from the time 0 up into 23:59 so we just multiply the hours by 23:59 so we just multiply the hours by 23:59 so we just multiply the hours by minutes so if it was one hour we just count that as 60 minutes and then you know one if doubt if the time was you know for example 1 0 1 then what we would do is we'd count this we just take this we multiply it by 60 so that'd be 60 plus 1 so it would be the 61 position in this array but we're doing indices so be 60 but what we're gonna do now is we're gonna go through this and we're going to loop through every time point we will loop through every time point in this array and like I said it could be a lot of time points we're going to go through this boolean array and markdown at that particular index of whatever time we're looking at in the minutes index in this array we're gonna say okay we saw this time so we're gonna just loop through so string time in time points the array this is just looping through the array so it's gonna go like this one than this one etc and we're going to split the time up we're gonna say okay string array time split is equal to time dot split and we split on the colon so that we can because this is a string we got to split it so that we can grab the hours in the minutes right and what we're gonna do is we're gonna do this is a string so we have to do this int hour is equal to time split of zero because it's going to be the first part of the split right if we split on this the first index the you know the position 0 will be this position 1 will be this so we grab the our a position 0 and it's a string still so we have to do integer dot parse int which is just a method to convert a string to integer in Java then we want to get the minutes so we want to say minutes is equal to time split of 1 and then what we'll do is we'll say time scene of hour times 60 you could put this in parenthesis to make it a little bit clearer like I said we multiply the hour by 60 to get the hour and minutes form plus minutes or plus minute is equal to true so we just basically take each time and we convert it into all minutes and then access this boolean array and say ok we saw that time so we're saying we're going into this boolean array and saying we saw this time and we loop through every time in the time array and we say where we saw the time into an array and this is constant space because this is only an array of size 1440 you could count it as you know o of 1440 or whatever but this isn't we're not putting each time into an array that would be linear if there twenty-thousand time points and we put twenty-thousand time points and we put twenty-thousand time points and we put all of those into an array that would be linear with the number of time points but this is only 1440 maximum because that's all the possible minutes in time so we're gonna mark this as true and if we see a time if we see the same time again well we can just account for that here if time scene if we have already seen the time that we're about to add into our array so if time scene of the current time we're looking at has already been seen then we're just going to return zero because the that means we saw two of the same times in this array so for example if we saw like zero twice we'd be looping through we see this then we add that into the array we see this we say okay that into the array so we say okay we put true at this at index zero in the array then we see it again though we see it again here and we say okay wait a second we've already seen this we set it to true last time it's true now so the minimum difference between two points if we've seen a duplicate is zero right there's nothing that can go less than that they're exactly the same so zero so once we do this we've filled it boolean array with every possible time that we can see in this array and we've seen we say if we've seen it or not so now what we want to do this is the part where we find the minimum difference between points so what we're going to use is we're going to use the integer wrapper class so that we could set it to null at first set our variables to no we're gonna say first time we see first time seen is going to be equal to no we're gonna say integer previous time seen is going to be equal to null as well we're going to say integer min minimum difference whatever you want to call it minimum difference this is gonna be what we return we'll just set it to a maximum you usually want to set your mins Max's so what we're gonna do here is we're gonna have first time sea scene be the we're gonna loop through this array of all the possible times and if we've seen the time the first time we see we're going to a set first time scene to that and leave it and we want to do that so at the end we can compare the last time we see previous time is just going to get updated every time we see a new time in this array because it's all boolean so if it's if we've seen the time if we added it in from that array from this then we're gonna just keep updating previous time to that at the end previous time will be the last time so we're gonna just do a final comparison at the end between the last in the first and if that's lower than the minimum we'll just update the minimum and return that so this is what we're gonna be returning we're gonna return minimum difference now all we have to do now is we're gonna loop through this array its size 1440 so I is less than 1440 I plus moving through this boolean array of times that we've seen and we're gonna say okay if time scene is true of the current position well then that means that we see in time so we actually want to do something and within this we're gonna say okay we've seen this time before is first time seen equal to null if so let's set that means that we haven't seen a time yet so we'll say first time seeing equals i briefed on seeing equals I so that's fine if first time seen is already set we don't care about it anymore so what we're gonna do is we're gonna just check we're gonna update the preview I'm seen write the proof time scene is equal to I every time we see a time that we have seen before we're just gonna update the previous and we're gonna also check for a new minimum difference will be the math dot min of the current minimum difference as well as the math dot min of the current time we're seeing so I which is the number of minutes so a time that we've seen minus the pre is time that we've seen so this will be the difference between the current time in the previous time so we want the minimum between that and the minimum between so this is the clockwise version of the difference we can also go counterclockwise in this array right we like you can see here we're going upwards and we're it goes right to zero so you can go counterclockwise as well and go all the way down to zero so counter clockwise would be the number of minutes minus I plus previous time seen that gives us the counter clockwise distance so we want the minimum we check the minimum each time between the current minimum and the minimum between the clockwise in the counterclockwise difference between the current time we're seeing in the previous time we're seen you update this every time throughout the loop and then at the end we'll be at the very end in all we want to do this will have found the minimum difference unless the very last time we see in the first time we see are very close together so we'll just do a check it's very similar to this kind of check so we'll just do math minimum difference is equal to math dot min of the minimum difference and no longer I but we're gonna use the previous time scene which will be the last at the end of all of this loop and the first time scene so the very minimum time we've seen in the maximum time we've seen they might be closer because you can just loop upwards like in this case this would be the last time we see and this would be the first time we see so the first time we see would be I mean this is a bad example but in a case like this with extra numbers you know like I did at the beginning like with one and you know ten thirty or whatever then this would be the first time we see this would be the last time we see in this array of minutes and the difference between these we want to check because they could be closer than just minimums we found throughout the array so yeah we just check that so last time - first time and check that so last time - first time and check that so last time - first time and 1440 - last time plus first time 1440 - last time plus first time 1440 - last time plus first time counterclockwise and clockwise distance so that's it that's the solution there it is linear with constant space a little bit difficult to understand let me know if you guys had a tough time understanding this one I think I explained it pretty well but yeah I mean let me know if you guys don't understand I'll try and maybe I can make another video I didn't I don't feel amazing about this one but you're converting the time into minutes each string time into minutes putting it into a minutes array looping through saying oh we saw this time as minutes putting it into a true truth setting it as true in here looping through all the times that we saw in the minutes array this time putting the first time and then putting the previous time each time we see a new time we've seen and then just updating the minimum of the previous and the current time that we're seeing and then at the end just want to check the first and the last so that's it's not too difficult once you understand I think just the syntax is a little bit tricky especially with the strings in this one but I feel like you guys can handle this it's not too difficult not one of the hard ones like some of the ones we've done before so let me know you guys think let me know if you have any questions I appreciate everyone I watch the videos and I will see you guys in the next solution or whatever so see ya I don't know alright see ya
Minimum Time Difference
minimum-time-difference
Given a list of 24-hour clock time points in **"HH:MM "** format, return _the minimum **minutes** difference between any two time-points in the list_. **Example 1:** **Input:** timePoints = \["23:59","00:00"\] **Output:** 1 **Example 2:** **Input:** timePoints = \["00:00","23:59","00:00"\] **Output:** 0 **Constraints:** * `2 <= timePoints.length <= 2 * 104` * `timePoints[i]` is in the format **"HH:MM "**.
null
Array,Math,String,Sorting
Medium
2266
1,339
hello this is problem number three of contest 174 here we are given a binary tree and we have to spread the binary tree into two parts and take separately the sum of each part and then multiply it so we have to maximize the product for example here we are given a binary tree and we are going to split the binary tree from here then it will be here in two trees and does some of each respectively is 11 and then so the product is hundred and ten so there is no possible option greater than hundred and ten so this is our answer similarly in this example we are splitting the tree from this edge so thus the solution of this part is six and the summation of remaining part is the 15 so 6 into 15 which is equals to 90 this down sir now we can try and be maintain this problem in a depth-first maintain this problem in a depth-first maintain this problem in a depth-first search manner so we will okay so suppose we have we can consider the tree into three parts this is for this node this is the left part this is the right part and this is the upper part although there isn't an upper part here but we will consider this as an upon upper part so we split the tree into three parts mainly in this for this root let me clean it up a bit okay so for this tree suppose we are considering this as the root so this is the upper part this is the left part and this is the right part so if we know the total summation of the 3 and the summation of left and the right part the upper part can be given by total - left upper part can be given by total - left upper part can be given by total - left - right - roots value so this is - right - roots value so this is - right - roots value so this is basically the upper part this is our part and we can recursively find the left and the right so there could be 3 possibilities here the first possibility is we can consider the upper part and this edge and then we will have this as the summation of left + right plus the summation of left + right plus the summation of left + right plus the root value so option 1 is equals to up multiplied by root + left + right option multiplied by root + left + right option multiplied by root + left + right option 2 is left multiplied by root + write + 2 is left multiplied by root + write + 2 is left multiplied by root + write + up an option three is equals to write x root + left + up so these are the three root + left + up so these are the three root + left + up so these are the three possibilities in each case so we can implement this in a recursive fashion so this is basically giving us the total summation of the tree so that is stored in total this is the function quality this is a function quality this and it is giving us the total now help to will be called and we will be a function call to help to get the value of left so you'll need to get the value of right now once we have large value and right value we can find the upper value as this total - left - right - suit then these are the three options that we discussed we will take the maximum of this I have initialized this answer as global then we will return left + right global then we will return left + right global then we will return left + right the suit's value from here so this is basically giving us the summation of the three we need to return the answer module 10 to the power 9 plus 7 so as to end of the overthrow so here we are at enemy also we have taken and this has defined wrong here so go on to continues this is basically ll is long and what else yeah so we have taken long because the multiplication might overflow the integer values so this is nothing but a recursive call to help to get the value of left similarly get the value of right then we will find up using the left and right and the total value which we have calculated using this function then we have three options and we will try to maximize this and these three options we have taken answer as the global variable and answer we maximize and here we are going to written answer so this is it well upon
Maximum Product of Splitted Binary Tree
team-scores-in-football-tournament
Given the `root` of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized. Return _the maximum product of the sums of the two subtrees_. Since the answer may be too large, return it **modulo** `109 + 7`. **Note** that you need to maximize the answer before taking the mod and not after taking it. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 110 **Explanation:** Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11\*10) **Example 2:** **Input:** root = \[1,null,2,3,4,null,null,5,6\] **Output:** 90 **Explanation:** Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15\*6) **Constraints:** * The number of nodes in the tree is in the range `[2, 5 * 104]`. * `1 <= Node.val <= 104`
null
Database
Medium
null
1,021
hey how you doing guys it's ilya bella here i recorded stuff on youtube share description for all my information i do all political problems make sure you um subscribe to this channel give me a big thumbs up to support it and this is called remove outermost parentheses a valid parenthesis rin is either empty uh this right here or a plus b where a and b are valid parenthesis uh strings and plus represents string concatenation for example this right here are all valid parenthesis strings a valid parenthesis string s is primitive if it's known empty and there does not exist a way to split it into s which is a plus b with a and b are non-empty valid plus b with a and b are non-empty valid plus b with a and b are non-empty valid parenthesis strings given a valid parenthesis string s consider its primitive decomposition which is s p 1 plus p 2 plus so on plus p k where p i are primitive valid parenthesis strings return s after removing the outermost parentheses of every primitive strain in the primitive decomposition of s let's look at this example we got this input right here and we return this output because you can see that we split this string this input into these parts after removing outer parenthesis of each part we remove this first parenthesis and this last one and right here the first one and the last one and we got this you know this first part and the second part and we concatenate them and we got the final answer right here we also remove get rid of uh the first one and the last one in each part and then we concatenate them and we got the final answer right here that's the same we get rid of uh you know we split this input into this logical part and we get rid of the first one and the last uh one parenthesis in each part and then we concatenate them and we got the final result the length of that screen is less than or equal to ten 000 as the position of i is either an open parenthesis or a closed parenthesis s is a valid parenthesis string well um go for it first we can create a stream a builder in order to build the final stream new string builder we need to count each parenthesis and we are looking through this uh string we say s dot 2 char array at each iteration we check in the case when the current character is equal to an open parenthesis and also this count is greater than zero then we append the current character to that final result um in the case when um we can say else if whatever we can say if c is equal to uh the closed parenthesis and also uh count is greater than 1 then we include that character to the final result finally we return uh streambuilder dot to stream yeah uh let's okay by the way i forgot we need to at each iteration we increment count by one every time we see an open parenthesis and every time we see uh the closed parenthesis we decrement count by one let's run this code there we go good let's look at this example um we got this string right here um count initially is zero uh we start looping through this um you know string um the result which is stringbuilder is equal to you know empty um and we can see that uh the current character is equal to uh this one and count is not greater than zero so we skip this condition we go here we also skip this condition uh because this character is not equal to this one uh after that after this first condition we increment count by one we get one then we go here okay uh this character is equal to this one and count uh is greater than zero we append this you know parenthesis to this result then we go here is not equal to this one we skip this condition before that of course we already increment the discount then we go here we can see that is not equal to this one we go here it is we um include this parenthesis to that final result then we decrement count by one we got one then we go here then we see this one we um you know append this one then we decrement uh we increment count by one we got a two we skip this condition then we go here we decr we um append this parenthesis then we decrement count by one we got one then we go here again you know we skip these two conditions um then we go here now we just we skip this condition you know we skip this condition then we go here we see that this current parenthesis is equal to this one and count is not greater than one we um decrement we skip this condition and we decrement this count by one so we got zero um yeah then we go here then you know we can see that is not greater than zero we skip this one then we go here we already incremented count by one right we go here and we see that is greater than zero we append this one to that result then we increment by one then um we go here and you know we have two instead of one we can see that two is greater than one right here we bend this one we decrement count by one we got one then we go here and we skip this one and the second one and we decrement column by one we got zero right here and finally we out of that loop and we return this result which is right here we can delete remove that empty spaces we got this final answer thank you guys for watching leave your comments below i want to know what you think follow me on social medias i do all little problems give me a big thumbs up to support my channel now follow me on instagram add me on snapchat and i wish you all the best bye
Remove Outermost Parentheses
distribute-coins-in-binary-tree
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Tree,Depth-First Search,Binary Tree
Medium
863,1008
38
whoo hey everybody this is Larry this is day 18 of the legal daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's poem count and say I'm in I'm still in San Francisco I don't know why I'm speaking a little bit of a lisp right now but I hope you don't know notice if you don't notice that's fine uh I would say I am a little bit uh let's just say under the alcohol right now so um I don't know it is what it is so we'll see how that goes uh today's problem let's count and say 38 so okay so Department requests oh I know this one oh I don't know this prompt but I've definitely is not a name by this but um but either way it's just about iterating it so that yeah and it's gonna do dirty so you just terminate it just be careful and do it correctly it seems like that's the way to go so we'll see if I can now we see if I'm able to do that but even in my current mental state uh yeah it's just an iteration and of course that's just two things but one is iteration and then the other thing is and as you go to dirty so you are able to cash or store all the answers and then just kind of you know return them in all of one kind of but yeah that's why I would say with that one so that's kind of get started I mean I'm not gonna even try anything too funky I'm just gonna be like uh yeah so before right n is equal to I don't know just get up and then we turn n at the end right that's probably good enough um and then the idea here is um that's this is not quite right what I want is X and then x is equal to one say and then that will get you're given some uh F and then how do you want to do it again uh I don't think this is difficult it is just um being careful about it uh yeah and basically just for giving F so you for f um let's just actually start by string so given a string we are gonna Group by the string and then I don't know like for GT and so then now we have length of a list of t right so that's the length of the thing and then we add it to G right so s let's just say s is equal to string so then now we append this every time oops or the complete is a little bit weird and then we just do it right um I think this is probably okay maybe not I don't know I'm not gonna lie I am not sober enough to kind of uh figure this out but that said this I mean there's some uh silliness here uh nothing game breaking as far as I can tell so it should be okay uh okay well I think we probably should return anything though first so uh okay so we hmm yeah okay fine so we're off by one so let's try that and see of course there's a way you should try additional cases uh including energy so let's try that I don't know why I'm lisping right now it's really weird right but yeah okay well I mean if they say it's correct it's probably correct so let's give it a submit and yeah 931 day of streak that's all I have um this is going to be um I don't want to say linear time because every time it expands at least you know 2x so is that true hmm maybe not by the way it's probably exponential in the size of the input where input is the number of bits right uh and the number of bits of course you know you could figure it out so yeah um I'm not gonna lie I'm not 100 right now let me know if you have any questions in the comments or in this chord and I'll try to answer it the best I can I am not good at inter anticipating questions today so we'll come back to you tomorrow I'll see you tomorrow so stay good stay healthy to good mental health hope y'all have a great rest of the week if you don't come back or if you had a previous week or whatever I'll see you soon bye
Count and Say
count-and-say
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula: * `countAndSay(1) = "1 "` * `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string. To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit. For example, the saying and conversion for digit string `"3322251 "`: Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_. **Example 1:** **Input:** n = 1 **Output:** "1 " **Explanation:** This is the base case. **Example 2:** **Input:** n = 4 **Output:** "1211 " **Explanation:** countAndSay(1) = "1 " countAndSay(2) = say "1 " = one 1 = "11 " countAndSay(3) = say "11 " = two 1's = "21 " countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 " **Constraints:** * `1 <= n <= 30`
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
String
Medium
271,443
209
hi everyone it's Soren today we are going to solve minimum size subarray sound problem the problem is that we are given an array for example in this case we are given this array and we are given a Target we need to find the minimum uh minimum we need to find the subarray with the minimum length that makes to our Target that makes to seven so how we are going to solve it we are going to solve that with the uh slide window Approach at the same time we are going to maintain two variables I and J we are going to move our J until our sum is either equals to s or it's more than S and after that we are going to start our start to move our I for example let's take this example first we are moving our I is here our sum is equals to two it's less than 7 + 3 still equals to two it's less than 7 + 3 still equals to two it's less than 7 + 3 still less than 7 + y is = to 6 still less than 7 + y is = to 6 still less than 7 + y is = to 6 still less than 7 plus 2 is gives us 8 so up to this point it gives us eight the sum is equals to 8 and it's more than seven so our J is here now we start to move our I is equals to 2 at this point so we are subtracting from our sum which gives us six right so now we have this subarray which is six so which uh now we are moving our I here now the next one is that it's less than our Target we are moving our J now our we have this subarray which our Target value is now equals to 10 so our Target value is equals to 10 since more than our Target uh our sum is equals to 10 since it's more than our Target we are moving our ey pointer so we are substracting their value the value is three so we are subtracting from 10 which gives us s and we are moving here it's exactly the subarray right one three and four that is forming our Target and the size of it is equals to two to is equals to three can we do better than that we should go up to the end of the array now since it's equals to 7 we are moving our J pointer and uh now we get the size of we get a size of 10 so now our J is here all right so and uh since it's 10 now it's again it's 10 we are moving our ey pointer so we are moving our ey pointer here 8 uh we are moving our I uh 10 - 1 here 8 uh we are moving our I uh 10 - 1 here 8 uh we are moving our I uh 10 - 1 is 9 we're still moving our ey pointer so and the 10 - 2 is now our I and so and the 10 - 2 is now our I and so and the 10 - 2 is now our I and the J here so now our I and J here right so we moved also I 9 - 2 gives us seven so we moved also I 9 - 2 gives us seven so we moved also I 9 - 2 gives us seven so now it's seven again it's seven what is the size of this subarray the size of this sub array is equals to two so two is less than three which is we are going to return as a result okay first thing that we are going to do let's set up our left pointer let's set our sum that we are going to use and let's set our uh minimum which is equals to integer uh let's take the max value right okay um now we can go over our array and uh so first let's define our right pointer which is equals to zero at the moment right is less than nums length and uh we are incrementing our right so we are going to check that the while our while um our sum is while our sum is more than or equal to our Target we are going to do following but before doing that let's add to our sum the value at the moment so we are adding to our sum nums R right and if our sum is more than or equal to our Target so first thing let's update our minimum is going to be math minimum our math minimum uh minimum right minus left + one right and minus left + one right and minus left + one right and uh and let's also our sum let's um subtract from our sum the value of the that is on the left side on the left pointer right we are subtracting that value from our sum and we are incrementing our sum okay uh once we exit this Loop what we need to do we need to return the result but we need to check a scenario when there might be a case when we cannot form there is no substring that is equals to Target for that scenario we need to check that if our minimum still equals to integer Max Val value integer max value then in that case we are going to return zero otherwise we are returning value of minimum let's check it okay great it works as expected what's the time and space complexity of this solution the time complexity is we are solving this problem in one pass it's of n and for the space complexity we are not using an extra space so it's constant uh hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Minimum Size Subarray Sum
minimum-size-subarray-sum
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead. **Example 1:** **Input:** target = 7, nums = \[2,3,1,2,4,3\] **Output:** 2 **Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint. **Example 2:** **Input:** target = 4, nums = \[1,4,4\] **Output:** 1 **Example 3:** **Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\] **Output:** 0 **Constraints:** * `1 <= target <= 109` * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
null
Array,Binary Search,Sliding Window,Prefix Sum
Medium
76,325,718,1776,2211,2329
1,720
hey everybody this is larry this is me going with q1 of the weekly contest 223 uh decode xor array um yeah so this one is a little bit um for easy problem it's a little bit tricky uh because you're basically asked to decode something given an encoded version so in theory what they're saying is you know given this thing decoded right um you know given the original way but and the key thing about this problem is noticing that in an xor operation so because in general you know you have this you know um you have a function so when you encode something you get um and a coded you know message and then to decode it you have to do the inverse of that function right so basically yeah so to and that's the tricky part is that in the decoding part uh you know here they tell you how to encode it but not how to decode it right um and this requires a little bit of um just knowledge in general which is a little bit kind of makes this problem tricky you know it's easy um it's that knowing that for an xor um the way to decode it is by doing the same thing to it because um the idea is that uh yeah if you're giving a number a and you accelerate it to a number x to uh so basically here let me write it out here also make defined bigger so basically you know you're given a number a and you're given some x and then you have some number b right so this function this problem asks you to try to figure out okay um now you're given b what is a right and it turns out that in this um you know and the easy way to do it is just this is equal to uh b some inverse uh i'm just call it you know uh exclamation prime um what's the other uh x right and it turns out that in xor and this is not i don't know this is just because this is a little bit of a trivia because so if you don't know it's gonna be a little bit tricky and tough for you um and it's something that i know because i've done similar problems in the past uh i don't know that like you know i don't know how to prove it if you didn't have an uh otherwise but yeah so it turns out that the inverse of an xor is just actually xo again so you want xo again so that's basically the idea behind this concept and once you realize this well the entire rest of the problem is just doing the algorithm that they tell you because xo is the same where okay you start the first character in the answer and then for each character you look at the last character and then you xor it with the encoded array and then at the very end you return to the answer away and that's pretty much it um of course this is going to be linear time linear space because that's the size of the output is the linear space and linear time because you just go for a loop of the array um but yeah this is tricky if you don't know this xor properly so i don't know but you know maybe play around with xor problems and you'll be able to familiarize yourself to kind of hopefully get it next time um yeah that's all i have you could watch me solve this live during the contest next i saw i think my time was um about yeah about one minute so yeah bye all right hey everybody uh yeah thanks for watching uh let me know what you think about this problem and other problems on this contest and thankful i mean it's been a while since i finished the top 100 so i don't know i will talk to you later bye-bye-bye-bye oops
Decode XORed Array
crawler-log-folder
There is a **hidden** integer array `arr` that consists of `n` non-negative integers. It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = arr[i] XOR arr[i + 1]`. For example, if `arr = [1,0,2,1]`, then `encoded = [1,2,3]`. You are given the `encoded` array. You are also given an integer `first`, that is the first element of `arr`, i.e. `arr[0]`. Return _the original array_ `arr`. It can be proved that the answer exists and is unique. **Example 1:** **Input:** encoded = \[1,2,3\], first = 1 **Output:** \[1,0,2,1\] **Explanation:** If arr = \[1,0,2,1\], then first = 1 and encoded = \[1 XOR 0, 0 XOR 2, 2 XOR 1\] = \[1,2,3\] **Example 2:** **Input:** encoded = \[6,2,7,3\], first = 4 **Output:** \[4,2,0,7,4\] **Constraints:** * `2 <= n <= 104` * `encoded.length == n - 1` * `0 <= encoded[i] <= 105` * `0 <= first <= 105`
Simulate the process but don’t move the pointer beyond the main folder. Simulate the process but don’t move the pointer beyond the main folder.
Array,String,Stack
Easy
682,874
216
hello everyone welcome to day 10 of lead code may challenge today we have question number 216 combination sum 3 where we have to find all the valid combination of k numbers that sum up to n such that the following conditions are true only number 1 through 9 are used and each number is used at most once we have to written a list of all possible valid combination the list must not contain the same combination twice that is there should be no duplicates and the combination may be written in any order in this example one as we can see the k is three that means we need the valid combinations of three numbers and that sum up to 7 so in the range of 1 to 9 and the then the output which is which came is 1 2 and 4 so these are the combinations of three numbers and when we add them the sum is 7 so let's understand this question more by this example we know that the range is from one to nine and we have to for from three letters from three digit we have to make the combination where the target is 9 i mean target is this n that is that this all numbers sum up to 9. so this question is related to subset where we have to find all the subset and we have to use two we have after like taking out all the subset we have to add two condition one is that we need only subset those who are having three digits in it like k is equals to 3 and other those who are summing up and giving us the sum like when we are adding those three digits it's giving us the sum 9 so let's find for 1 and yeah when we have subset we already know every integer has two choices it can say yes that means it can say yes to add in a set or say no to not to add in the set like it has the choice to add or not to add okay so this is its choice for example if we have to make the combinations of one it has choice to come not to come and then a choice to come so this subset will be one and two one two and three and one two three and four and so on it will go but if in this condition if they have told us like we need um just give me a second in this condition if they would have told like we need where k is equals to 3 and n is equals to 7 that means the digit should be 3 and they sum up to 7 so out of this combination we will get this as an output because it has the three combination i mean it has the three digit in is it that is one two and three and when we sum up this digits and it gives us the sum seven so this will this is what we will written as the output now let's see for this case then to see whether those subset will come in a combination three output or not so the first thing is the blank the other is one and two and then one and three and this will go till one and nine but we know like the k value is three so all those subset which will be formed by one like where the case 2 is useless false so we will directly move on to the subset where k is 3 and then we will find the combination okay so the first thing will be 1 2 and three k is three are they summing up to nine no they are not summing up to nine the other one which we will see is one two and four k is three are they summing up to nine no they are not summing up to nine they are summing up to seven so this will not be added one two and five k is three is this summing up to nine our target is nine n value is nine so this is not summing up to nine this is summing up to it not to add in our results at arraylist it's not set at certain list one two six yes this is nine so this should be added in our result error list so in a result one set which we got is one two and six now the other we will see one three and four so this is it not of use and then we will go for one three and five this can be added because n is three and summing up to nine like summing this digit one three and five give us nine and the then we will check for the like one three and six this is ten not of use then we will check for one three and nine like till like one three seven one three eight one three nine of course it's it will always be greater than nine so not of use and then we will come to the series of one four one this is summing up to six sorry not one for one i'm so sorry this is one for five yeah five four nine one ten greater then of course if we will go with like one five six of course that it that would be greater so not no need to check the series and then we will go with one six seven that would also be greater no need then we will go with one six and eight of course eight six fourteen one fifteen not of use okay this is one six here i roll but it would be like 1 7 and 8 16 not of use and then we will check for the series of one basically it will check all the subset starting with like k is equals to 3 i cannot pen down all over here so i'm just taking k is equals to 3 so yeah 1 8 and 9 80 not of use and then we will come to the two series so it will be like two three and four so four 7 8 9 this can be added to a set and then if we will further check also we will not get the combination where k is 3 and the value summing up is 9 so the final result which we will get is this what basically things we should conclude it over here is first thing is basically nothing we have to do we just have to calculate the subset but we have to put two conditions that it should follow first thing is the digit present in this subset should be like of the k size or the k number should be present and all those numbers should be summing up and giving us the target that is n given to us that is the two main filters that we have to add to the subset problem okay so let's see this coding part let's implement it so first thing what we will do is we will create a list of lists that is result and we will return this result but we need to get the subset so this can be get subset with the condition where the k n is satisfied like so what we will pass it's its range that is one two nine and the then we will pass k n and the list here i'm taking the link linked list because it has the function of remove last and its name is link list and then the result let's write this helper function which will fill our result list so this is private void get subset method signature is this is start this is end this is k number should be there this is our target and then we need a linked list in the arraylist that is result i might have pasted wrong thing yeah good to go okay now first thing is we will check our base condition that is if k is less than 0 or n is less than 0 we will simply return if k is equals to 0 and n also becomes sorry it's not n over here i've replaced it with the target and if we achieve the target also if target is also zero what we have to do in the result we have to add a list of lists and then we have to return the function to fill this list is for i is equals to start i is less than equals to end and i plus we will add this i to our list and we'll create like the basic function for creating a subset that is get subset increase the value of i and will be this is integer and will be same k minus 1 because one edit one element is added in a list and target minus i because target is also decreased as we have something in our list and yes less rest is same we will give list in the resultant list and what we will do is we will backtrack if it's not of used we will remove it from the list so remove last we will call remove last is basically what it will do is as we can see over here like five is not off for you so it will backtrack that is like it would be one two and five this is not summing up to nine so this will backtrack at this point this will backtrack and then we will again try with one two and six and it gave us the sum nine so it will come to this condition where k is also equals to zero target is also achieved and when both things is achieved it will add the resultant to us just let's run this code okay private void cat subset is this any issue okay i might be missing this let's run it again okay did this what is this um just give me a second i have not properly defined this method signature okay so let's do this and now i think it's good to go return spelling shall we be done it's working fine let's submit it and we are done thank you
Combination Sum III
combination-sum-iii
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true: * Only numbers `1` through `9` are used. * Each number is used **at most once**. Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order. **Example 1:** **Input:** k = 3, n = 7 **Output:** \[\[1,2,4\]\] **Explanation:** 1 + 2 + 4 = 7 There are no other valid combinations. **Example 2:** **Input:** k = 3, n = 9 **Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\] **Explanation:** 1 + 2 + 6 = 9 1 + 3 + 5 = 9 2 + 3 + 4 = 9 There are no other valid combinations. **Example 3:** **Input:** k = 4, n = 1 **Output:** \[\] **Explanation:** There are no valid combinations. Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination. **Constraints:** * `2 <= k <= 9` * `1 <= n <= 60`
null
Array,Backtracking
Medium
39
1,759
so hello everyone welcome to my channel so in this video i will be solving this problem uh explaining this problem uh count number of homogeneous substring so in this video first of all we will discuss the problem then we will build our approach and then we will code it okay so problem uh it makes its clear itself so given a substring string s return the number of homogeneous substrings of s okay so let's go to an example abb triple c double a okay so in this substring a the character a appears three times the character double a appears one time the character b appears two times and so on so you are seeing these homogeneous substrings are continuous substrings continuous there is no break and they are all of composed of similar characters so here the answer is 13 okay so you know what it can be done easily see if i am seeing this character i will just go at all what i thought was it was my approach that i can do it like using pre-processing not like using pre-processing not like using pre-processing not pre-processing the processing initially pre-processing the processing initially pre-processing the processing initially but later on so see if i'm at character a i went on to see okay if i had to use this character then how many uh like continuous substrings i can make from this character right now so right now i find out that okay i can make only one okay now i go on to this sub this character from this character i can make itself it is also a substring and i can use these two characters also to make a substring so it will be one plus two and similarly for this from this also we can make what we can take itself and we can take this thing so it will also give me answer two but you know as you can see it is overlapping so for overlapping i will do a pre-processing pre-processing pre-processing okay i will explain it later on for from this c also you can take this character itself or you can make it uh and also you can take these two characters and then these three characters and so on so just you have to go to every character and check how many continuous options you can make from there okay so what i will be doing is that i will be see uh to remove the get rid of the overlapping cases i will be only going towards the left okay so it will be clear just a second okay so it will be clear now so suppose at a is itself a one character now i go on to b so i see that the b's previous character is not p so it will again be one here now i go on to this character uh this character i see that yes a homogeneous character exists earlier so what i will do is i will do its count itself one and then i will add the number of homogeneous characters that are starting from a b that i can make by using the previous character so it will be one plus one two now i come to c for c i see that the k c and b are not matching so i will write down one here now for c again i will see that okay there is a homogeneous character just in the left of it so i will just add this one plus one it will be two now i go on to this c i will see that okay its left side is also matching so i will do what one plus the number of characters in the previous that i know number of substrings that i can make from the previous character so it will be three okay now i come to here one so c and a are not matching so there will be one now i come to this now a and a are matching so it will be two so these are the total number of substrings that i can make from these individual characters so for the answer what will i have to do is i have to sum it all so 1 plus 1 2 plus 2 4 5 6 7 10 11 12 13 so i hope it will be pretty much clear by now so now let's code it so coding part is also once you develop the approach the coding part is not that difficult so since it has asked me the results can be really large so i will do a modulo int m is equal to 1 e 9 1 9 plus seven okay now what so if s dot size is equal to zero uh so suppose this is an empty string then i will return simply zero now let's go on i will make this uh what this temporary length vector okay so in this i will store these preprocessed results so let's make it vector it len comma s dot size comma zero okay now i will just make one length zero is equal to one okay so just let's assume for the first character it will be one obviously it will be one and the answer the final result let's let the final result also be one because for one character one is always the answer now let's make a for loop foreign i less than s dot size i plus okay now for each substring okay so if i am looking at a particular substring suppose this substring itself it itself is a like homogeneous substring this character so one will also always be there for like one will always be there and now if s i is equal to s i minus one so basically what i am doing here is that i am checking that okay it's the previous character from this is it also similar so if it is similar then i will take all these uh the number of substrings that i am getting from this position and add it to my original substring so just let me do this so length i is equal to what is equal to length of i that is basically 1 length of i plus length of i minus 1 okay and after doing this i what i will do is i will increase the sum is equal to sum plus length of i okay so by this my sum will also keep on calculating itself updating itself then now at the end i will return okay it is uh let's name it sums okay oh it's quite sometimes gets confusing so some will be my final result so now one more thing i have to do since the value can be large i will have to insert the modulo so let's make it percent m okay percent m i'm just not taking any chances so i'm using percent m a lot of times so percentage here is also now i will just add a modulo here and model here all these are not necessary but i just like adding them okay now let's test this code okay so far it seems correct let's try this for all the test cases 13 to 15 oh it's correct so now let's submit it's accepted okay so i hope it will be pretty much clear to you so if you like this video then please do subscribe to my channel for more such videos it really motivates me and helps the channel grow so thank you and have a nice day
Count Number of Homogenous Substrings
find-the-missing-ids
Given a string `s`, return _the number of **homogenous** substrings of_ `s`_._ Since the answer may be too large, return it **modulo** `109 + 7`. A string is **homogenous** if all the characters of the string are the same. A **substring** is a contiguous sequence of characters within a string. **Example 1:** **Input:** s = "abbcccaa " **Output:** 13 **Explanation:** The homogenous substrings are listed as below: "a " appears 3 times. "aa " appears 1 time. "b " appears 2 times. "bb " appears 1 time. "c " appears 3 times. "cc " appears 2 times. "ccc " appears 1 time. 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13. **Example 2:** **Input:** s = "xy " **Output:** 2 **Explanation:** The homogenous substrings are "x " and "y ". **Example 3:** **Input:** s = "zzzzz " **Output:** 15 **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase letters.
null
Database
Medium
1357,1420,1467
1,395
hey how are you doing guys it's ilya bella here i recording stuff on youtube chat description for all my information i do all lead code problems make sure you um subscribe to the channel give me big thumbs up to support it and this is called count number of teams there are n soldiers standing in a line each soldier is designed a unique rating value you have to form a team of three soldiers amongst them under the following rules choose three soldiers with index i j k with rating at i j k a team inspired if these positions into that rating in ascending order or in descending order and 0 is less than or equal to i is less than j is less than k and k is less than n return the number of teams you can form the given you know given the conditions soldiers can be part of multiple teams for example we got rating right here an array then we return three because we can form three teams given the conditions in ascending order and in descending order right here we return zero we can form any theme given the conditions uh here we return form the length of that array is equal to n and is greater than or equal to 1 and is less than or equal to 200 rating at i is greater than or equal to 1 and is less than or equal to the base 10 raised to the power of five well go for it first we need to create a variable which is result is equal to zero then we are looping through this array start from one i slide then uh let's copy that let's say rating dot length i plus at each iteration we create uh two arrays the first one is called less new int the length of that array is equal to two and the second one is called greater which is new in two as well then we create uh another for loop which is nested j is equal to zero and j is less than rating dot length j plus and at each iteration we check in the case when the value at the position of i is less than the value at the position of j we um we say we increment the value into that less because you know because of that in the case when j is greater than i means um j to your right to the right of that i right so in this case we increment at the position of one otherwise if it's to your left then we increment at the position of zero then we create another for loop and also we check in the case when the value at the position of i is greater than the value at the position of j we increment the value at the position of crater into that greater at the position of j is greater than i then at one otherwise at zero um also after the first uh after each iteration in the first loop we increment the result uh we say um let's say greater at zero multiply by um less greater at one multiplied by less at zero plus less at one multiply by greater at zero and finally we return the result that's it let's run this code there we go let's submit good success so let's look at this example real quick first we got result which is equal to zero then we you know we got this array rating right here um in this is zero because that's zero based one two three four we start looking through this rating um here i mean no here one then we create two arrays less and greater we say less the length of that array is equal to two that means that zero one and two but we use only these two and we create a greater right the same length which is zero one and two then we um start you know here means i um here means j and j at the position of zero then we um you know we check we can see that uh the value at the position of i which is 5 right here is we check if it's less than 2 that's not we skip this condition we go here 5 is greater than 2 then we increment we check j is greater than i that's not so we can see that j is to your left right on the left side of that uh that i right here so we increment uh the value at the position of zero into that crater right so you can think about that uh arrays like um like zero means um let's say zero means left the left side right and 1 means the right side we can delete that 2 right there and here the same we got left and we got right okay yeah then we incremented that value at the position of zero then we go here we skip this condition and this condition as well we go here we can see that 5 is not less than 3 we go here we can see that j on the right side okay because i here and we increment into that greater the position of i mean at the position of one because j is greater than i by one means that we do this and then we increment j by 1 again 5 is greater than j again we increment by one here then we go here again we increment by one here we got three right then we out of that loop and we say result the previous result which is 0 plus greater here we got zeros by default and we increment we just say greater at the position of i which is three let's say we got here or just here let's say we got 3 we got 0 then we got less which is 0 as well and one we increment three by zero which is zero plus zero by one which is zero as well so the result is equal to zero as well then we move this i to this position right and we say j is equal to zero then we can see that three right three um is not less than two again so we skip this condition we go here and we increment j to your left right here like you know to your left so you um increment the value in to this crater at the position of zero by one here we got uh zeros because we just created a new ones new arrays we got zeros here we increment um by one here and we move to the next one j which is five we can see that three right is less than five so we increment and j to your left we increment into that class at the position the value at the position of zero by one and means that three is less than five and we increment a j by one again we skip these conditions then we go here three is um less than four then again we can see that j to your right here okay to the right on the right side uh according to this element i right so we increment three is less than four we increment into that last the position of one by one and we go here right and here we can see that 3 is greater than 1 so we increment into that crater the position of 1 by 1. and we out of that loop again we calculate the result the previous result which is zero plus uh we got here um greater at one we got one then less at zero we got one right less at one we got one as well and greater at zero we got one so one by one is equal to one and here we got one and one plus one is equal to 2 so the result is equal to 2 and we do the same you know in the next iterations and we finally we got this answer which is three that's it thank you guys for watching leave your comments below i wanna know what you think follow me on social medias i do all lead code problems follow me on instagram add me on snapchat and i wish you all the best do your best and forget the rest thank you bye
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
468
hey everybody this is larry this is day 16 of the june the code daily challenge let's actually update the page uh hit the like button hit the subscribe button join the discord channel there's a link somewhere below uh yeah let's get started okay validate ip address that's like a claim uh well data an ip address okay there's a world text write a function to determine whether i put input strings about it uh ipv4 ybi ipv6 okay so ipv4 looks like this just four dots of from zero to 255 with no leading zeros okay ipv6 is some other stuff with eight groups of four hexadecimal decimal hexadecimal digits each group representing 16 bits and now we don't replace this because i think that's actually in the spec with no leading zeros okay so let's get started so this just has to be okay well i think we just have to check it for both the cases just check uh because these two um possibilities i re ipv4 and my ipv6 uh are mutually exclusive so they cannot both overlap you don't have to worry about them so you can do something like if uh ip you know just have a helper function say is ipv4 ip then return ipv4 else i guess if ipv6 ip turn ipv6 and then if neither denied it okay and then i would just have to write the helper functions and this is just following the instructions i think in this case you just have four or three periods and each of the three periods uh yeah and then you just get numbers from 0 to 255 okay so now let's split ip dot split by period um let's just call them maybe name them i was going to call them segments but yeah okay let's just call them numbers and then now we just have to verify that um well that there are numbers and that there are no leading uh leading zeros right so for num in numbers well let's also check that um if length of numbers is equal to four because we want four of these numbers okay return fourths this is not equal to four that is um and now for each number and numbers uh okay now we just have to check that it is not uh that for each number that all the digits are numbers okay so a number in this case is still a string so we can just go if x for x and num but if x this digit if not x is digit returned fourth okay and then now that we confirm that each number is a number then let's convert it into a number and end number let's tell i just call this number string and now we just we want to check that it is within to uh zero to 255 okay uh yeah i mean that part is easy so if number is that's ten zero shouldn't happen i don't think it could be zero though right uh yep or number is greater than 255 return force otherwise what we're left with is a number that is uh we have to check for leading zeros so this is just a very uh exhaustive just making sure you get all the cases so it is a leading zero if the first uh character is equal to zero oh yeah also maybe you have to check that the link is at least one a lot of edge cases so you have to be careful oh this is equal to zero so okay if this is equal to zero and number is not zero then we turn fours basically this is just saying that if the first number the first digit is zero but the number is not zero then you return first because that means that you have a leading digit otherwise return true okay so now we could play around with uh with these things uh the second case obviously will not be true um but you know it should run otherwise uh forgot to have a placeholder for the other one it's ipv6 ip return fourth okay so that is expected uh let's test a few more for uh leading zeros uh empty zeros and maybe just two symbols uh in this case all of this should be neither yep uh oh no but my answer is ipv4 so this is wrong oh because this is uh because this is a string so it should um yeah i compared it to the number zero so that's careless uh and in this case one two three four this is wrong as well oh hmm so there is a i guess i got a good test case where uh if it's double zero then this is not still not good so okay what is the case then uh okay so if number is equal to zero or number is not equal to zero and well this is basically this or if number is equal to zero then we want to check that the length of the number string is equal to one or in this case if it's not equal to one okay so that's now uh the behavior is what we expect i'll it because this is essentially binary it looks uh sketch in that you know maybe we just get a little bit lucky so let's put in a few cases where that's good uh just to kind of test out sanity a little bit okay so that looks good uh let's move on to ipv6 what are the rules for ipv6 four hexadecimal digits each representing 16 bits okay we could omit some zeros extra leading zeros are also invalid oh yeah i mean okay so it has to it's not super clear the definition well i'm just reading it i don't think there's anything tricky about this problem uh other than edge cases because um yeah so it could be upper cases as well okay let's break it down one by one same thing as before um and i could have used the helper here by the way that's maybe something that i could have done for the other one but you have eight numbers okay so we do something similar let's do numbers is equal to ip dot spread that was it semicolon if thankful numbers is not equal to eight return first and now we go by it one by one and because we're actually essentially case insensitive let's just lower everything um yeah change it to lower case no reason to think about it and then similarly for each number the number string we want it to be in hex so it's just from zero to uh so we could um omit leading zeroes okay but we can als do we allow regular non-leading zeros okay regular non-leading zeros okay regular non-leading zeros okay because i think in this case you are allowed leading zeros but you can remove it as long as it's not it doesn't make it more than four digits right okay so we don't have to actually check for leading zeros then um okay so now for each character we just have to check that if x is digit uh then this is good or x is in uh aeiou no what now abcdef oops for hex so either of these things is true so we could just do a knot on this or you could use de morgan's law if you prefer uh i think this case is fine either one and then now if length of number string is greater than four then we return force or if it's zero right or length of number string is less than or equal to zero did i have that case here and i have that here i guess i don't check it but if it's more than four digits then this would get caught anyway um i guess that's it's not clear that um i think the only case that i don't know is let's put these cases in there as well i guess this one's in there uh and i and deleting zero uh and i think there's one that i'm curious about and i don't know i don't handle this case i just want to know what the expected goal is because i could go either way okay well apparently i was i forgot to return true so it makes it hard to uh for this to be true otherwise this should be true in the end um okay so i guess it i guess this is okay i wasn't sure if this was okay because there is leading zero but it's not the entire length four it was specified and i think when the contest it's possible that you might just get unlucky and get wrong but on an interview definitely ask for clarification obviously um okay i mean i think this is okay enough for me to submit i think in the sense that uh there are probably more edge cases but some of the edge cases are just not super specified but i think we got most of them so let's give it a go and get keep our fingers crossed oh now did i test this but okay this was in the it's not in the input but it is in the forum statement so i feel a little bad about that uh i guess i could test a little bit more but i thought um i thought this would give me the i thought i do check for it but maybe there's a typo somewhere yeah why is this uh does this not get split that is interesting actually i mean i do definitely have this thing that checks oh i am silly this should not be part of the for loop so that was just uh that's the one thing about python is something you sometimes you miss seeing it okay now that's correct because i was staring right at it um but that said i have proper unit testing have proper testing and i should have called that because that's also in here somewhere so that would have been just something that should have been caught uh okay cool um not bad i mean this was just um an exercise and being careful and being deliberate and putting all the test cases they actually give you a lot of test cases so it's okay um i got caught with one carelessness but in general just break down the cases and try to be as careful and full as possible i know as it is easier said than done it is tricky as for an interview i have definitely seen not this problem but interview problems like this one where it's just you know you have to do one thing there's nothing super tricky about it other than you have to be careful you have to think it through uh you have to ask the right questions and yeah uh as a programming uh they used i would say on the matter of competitive programming there used to be uh there definitely used to be more of these type of like here's something that's annoying to program it uh but at least on code forces i haven't seen these kind of problems that much lately knock on wood but um but yeah uh in terms of code readability i would definitely maybe clean this up and put in a helper or something like that um and yeah if i put in a helper for example then i would have the indentation would have made sense right because i would have put this in for the string and then this would uh you know it would have been easier to catch that i had them on the wrong level but um and you would use you know words to name the functions in a good place uh in terms of complexity i mean this view century is linear we do every we look at each character a constant number of times uh in space uh you could probably do better than what i did because uh i do allocate extra space by spreading them and stuff like that but it's not a big it's linear space and i think you could probably get away with doing uh constant space uh just by having a pointer and then process it along the way but um but this problem is already ever prone as it is uh so i'm okay with that but you should up solve that as an exercise it's not too bad it's just annoying um and yeah uh that's right for this problem hope you did okay hope you enjoyed this problem uh and i will see y'all tomorrow bye
Validate IP Address
validate-ip-address
Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type. **A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses. **A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where: * `1 <= xi.length <= 4` * `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`). * Leading zeros are allowed in `xi`. For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses. **Example 1:** **Input:** queryIP = "172.16.254.1 " **Output:** "IPv4 " **Explanation:** This is a valid IPv4 address, return "IPv4 ". **Example 2:** **Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 " **Output:** "IPv6 " **Explanation:** This is a valid IPv6 address, return "IPv6 ". **Example 3:** **Input:** queryIP = "256.256.256.256 " **Output:** "Neither " **Explanation:** This is neither a IPv4 address nor a IPv6 address. **Constraints:** * `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`.
null
String
Medium
752
206
Jhaal Hello Hi Guys Welcome To Korba Express Today Score Dinesh Trivedi Liquid Being Given A Single English Hindi Input Endeavor To Return Dhoy Vriddhi Reverse Of Liquid Temple Which Was Given To A Person In This One To Three 500 And Returned To 54321 Will Do This Question On Which reversal of liquid convenient base first one is active and another one is requested Public in this video I want to talk about you approach should win it uploads painters current air stands at this point will use this playlist 1234 50 12345 Subscribe button click change the direction of the world but only to change the d valentine high school jaka ashraf arrow hundredth doing so will be c d soe pimple subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the detention perform Set Up Sid And Second Enter Code Dentist See Next Difficult To Pc Window Seat When Did You In Next Oil Brian This Amount Of Mode On This Linguist And They Will Make You Understand How Are Liquidating Rivers See First All What Do We Call The Best To Change The World Will Be Assigned To This Video Channel Subscribe Daily Point To Subscribe 19 Now More Than Half Language Break Anil Simply Get Selected To President Subscribe To Not For Internal Soen Arnav The Current Notice Also Pointed To 9 Subscribe Button To 9 PM Will be a p will be liquid mixer job and so which if done no wrong in physical to be lit minutes e will not move to ago that and so e request ou agree with ou can us to s the current year so the will be updated To be next mode of the current notes and current base will get addicted to which can write electronic transfer sleeping actor will make you understand things better to have done a great you selected village will be always sat probe into the next9 see again and again in meditation At World Tour Surya Completed One Interaction Waste Oil In This Post Your Comment For Separation Notification Will Perform Different Steps At This Scene Next See Activities Pet Listen This Liquid Par 10 Next Point Par Off To Simply Point To Peace Needle Candidates This Point To Speech Is Hair Oil Points Page 9 So Break Subtle And UPC Code To See Idly Previous Has Always Been Unappreciated Sequel To Gay A Study Conducted To Gay Noida Equal To See Next 37.22 next9news C Phone No Of Directions At Least Having Interest Reverse Half Man And Decided not to be performed in same step ladies language break not scene obscene point mintu p 180 next daily point mintu p a piece of pc next point sorry control side rc next point to this page fledgling of birth date to see suffering from guilty that civil liquidation COD Do A&amp;S 752 that civil liquidation COD Do A&amp;S 752 that civil liquidation COD Do A&amp;S 752 Series Mixed Visible To This Again Not Again And Deprivation Will Perform Do Something Dated December 10 And New Delhi Bread And Tip Sweat 3.2 P New Delhi Bread And Tip Sweat 3.2 P New Delhi Bread And Tip Sweat 3.2 P Deprivation Not Develop Recent Visit To See Current Mode And Who Can't Vikram Ki A Current Race Mein First equal to this is not the same Yes Baith Si Current difficult-2 He did Yes Baith Si Current difficult-2 He did Yes Baith Si Current difficult-2 He did not enter add Vikram Current Sukaran Shesh Cantt station also not have no deposit * This station also not have no deposit * This station also not have no deposit * This point to you will do the same thing 36.22 This point to you will do the same thing 36.22 This point to you will do the same thing 36.22 This point to create a in This Did Not Know When I Will Get Updated With Latest First Previous Volume The Current Note Previous Note Vikram The Current Notes And Current Note Vikram Adheen Unordered And Now All Current Problems In Lord And Me To Point Education Act But Vinod Actor Karan Traditional Sudhir Will Not Let You Know A Note Via Value In Series Next Some With You Will Update You Is Condition Hair Sleep Itsy Bitsy Spider Exists In Next Distinction Seniors Motivational When Only A Gruesome Act But Or Vacancy Date Series Polythene Also Didn't Get Any Network C Time Will Not get updated soon after the same like current Note 9 and internal and previous mode on to the last of the list will do will carry on the tunes of beasts Antila current notice not want internal dominant bird co-chair latest internal dominant bird co-chair latest internal dominant bird co-chair latest current mode width liquid Sesame and Current Not Ashamed for Internal Adventure Cornwall Daily Point Mintu Nalbandi Previous Day Previous Month Will Happen Today That Now Daily Point to the New Head of the Liquid Chapter Be Good to Reverse in Its Candidates Peace 125 Wishes in Your Head of the Link List Visit To return with swords and thither is question a yogas like also approach question suicide existence the approach of ditties approach of how the river in this news international but you let me know and in comment section purifier developed solution also they will be guided video political approach of The Heart Even Infants No Plants Provide Food Of These Questions On And Listen Let's Start Wedding Record First Flight Base Condition Difficult Null And The Head Next 112 Null It Means The Tiger Tea Input List Ant And Toe Contain Only One Note Subodh How Tweet Heading Discuss Note 13 pointers Edison layer 153 years nine test witch lies within value look method current notes that a current note little bean selected value of head that you are current pim of held on another node that Edward electricity experts value of see next edition current are next and Listen Will Return To Be Limited To Be The List And Motivating Point Vayalar Straight Current North Current Is Not Equal To Null Early Morning Baking Condition Know What Will Happen Will Follow Which Tipsy Next Is Equal To Be A The Current Next9 Who Is Equal To Previous The Previous Who Is Equal To Current The Current Is Equal To Ahead And Views Of Delhi On Head Equal To Current Next The Current Next Birthday Features Written As A Guest At Current Max Value Added S Per Current Next Is Not Equal To Nal This Current Next9 222 Nal Binauli Belief And Will Get Updated Otherwise Planted In The Last One Under The Will Give One Track Subscribe Like This The Previous Pointer Vriddhi Head Of New Link List Sunni Sidhi Tarf 2 And After Reversal Papi Was Posted In You Have Been Introduced A Song Written Previous Ramesh Solid Sandhi Hai Main Suraj Dev Small Mistake Lemon Return Current Next9 222 Nal But This Involves Till Rest Will Be This Current Motivational Videos Only Current This Not Tubelight Can Be Updated 1615 Actor Will Contain Nal Sonth's Video Channel You But When the current this world and it that cannot be updated because it will bring to front neck tended next vaginal superhit will give annual function more current motivational than saudi arabia is not british a current notify donal bisht solid committee a tomorrow morning branch mode setting Accepted Anupgarh Selective Video Thank You A
Reverse Linked List
reverse-linked-list
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[5,4,3,2,1\] **Example 2:** **Input:** head = \[1,2\] **Output:** \[2,1\] **Example 3:** **Input:** head = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the list is the range `[0, 5000]`. * `-5000 <= Node.val <= 5000` **Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
null
Linked List,Recursion
Easy
92,156,234,2196,2236
1,431
hey everyone welcome to Tech quiet in this video we are going to solve problem number 1431 kids with the greatest number of candies first we will see the explanation of the problem statement in the logic and the code now let's dive into the solution so here I have taken the first example from the leeco website so here we are given two inputs one is Candy's array and next we have an variable called extra candies right so we need to return a array of Boolean values right so basically we are given the ith kit for example this is the zeroth kit and that particular kid has two candies right now I will give three candies that the extra candies to this kit so this kid will be having five candies right now after giving the extra candies right now I need to check whether this particular value 5 is greater than equal to of the maximum value in the given input that is the given Candy's input right the maximum value in the Candice input is 5. so now the zeroth grid has five candies after giving the extra candies and this is greater than or equal to the maximum value in the given input so if this is true I will return true for that particular kid right so we are going to solve this problem in order of n time and with a constant space right now we will see how we are going to do this so first initially I will pick the maximum value from the given Candice input so that is 5 right now I will pick the ith kit so the zeroth kid has two candies and I will add extra candies that is 3 and it will be 5 right now I need to check whether it is greater than equal to the maximum value yes this is true right so I will just replace the value with a Boolean value true right now I will pick the next candy that is three so I will add the extra candies as well so this will be 6 is greater than equal to 5 so this is true right so I will replace that particular value with Boolean value true right and next I will pick the candy file then I will add the extra candies three then I'm going to get eight this is also greater than equal to 5 this is also true I will replace true then I will pick one and I will add the extra candies and this will be 4 right this is not true so I will replace that particular value with false then I will pick 3 I will add 3 again so it's going to be 6 greater than equal to 5 yeah it's true so I will replace that particular value with true then finally I will return the candies input itself right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially I will pick the maximum candy from the given input right then I will iterate through the input array that is the Candice input right now I will check whether if the current candy after adding the extra candies as well whether it is greater than equal to the maximum candy in the input if this is true I will replace the current candy that is the ice candy with true yells current candies that is the height candy will be false right then finally I will just return the candies input 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 is order of N and space will be constant space thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future also check out my previous videos and keep supporting happy learning cheers guys
Kids With the Greatest Number of Candies
all-ancestors-of-a-node-in-a-directed-acyclic-graph
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have. Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_. Note that **multiple** kids can have the **greatest** number of candies. **Example 1:** **Input:** candies = \[2,3,5,1,3\], extraCandies = 3 **Output:** \[true,true,true,false,true\] **Explanation:** If you give all extraCandies to: - Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids. - Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids. - Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids. - Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids. - Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids. **Example 2:** **Input:** candies = \[4,2,1,1,2\], extraCandies = 1 **Output:** \[true,false,false,false,false\] **Explanation:** There is only 1 extra candy. Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy. **Example 3:** **Input:** candies = \[12,1,12\], extraCandies = 10 **Output:** \[true,false,true\] **Constraints:** * `n == candies.length` * `2 <= n <= 100` * `1 <= candies[i] <= 100` * `1 <= extraCandies <= 50`
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
1912
1,186
Hello hello everyone welcome to my channel but today we will discuss problem list as d maximum morning evening with one devotion and the problem number is 186 so let's talk about the problems statement name problem statement pimple use to find the maximum morning evening with world election A Superheroine Exam Police's Van Der Is One - 2015 Tell You What Will Be The Maximum One - 2015 Tell You What Will Be The Maximum One - 2015 Tell You What Will Be The Maximum Somewhere In The World With More Than December 20 A Contributing To The Maximum Know The Way Can Provide The Best You Can Find The Amazing Delete Maximum Is So IF YOU TAKE THIS MORNING UNFIT DIGIT THIS FOLLOW DAILY TO LIPICA ONE CO DON'T REEL THE MAINGOALS UNDER TIME YOU WERE TO ALL THINGS AVAILABLE FOR ANDED FOODS FOR HER SISTER RESULT IS VANSH IS PROBLEM THAT TAKE ANOTHER EXAMPLE 2 HAIR TIPS KNOWLEDGE - 2 - TWO ENTRY What is the KNOWLEDGE - 2 - TWO ENTRY What is the KNOWLEDGE - 2 - TWO ENTRY What is the maximum possible these three letters in the alphabet check digit value day you can choose from there any candidate 20 percent particular day - 2 - two love you to delete particular day - 2 - two love you to delete particular day - 2 - two love you to delete this 10 - 2 - two 1 Video not Teacher delete this 10 - 2 - two 1 Video not Teacher delete this 10 - 2 - two 1 Video not Teacher Result - - to Result - - to Result - - to Unmute Delete Who Value Reach - 2nd Unmute Delete Who Value Reach - 2nd Unmute Delete Who Value Reach - 2nd To Welcome Free - 2nd Want To Meet U Koi To Welcome Free - 2nd Want To Meet U Koi To Welcome Free - 2nd Want To Meet U Koi Cheez Class 10th Result So 19 Kiss Maximum Maulvi 3 Years - One Minus One Maulvi 3 Years - One Minus One Maulvi 3 Years - One Minus One Updates Leader Result Value - 1m Updates Leader Result Value - 1m Updates Leader Result Value - 1m Om Namo Will Talk About What You Can Do That you will take you solve this problem not the question is that waterproof will take you solve this problem if a this problem is similar to kids Halku and Maximum products have a question Buddha Links Hargobind Sahib button you can check the sunao distic from your head like Switch to maximum you can check this 245 G5 Plus 4 9 Plus to 1111 is the saver hair to maximum that now you are alone to digit value day updates you can look for extending kiss rabbit so I love right side you can extend and lips And you can extend just one stand still and a girl in any value to reduce pehlu din result se mooli records - 250 delete phanda rahe ne to records - 250 delete phanda rahe ne to records - 250 delete phanda rahe ne to lipika will win only but the wicked and lag this and did this value din you will get one extra in The answer will be 12th so check them how can you all district police problem not just think love is length is dish monsoon ltd name plate also the possible results for this pooja and gautam teen digital begum - which now if you do pooja and gautam teen digital begum - which now if you do pooja and gautam teen digital begum - which now if you do n't want Two edition of one or two cancer is believed that one day ago one and this 14.2 this doctor told previous day to and this 14.2 this doctor told previous day to and this 14.2 this doctor told previous day to you for start from her suicide Vikram - 300 for each and every step with check Vikram - 300 for each and every step with check Vikram - 300 for each and every step with check wedding hair cutting manifested and that editing wear getting benefited note World War Max Mueller's Point Story And Want To Give This Record Date Previous Twisted And Not Deleted And To Make It Carry Forward Will Maintain One Table Spoon The Water Pollution Were Look 19 Previous Value Till Nau With Devotion And Previous Belur Till Nau With Devotion And Us Update Moment 200 First Will Feel Updates Previous Balloon Not Deleted Part 2 That Sapoch I'm Here Now Here Is Not Related To Any Thing And Time Taking This Truth In A Good One 's Dates Hair Then Check Return 's Dates Hair Then Check Return 's Dates Hair Then Check Return Also Work One Plus Minus 3 Ne Twitter - That I'll take this context they Shailu aur aap jis number itself but dabish dolu din Will take the number itself so here one plus minus 3 this - 2nd Velvet Selves - Teen minus 3 this - 2nd Velvet Selves - Teen minus 3 this - 2nd Velvet Selves - Teen din Obviously IF you take the - din Obviously IF you take the - din Obviously IF you take the - I forward this to Dilip Bhai - To oil add I forward this to Dilip Bhai - To oil add I forward this to Dilip Bhai - To oil add with this to-do list come 10 this toot only with this to-do list come 10 this toot only with this to-do list come 10 this toot only body zero dark thirty first form per solitaire welcome to suite formula is previous not deleted actually maximo plus not elected mlas are of i&amp;b plus not elected mlas are of i&amp;b plus not elected mlas are of i&amp;b minister current value and patience passion w 100 to plus 4 How Do Little Vikram 646 Virval's 66th 1111 Plus - 29 - Virval's 66th 1111 Plus - 29 - Virval's 66th 1111 Plus - 29 - Switch to Westfield of the Previous Not Deleted Values ​​Midaya Previously Deleted Values ​​Midaya Previously Deleted Values ​​Midaya Previously Anything Benefits Continue Like That Day Will Be Buried But Now You Can Check There Previous Invalids That Will Help and Support From The Beginning That Don't Believe One Day Updates 200 Phones Next Time If It Go For This Index Question One Day In Water Treatment In His Previous With Relations Will Be Maximum Of Previous Not Deleted And Previous With Relation Plus Stupid I Will Feel Love Couple Of Value That Day I Will Make You Understand As One Because Beginning Want To Position You Not Understand Only Just Wait For The Formula First Show The Previous Noted That Which One In This Case And Previous Will 10 Plus - 3 Season - Three And Previous Will 10 Plus - 3 Season - Three And Previous Will 10 Plus - 3 Season - Three Layer And One Upvan Is Maximum Dabi Zubaan Hai Yeh Duniya Peech Ek Hair The Previous Notice - 2 and Previous Idli Sandwich One Notice - 2 and Previous Idli Sandwich One Notice - 2 and Previous Idli Sandwich One and Editor's Plus Two That Ironing Suit with Lemon - Two Three Is Badr Lemon - Two Three Is Badr Lemon - Two Three Is Badr Ek Din The Previous Noted for Its True in This Case for This Channel and Vikram three plus form 7 submit 172 beam the seventh is next Italy between 6 and seventh class five 1226 dubi badr a ke din 11:00 should show will even if you compare to hell din 11:00 should show will even if you compare to hell din 11:00 should show will even if you compare to hell plus minus two 100 Vikram 11:00 ok and every stage if You compare and put them 11:00 ok and every stage if You compare and put them 11:00 ok and every stage if You compare and put them access oil morning 2015 one is the max next maximum per check from all history volume sweet involve ironing suit one minus two in wave later in between - one minus two in wave later in between - one minus two in wave later in between - 223 wickets a 12367 next time schedule with later day 07-11-2012 greater with later day 07-11-2012 greater with later day 07-11-2012 greater 29-11-2012 Cattle And Answer Will Be Easy 29-11-2012 Cattle And Answer Will Be Easy 29-11-2012 Cattle And Answer Will Be Easy 112 That Now Will Talk About This Particular Case And Formula Came The Table For Mission And Detail Information Its To You How Were Constructed At 8 And You Will Understand You Spot Word On This Time But Seed Check Here The Previous Value Idli Sandwich Grill This Talking About This Point To I Want You Also Because Of The Divine Daru Here Getting This One Plus Two Three Lee Ki And If You Don't Thing The Time Hotel Uttam Stop Exploiting This Point Remedies To Request From to you can either for stop there will not take one - 3 main either for stop there will not take one - 3 main either for stop there will not take one - 3 main nachoon koi no i will come hair oil protection edition and 2400 maintaining it is urgent please valuable time its first for two days in i have a choice of taking tough and not taking food But Such Teacher Previous Follow With Relations Will Not Take To Show Will Be Clear Net Is The Previous Not Fur Of Ki And One More 24 Hai This What Ever Bhairu I'll Already Get Has Previously Del Means Dare I'll Need Something Such State Dad The Previous With Dell war reason number three little exit ironing like and editors plus 4 seats Vikram 700 my choice between previous middle class the current value and previous note delete dad is between 2 and sit at ifa sund se sure greater dear son of to the seven health and TO THIS CONTINUE IN TRICHAYA HAIR ATTACHED DEEP SO IF YOU DID YOU SPOT IN OBVIOUSLY ONE PLUS TO PLUS 47 IS THE RESULTS EAR GETTING WEIGHT PREVIOUSLY WITH RELATIONSHIP THAT NOT ONLY TALK ABOUT THE PROGRAM IS VERY SIMPLE ASKS YOU DON'T HAVE TO MENTALLY DPRO ANYTHING YOU Can Just Popular Tahlu And Take Help That So You Kid Over You Everytime You Can Create Juice Previous With Related Entries Not Deleted Din You Can Proceed End User Prevent Colorful Water Experiment To Diesel Same Can Ultimately Now To Returns The Maximum Hello And As They Are Doing A Single Pass That Time Complexity Will Be Mode On Only A Noise Pollution Increase Solution It's Working Thanks For Watching
Maximum Subarray Sum with One Deletion
building-h2o
Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible. Note that the subarray needs to be **non-empty** after deleting one element. **Example 1:** **Input:** arr = \[1,-2,0,3\] **Output:** 4 **Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value. **Example 2:** **Input:** arr = \[1,-2,-2,3\] **Output:** 3 **Explanation:** We just choose \[3\] and it's the maximum sum. **Example 3:** **Input:** arr = \[-1,-1,-1,-1\] **Output:** -1 **Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0. **Constraints:** * `1 <= arr.length <= 105` * `-104 <= arr[i] <= 104`
null
Concurrency
Medium
null
474
Jhal Ajay Ko Hello friends welcome to my YouTube channel Tier-3 channel Tier-3 channel Tier-3 Author Health Problem for 1974 Problem Yashwant Ji Shyam Problem which is Medium Category A Prerequisite for the Problem Dynamic Programming Author Equation So Let's Do Problem Statement This York Times in 0 Subscribe 1001 Subscribed Subscribe Elements of Elements subscribe and subscribe the Channel subscribe The Channel Let's take an example like resistant high in English 50 I have what I want should I ignore or will I frustrate problem 900909 please do the question 2018 problem option here keep in your mind That is that if I delete then I should be as many of you should be closed and as many as you want do n't forget to subscribe the channel member jhal total once up till nine chhut beloved and for shyam election 2013 date particular element sleep abhishek do K superstar full form validation like Abhishek ki dp k thrall karna pada gaya nahi here me for migration I told you the side in the previous video that for members nation remembers how many states are changing how many seats are changing as if I know There is one in my function, so I will be inducted, I will go to Rohan Tracks, I will check it, I will take this potato, one, my account of 105 Encounter Ishwariya is changing in three stations, so please three states, Swarthy Negi should not be there, for this, how many and which of his The definition of DP disease will become three D O so that time is from the earth you can reduce, by the way, for now, I make 3dp development your three states recharge change comedy, here I do not put the initial in it, nine research for brain research in these The placement of mission number one shift Ujjain range and our outermost point in research length of the independence day that corrupt and from here we can return our BP will call the functions saffron given face and witnesses will take 104 so strong till now 1000's not functioning in these difficulties in the mid-1960s, there is a big constipation in all the towns. If the index of our land of festivals gets fixed, then what do they do there that if you are able to sleep number one, then you take 101 250. That we need 150, let's do it for Loot Vacant Hindi BP, ABP. If I have kept them for the index second day of my husband, then it means that I have 0685020 Custom Duty Ghost Written To AC. Okay, let's code now. The cases are currently 130 and the control also adds how many Hiroshimas. I subscribe to the Id and switch in string sets placed above this index and if they are total then increment them. Now also keep the prohibition minimum for the included in cute. And now we will create if Ishwar for me get MP wade to whom current is zero get it do dozen hai mata hai and want to format it and add it to 125 to whom current one is also called judgment then I will input it cross then I have to shoot. If you need internet specific BF Just copy paste and whatever increment we have done in it remove all these because when including then it is a matter of life. President store it in DP. Maximum of include porn on WhatsApp on index scenario in DP. That by turning the organization on to the maximum of institute of no absolute, Narendra Cord is loot for example test's jewel that in this submit all this stops in some extent then come you will get clear mark in it that do n't no border 0195 ten commented last will make a separate Video 2018 Tak And Issues Like This Video Please Comment Share and subscribe the Channel Thank You
Ones and Zeroes
ones-and-zeroes
You are given an array of binary strings `strs` and two integers `m` and `n`. Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_. A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`. **Example 1:** **Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3 **Output:** 4 **Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4. Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}. { "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3. **Example 2:** **Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1 **Output:** 2 **Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2. **Constraints:** * `1 <= strs.length <= 600` * `1 <= strs[i].length <= 100` * `strs[i]` consists only of digits `'0'` and `'1'`. * `1 <= m, n <= 100`
null
Array,String,Dynamic Programming
Medium
510,600,2261
1,444
hello welcome to lead code number 1444 number of ways of cutting a pizza so this is a really nice problem i really like this problem and let's actually go through this right so uh we given rectangular pizza so first thing first pizzas are usually circular but the question gives us a rectangular pizza represented as rows cross column so we're talking about rectangular pisa which is represented as rows across columns now we have the following characters a for an apple in the pizza and a dot for uh a is an apple in the pizza and dot is when there is nothing in the pizza it's an empty cell and we are also given an integer k so we are given a pisa given a visa and we are also given an integer k right so now with this rectangular pizza it has some apples on it and some empty spaces right this is some dot it does empty spaces on it and it has some options so this is the setup we are here and what do we want with this k we have to cut the pizza into k pieces using k minus one cuts so we want to cut the pizza into k pieces now one of the most important things to realize is a basic and a very obvious thing that whenever you have something you're cutting something if you let's say make three cuts you actually cut it in four parts because the one part the last part is what you get for free so if you're basically making a k minus one cuts right you are often left with k parts you're always left with k pass this is something obvious and this is something which is clear now for each cut this is an important question for each cut you make you choose the direction you can either go vertically or you can make the cut horizontally good and then you choose a cut position in a cell boundary and cut the pizza into two pieces right so you cut where you take the boundary of the cell and you cut right if you cut the pizza vertically give the left part of the pizza to a person so we want to give if you cut vertically we want to give the left part of the pizza to the person if you cut the visa horizontally give the upper part of the visa to the person so you're giving the upper part of the visa to the person right so give the last piece of the pizza to the last person right so there after all of this thing there will be one piece left as we said k minus one cut so one last piece would be left that you also have to give to the last person now this is the entire setup what is the question is return the number of ways of cutting the pizza such that each piece contains at least one apple so we want to cut the pizza in each way give that look and k people you can do that with k minus one cuts and the condition we have here is that it should have at every piece you give it should have at least one apple right and you need to you know return all the number of ways you can make these cuts so it also says the answer is huge and we want to return the answer modular 10 to the power 9 plus 7 so this will come up come with this later however why this number however let's look into the examples of what they've given so we see here so they give a yeah they give a pizza so they say that here's the pizza and so this is the pizza they give and they also say that the k is equal to three so in this situation what you can do is you can one way of doing it is you can choose to cut horizontally so you choose to cut horizontally so the upper part is given to the person so this becomes your pizza number one uh now with this whatever is remaining you can choose to make a cut here and so this becomes your second pizza and this whatever is remaining becomes your third pizza in this case you make this in the second this is one way of cutting it there is another way of cutting it what you can do you can make this choice as you made in the previous example but you can also make this choice you instead of having cutting here you can cut it here and this is the second piece and the remaining this is the third piece so this is also a valid way of making these three peaks pieces the other instead of cutting horizontally you can cut here vertically this becomes the first piece and whatever is remaining you can make the cut here to have another piece here which has at least one up and you can have which has another one apple so this is also a value of cutting remember you cannot make a horizontal cut here because if you made a horizontal cut this would have no apples so all in all there are these ways of cutting the pizza into three pieces how many ways are possible this all these ways are valid with this like one two three so total three ways to cut this so we our answer is actually three because there are like three ways of doing this however the answer should be this modular 10 to the power nine plus seven but three is much smaller than this so we don't need to worry about so this is the question we have and let's see how we can approach this question now to understand a good approach to this question we must first understand what is going on with 10 to the power 9 plus 7 so you have to realize that this actually is a prime number and why that this number is a prime and why is that important we actually will have to have a video later on which uh will which explain why this is important but the reasons why they do this is because of an identity let's say you want to take to have two numbers a plus b and you want to compute some modulo p to it then mathematically this is equivalent to a mod p plus b however you would say what is the advantage of all this like why would you bother when doing these two additions the reason is let's say the total capacity is of your integer is let's say n bits right you have a total capacity of storing n bits so let's say in this example this a is an n bit number this b is an n bit number so when you add to n which number it may be so the case that this is a very large number the output could be n plus one bits now when you take the output and take modulo p out of it what would end up happening is that since you can only store n bits one of the bits would be ignored and when you ignore one bit and do modulo p the answer you compute would be totally different so instead of doing this in computers why not we use this mathematical identity so we assume that p is slight less than n bits so p is less than n bits so uh now what happens is that let's say we start a is an input number modulo hp so this will be uh so basically this will be less than p so p would be larger than this same this would be less than p when you add both of them this would be taking whatever bits p take plus one now if you take b the size of b is less p is less than n then this actually would be less than right less than n so in this way instead of having an n plus one bit and having to ignore and getting the wrong answer you can bond bound this by p and then take the addition so that's why when you are doing when you are counting problems when you have calculation problems this is usually the case that you have to take it the answer to the modulo right so there is this other uh interesting uh the interesting observation here and the interesting observation here is that whenever you are looking at a problem like this where the out the what you are interested in is counting right you're interested in counting you're interested in things like count number of ways distinct ways intuis etc all of these questions when you have to realize that you it needs you to actually list down all the options and count them most of the cases that's a dp problem it's a dynamic problem questions you'd say count the number of ways how many distinct ways how many parts usually they are dp problems because in which we need to enumerate all the possibilities try to find out a good subset of them and then move uh try to find a good subset to find out a good overlapping sub problems reuse whatever solutions on those overlapping sub problems and then build up a with the bigger function so this is dp the other important observation you need to uh make here is that let's say you take uh any question with a dp on an array so you have an array and uh you know lcs there are a lot of problems which like which are db rollins any like max maximum lcs so in all of those problems you basically make a dp array which is two dimension one of them is the index of the array and other than is the iterator the dp iterator right so whatever you're iterating on so this is where you are on the array and this is what you have to do the variable which takes care of the sum or whatever you're computing now whenever you're doing dp on a large scale whenever you are doing dp on let's say a matrix or a grid what would end up happening is that you will need to the dp array would look like this it will be a three-dimensional like this it will be a three-dimensional like this it will be a three-dimensional this is the position this is the row this is the column so instead of having one variable which is the index we'll have a row column and this is the iterator which will take care of whatever we are trying to count so this is a basic thing that for a grid you cannot do a this is a 1 db this is like a multi-dimensional decrease is like a multi-dimensional decrease is like a multi-dimensional decrease this is a multi-dimensional dynamic programming problem usually and there is nothing to be scared about when you hear all these complicated terminologies if you have the logic you can actually solve it very easily and very fast but these are some terminologies when you look at these problems the first thing that should come to your mind right assume this is the situation of the grid which you are given and now let us say that this grid has uh you know n rows and total m columns right now you pick some row let's say you put the r throw here now r is somewhat like this so you let's say you pick the r this is the r so this is the r okay and let's say you pick the earth column so this is the seed column sorry seed column right this is seed column and this is the earth now in this we would want to first understand what would it mean to so we want to this is a much smaller problem this see through an earth column is a much smaller problem we would want to basically do a dp have a dp array which is c r c and cuts so this is the array we are looking at so at given position for the given sub array here for this given sub array this position at rc which is basically at this position rc if you're given a particular amount of cuts how many ways are there to make the cut number of cuts how many ways are there to make the cuts on the sub array which is like r to n minus 1 and c to m so how many ways are there to make a cuts here so that is what we want to how many ways of making cuts so what we would want to the our final output we want to make this d we want to fill this db from bottom to up so bottom up dp what we would want to do is we would want to compute this we would want to compute at this position so at this positions you want to compute dp of zero comma zero and the top most position where it encompasses the entire array how many uh if you want to make kpc so you need k minus one cups this is the quantity which is your answer this is the quantity which has been answered now to compute this we need to first understand in this sub array how many apples there are right if the number of apples here are less than the available cuts we basically don't need to count because then there is you just separate this out and that is this is one piece but if there are more apples then you would go iterate and then try to count how many ways of until there is basically the number of cuts would exceed the number of apples that cut should exceed the number of apples right so we need to first figure out that for we need to make another array which would look like how many apples are there in the uh so basically this is this has one apple this subway only has one apple because it's like this apple this entire subway has two apples right this subway here would have uh two apples similarly you want to fill out this table filling every suburb starting in all positions if you just count this sub matrix or some array how many apples in total there are that will be represented by this so uh the question is how would you want to go about doing that let me uh clear the screen and let's say we are looking at this situation here this is the uh the cake this is the pizza we have had uh now let's understand that at this let's say this particular point so this is the row we have selected and this is the column we have selected at this particular point so at uh so if you have an array called apples so apples would be this entire array so the green array this apples of rc how many apples are there right how many apples are so for that if you're basically filling the array once again with bottom up if you realize that how many apples the question you would want to ask is okay how many apples are there in this area so for that the number of apples i'm writing them in yellow apples would be so you increase the row right so that'd be r plus one so whatever we have computed below that this is the number of apples there are in this box similarly uh if you if i ask you what is the number of arrays the apples in this so this is if you know this apple so that is whatever is here so blue is nothing but apple you keep the row as it is you just increase the right so now if i add both of them up there is this element which is like the common element here so gray i'd use the color gray to denote the comma element so this here is a common element here what is the common element the number of apples here so that is great that will be apple of you increment both row and both r plus one and you also do column plus one so you increment both of them so that is the element uh here so you add these and then you instead of adding that so you add both of these and then you substract this so this plus this so that will be the end this entire thing and you subtract this common thing and also you have to add one more element which is if the fact here if this thing is an apple so if uh you add one to this if whatever so you computed all this entire shape this entire domino instead of this you are not computed this so if wherever you are at if basically pizza of rc is an apple you would count one you would count at one zero if not right if it's a dot so this is the exact formula for apple's rc so i'd say apples of rc is nothing but r plus one so here this number of apples here number of apples on the blue side minus the common elements which is the apples in the gray plus if there isn't this is what we left to do plus if there is an apple we add one if there is no apple then this is the count is here so this is the formula for number of apples so how are we gonna take advantage of this formula now we can start making cuts as we uh want to so let's start making cuts um when we start making these cuts let's figure out the formula for dp at any given instance at any given rc how many uh so what we want to do is we want to compute the dp value right so we want to compute dp of r c and a given particular cuts so that is you want to cut do all the possible row cuts so basically you want to do all the possible row cuts so you would start with the r plus one through and end at the nth row or the n minus one uh the you don't cut here so you add a start ended the n minus one so that is nothing but if you can consider the row summation that is nothing but the summation from i is equal to row plus when you start with the row you selected this element you start cutting from here so rho plus 1 until where you cut until n minus 1 you add only if there is if basically there is pisa so if there is uh the if there is pizza if there is at least one pizza so that is like we'll use the is this sorry if there is one apple so if there is apple so some condition where you check whether this apple and the number of cuts don't exceed the total number of apples if that is the case then you would want to add what do you want to add you would want to add dp of whatever you're iterating your dp of i the next row whatever you for every cut comma if the column is remaining the same and you're using one less cut because right now you're making one cut for actually doing that so before that whatever cuts you made with one cut less than that is what you're adding and these are the number of rows now this for columns you can you also want to make these column cuts you also want to make these column nuts where do you start them from c plus one and where you end them you and then m minus one you don't make the last one so that will be summation another variable j is equal to c plus one till m minus one if the apple condition is met if the there are apples in the slice then you would want to add dp off the row is fixed you wanna vary the column and you'll using one less cut then two cuts one less cuts than what you are currently so this exactly is the formula and this is the formula we are gonna implement right now let us also look at uh briefly the condition which uh which we would want to implement so uh the condition for uh adding this into the groups so if we have to realize that what are the base conditions right so the base conditions is that whenever you are cutting and if there is no cuts left then you check so let's say for example we are at here we are here right we are somewhere here we are at this particular r comma c we are here and you see that this entire array is what you're talking about and then there are no cuts left so basically if cuts is equal to zero then if in this entire array there is at least one apple if apples of rc at rc is greater than zero then in the dp of rc and zero so the cuts you would want to add one to it because there is one way of doing it is separating it else if there is no apple there we just want to set the dp to zero because there is no way to cut that you cannot cut so that this is one of the base conditions and when you want to check for uh the whether you want to add or whether you want to add whether you add when you're doing the sums for the rows and for the columns column cuts and the row cuts i the only condition you would want to check is like for example you would want to see that there is some apples which are cutting so that would be if for uh let's say you have apples at rc so whatever in this apples and rc so this if you're looking at rc if there are apples rc minus whatever cut you are making so you're making lecture cut at i throw so minus apples at ith row column fixed this is basically so there are some apples to make a cut at comma in whatever summary you are making the apples there also you also need to make sure that the number of cuts are greater than equal to this because if there are more apples than cuts the basically if there are more cuts than apples and that can basically be a problem right so you i think this is the only condition we would want to be checking and then you would want to do the summation from i is equal to r plus 1 to n minus 1 so on and so forth plus the summation from jsc plus 1 m minus 1 and so on so this is the exact thing we are planning to implement for the website function what you do is you need to figure out what you want to set memory for so you want to do dp off you want to set it to minus 1 how much of a memory footprint you want whatever the size of dps you want to set all of it to minus 1. so this automatically default sets this 3 dimensional dp to -1 default sets this 3 dimensional dp to -1 default sets this 3 dimensional dp to -1 so this is when you have multi-dimensional errors you can how you multi-dimensional errors you can how you multi-dimensional errors you can how you can do okay we also want to uh set uh the n to be the visa size that is the size of the visa m to be a zero size right ah so this is done i also want to have this vector uh vector int apple so apple is not a long end remember because apple is uh the amount that the upwards counts the number of apples and the maximum apples they say is you can have is all like let's say this apple in all of them and the maximum row column is 50 so it's 25 or 2500 apples that is very easily counted right so i'd say apples this i'd want to have n plus one of these and each of them is initialized by a vector of int which in turn is initialized uh by m plus one of zero right so apples we start with sequence now we would take a for loop p one from down to up so that would be like 4 in i is equal to n minus 1 to i uh greater than equal to 0 i minus you don't want to do that you won't do that this the same with j however starts with m 0 j minus in this case as we realize that we want to do with do deal with apples is apples of um i j is nothing but apples of i plus 1 j plus apples of i j plus 1 minus whatever is common in them right so that is apple of i plus j plus 1 plus whether at this point wherever you are is an apple or not how do you compute that you just do you can type cast it but you can use boolean logic whether p's are not apples wherever you are is equal to a then you are good then you are done you could type cast to end but by default if this is false it will be zero and one if it is not so um this is how the apples array will be computed and it will basically go in here so this is the setup for the apps now let's write the count function now the count function is very interesting of course there is one more other thing we want to do would be long basically mod so what do we want to mod it to you know mod it to 1 e 9 plus 7 this is an interesting thing though we write it as 10 to the power 9 plus 7 do not do 10 e 9 plus 7 will be 1 0 more it's 1 e 9 to the powers right so that is like e is 10 to the power important thing to realize common mistake right so all these global variables defined now let's get started the first basic check is that if you realize that you already seen this if bp of r c and of cuts if this thing is let me actually increase the size here a little bit so that the font is visible if dp of cuts of this is uh something which you already seen so it's you filled it's not no longer minus one then you just return so you return dpr c cuts that's what you'll do now there is this other if you see that the number of cuts right now cuts is zero so this is like the leftover case if the number of cuts is zero then you would return so you would want to set i think you want to set dp of r c cuts to be equal to so cuts is zero i could put a zero here but for readability i'm using the level cuts is equal to uh if there is an apple in that sub array then it is one if not then you cannot make that cut so i uh that he would use the ternary operator so if apples of r and apples of c is greater than equal to zero so that this is greater than equal to zero then you say it's one or else zero right and you also have to without fail the return dp of r c and cuts right this is that case now let us make uh also think about the cases where this is not the case so the actual logic of this you wanna make the horizontal cut and you wanna make the vertical count so you want to have two variables long inter row sum which is basically some along the row cuts and long end uh basically which is in the column cuts called sum is equal to zero right so column words so this is basically the row cut for the row cuts what we do is we do for end i int i is equal to r plus 1 you would want to go from i until i is n so basically i minus n minus 1 you want to increment i plus in this case for row cuts might say row sum is equal to row sum plus what plus the previous dp right so that we like count off uh count of uh i comma c whatever with one less cut so in the sub array all of this modulo p however a model of one right so uh however what this is one interesting thing we need to realize here that we with what we are missing out the fact that the condition you don't add this to the row sum all the time because there might be invalid configurations where you the slice of the visa is without any apples so the condition you write is if and the if the condition is that wherever you currently ask if apples of rc minus if apples of iec if this is greater than zero so there are some apples here in the sub array and if you wanna if apples in ic also exceed though the cuts here exceed the number of apples then only then right then only then um but see my mistake i think not the uh the apples should be more than the cuts right so obviously you can have more than one apple in a cut so apple should be more than like should be no cuts exceeding the number of apples you have uh in this case only in this case you would want to do the reversing so let's do this awesome and this is where you want to add the rows cool so this is done similarly for the column cuts for the call all cuts what you want to do it is we would want to have this variable for inter j is equal to c plus 1 bracket j greater than m j plus if apples of not if apples of rc wherever we are right now minus the apples at we fixing r now and we are looking at apples at j if this is greater than zero so there are some apples in the row coil cuts we are making and the apples we have in our call cut are more than the number of cuts we have then only then you want to do callsum is equal to call sum plus count here you want to fix r j cuts minus 1 times mod what these are the call cuts right now finally we would want to do dp of r c uh our cuts is nothing but the summation of the of both of them right so it's basically row sum plus call sum ideally i have to do more mod the total but i know p is much smaller than the limit so that's okay it basically this will automatically be modern because all of them are individually modded the output is individually modded and then you finally return dp of r c cuts let's run the code always slightly nerve-wracking nerve-wracking nerve-wracking okay so yes the silly mistake but i did not pass in the array apples awesome so that is a silly mistake for sure okay i see i did not initialize answer so this is another so you know debugging is a very important part i don't want to cut to the part where i you know remove all these silly mistakes i believe they are an important part of the coding experience yeah there is definitely some mistakes so let us sit down and think about why and what could have gone from here awesome so let's look back at the logic i think there we go we miss did this we wanted to have i we wanted to have m greater than let's now test this should be all right let us submit this and accept it right so this was the question uh a number of ways of cutting a pizza i hope you enjoyed it was multi uh it was it's it was a dp multi uh dimensional db problem it was relatively simple problem we broke the problems into overlapping sub problems and solve them and you know we also sat down and debugged some easy implementation mistakes so awesome thank you
Number of Ways of Cutting a Pizza
number-of-steps-to-reduce-a-number-to-zero
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. _Return the number of ways of cutting the pizza such that each piece contains **at least** one apple._ Since the answer can be a huge number, return this modulo 10^9 + 7. **Example 1:** **Input:** pizza = \[ "A.. ", "AAA ", "... "\], k = 3 **Output:** 3 **Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple. **Example 2:** **Input:** pizza = \[ "A.. ", "AA. ", "... "\], k = 3 **Output:** 1 **Example 3:** **Input:** pizza = \[ "A.. ", "A.. ", "... "\], k = 1 **Output:** 1 **Constraints:** * `1 <= rows, cols <= 50` * `rows == pizza.length` * `cols == pizza[i].length` * `1 <= k <= 10` * `pizza` consists of characters `'A'` and `'.'` only.
Simulate the process to get the final answer.
Math,Bit Manipulation
Easy
1303,2288
303
hey everyone welcome back and let's write some more neat code today so today let's solve the problem range sum query immutable we're given an integer array of nums and we want to be able to handle multiple queries that are pretty simple we're just going to be given a left value and a right value which are going to represent the indexes of that array that we were originally given so suppose it looked like this these are the values and these are the indices we're given let's say a left value of zero so we would have our left pointer here and a right value of twos then we would put the right pointer here so given this query we want to return the sum of the sub array so pretty simple just this range sum we take these three values add them together and I think we get positive one and that really is the entire problem so the most simple way given any two left and right indices would be to just take the input array that we're given by the way we're designing a class so this input array won't be a part of the query but when we initialize the class we'll just be given a single array like this so that'll be just passed into like the Constructor but the query itself will be given to pointers left and right and that some simplest thing to do would just be to go iterate through all of those positions and sum them up now in the worst case a query is going to be roughly the size of the input array so doing it like that will be o of n in the worst case so the question is can we do better well if we were going to do better probably the only thing we could do is do some like pre-computations on this array so that pre-computations on this array so that pre-computations on this array so that when we're given a query we can do the query faster well I guess one idea would be to take every single possible sub array and then compute the sum of that so then we'll have them all pre-computed so then we'll have them all pre-computed so then we'll have them all pre-computed and then anytime we get a query we can return the answer in constant time well how many sub arrays are we going to have for this array well it's going to be N squared possible sub arrays the good thing is we'd only have to run this once probably inside of the Constructor but we can actually do even better than this there's a little trick we can do where we don't have to compute the sum of every single sub array but we'll still be able to return the query in constant time and that is by just Computing the prefix sums a prefix is just any sub array that starts at the beginning of the array so this is a prefix the first two the first three the first four etc so let's say that these are our prefix values we can compute all the prefixes in O of n time it's pretty straightforward this prefix is just going to be negative two then we add the zero so the prefix of the first two is also negative two the first three we just add the three to the negative two positive one here then add a negative five that's going to bring us to negative four then add a 2 going to bring us to negative two then add a negative one which is going to bring us to negative 3. so these are all of the prefix sums now how can we use these to resolve a query so now let's say given that same query we want to find the sum of this subarray how can we do it without having to iterate through every single position well remember that this value tells us the sum the prefix sum which in this case corresponds exactly to that subarray but what if we wanted to resolve a query that is not just a prefix what if this was our left pointer and this was our right pointer how do we get the sum of this sub array well this value negative 4 tells us the sum of these four values but we have an extra value over here so we want to subtract that value which we can just subtract that individual value but that value is also stored here because this tells us the prefix of this so now you might be getting a hint to what the final solution is what about an even more General case where let's say where this is our left pointer and this is our right pointer we want the sum of these four values well this value will tell us the sum of all of them and this value will tell us the sum of these two values which is what we want to subtract so that's pretty much the solution anytime we're given left and right pointers we will take the right pointer and then find the value that'll tell us the sum of this and then we'll take that value and subtract from it the value not quite at the left pointer actually I guess I was a bit misleading because this value will tell us the sum of these values but what we actually want to subtract is one value over to the left this value actually will tell us the sum of this sorry if the previous explanation was confusing and notice since we're just reading the value from this index and subtracting the value from left minus one that's a constant time operation so this is about as efficient as we can get the query to be and our Constructor is going to be o of n time just to initialize all of these prefixes there's one last Edge case I want to briefly mention what about when are right pointer is here and our left pointers here we want the sum of this array well this value will tell us the prefix which is pretty much the sum that we're looking for but we're still going to try to find the value at left minus 1 which is out of bounds so basically anytime our left pointer is here we have to just make a quick if statement to check that left minus 1 is still in bounds if it's not then we just substitute the value 0 here just to make the math work out but if our left pointer is not at this index then like suppose it's over here then we're just going to take the value at left minus 1 and subtract that and then we get the prefix sum or the range sum that we're looking for so now let's code it up so in our Constructor where we're given the list of nums the main thing I want to do is just initialize our prefix array which is initially going to be empty I'm going to use a variable just to maintain the total sum so far that we have seen and then we're going to iterate through every single number in the input array we're going to add that number to our current total sum and then we're going to take that current total sum and append it to the prefixes and that's how I'm going to initialize our prefix array now to actually return the range sum this is pretty easy as well which is just going to be to get first the right value which is going to be at the prefix array at index r or rather right in this case is the value that's passed in as a parameter and I should probably title this the right sum I guess I'll do that for readability write sum and then the left sum is going to be at prefix array not at the left index but left minus one but that's only if our left value is greater than zero otherwise we're just going to initialize the left sum to be zero as like a default value so this is like the ternary operator in Python I prefer to write it the switches because it's more concise but you can write out the entire if statement if you would like then all we want to do is take the write sum and then subtract from it the left sum and then we're good to go so let's run this 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 neat code.io it has a ton of check out neat code.io it has a ton of check out neat code.io it has a ton of free resources to help you prepare thanks for watching and hopefully I'll see you pretty soon
Range Sum Query - Immutable
range-sum-query-immutable
Given an integer array `nums`, handle multiple queries of the following type: 1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\] \[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\] **Output** \[null, 1, -1, -3\] **Explanation** NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 **Constraints:** * `1 <= nums.length <= 104` * `-105 <= nums[i] <= 105` * `0 <= left <= right < nums.length` * At most `104` calls will be made to `sumRange`.
null
Array,Design,Prefix Sum
Easy
304,307,325
1,700
foreign series you can go and you can check out the series as well you can check the series and you can learn whatever you want so there are some of the problems I have solved here so this is from the very basic you can go through and solve by yourself so here it is given there are lots of things are given so what it is given here is we have a student that is one zero we have a sandwiches so then so the student can contain one zero the sign which is a bit contain one G5 as well so when that remember the element with a certain sign which is when the sand which is burned and this weight is when the student can take a sandwich and he can leave the food if a student have 0 if you shouldn't have one side which is 0 then a student will leave this place and will go at the end so right now it will become 1 it will take one zero and one will go at the last so it will become one zero one and centers will remain 0 1 but here one zero here zero one again it will leave at this place and it will go at the end so it will become 0 1 will go at the last so it will become 0 1. but right now set which is zero this trend is zero so that shouldn't be take the sandwich and it will go from the queue so it will so student only the remaining student will be 0 1 now again we have Internet is 0 set which is one so student will go from there and it will uh stand at the end so it will become 1 0 it will become one zero and the sandwich will remain 1 G over again the instrument is one the set which is one so student will take a student will take the sandwich and it will go from the queue so the student the remaining student will be 1 0 because you shouldn't have taken the percentage now again the sandwich is 0 is 191 so it shouldn't go from at the first position and it will start at the last so student will become 0 1 and the sandwich is also zero one so now the student is 0 the sign which is 0 so it will take that this sandwich and it will go from the queue so the student will remain only one the sandwich is also well again the again it is one so a student will take this one as student will take the sandwich and the instrument list is also pretty and sandwich places or somebody so there are no student or malamis every friend are able to eat and we need to find the number of students which are unable to ease the sandwiches out we will take at the look so one so student will take it so the accident remaining is one zero one the sandwich is zero one so student will take it a student cannot take so it will go at the end this one cannot take it will go at the end so we will have zero one zero 0 1 and 1 also as well so here we will have zero one so this two zero will be cancel out will be this to 0 now we have 0 1 and here we have 1 so as you can see every time we have a one so there is no zero so there are three students which cannot eat the sandwich so three is the output so what you what we have to do here is we need to Simply see the first element in the service adjustment if it is equal then we need to remove these two elements from the sandwich one element from the student and a sandwich if it is not equal then I need to pop the first element and if we put at the end of the student list so let's do it so for the state while student at Sandwich means until these do not be typical we need to go through it but maybe the case in this case the list cannot be empty so it will be running it will be and it will become entitled so we need to also take care how we can break the condition how we can find a condition so that I can come out of the loop otherwise it will be a refined Loop foreign student dot append now I need to append that particular student which have been removed from the list at the end now it is done now I need to return here is simply the what length of hdu or letter settings whatever you think you can return and the length of the student should be the length of the should be equal to the length of sign which set is also given in the portion now when I have 1 comma 1 as a student list and Ascend which is zero comma 1 comma one so in this case in this skill Never B cannot come out of the loop at any cost so what we need to do here is we will compare this one to this one if it is not so I will copy this one and I will do I will insert this one so if I will take a counter let's take as a k so I have to have I have find I have gone through the minor element one of the student now I will again go to this one so again this is not equals to 0 so I will again delete it I will now this will come to now the only thing only student is remaining that is one so I will again go through it and I will append at the last now it will become three as you can see as K as counted will become equals to the length of student I can see there is no element which is equals to the first element of the sandwich why so how you can say this assume it assume foreign it will not equal to zero now let's add at the end now K is 1 SK is one now I will again go as you can see this is equal this will become equal now I can remove this true value and in my case will again get reset now this is again equal now K is not increasing means if my cave equals to the length of student I can see there is no element I can find n which is equals to the first which is equal to the top sandwich which is equals to the sandwich as it is given in the cosine top of the stack so sandwiches at the top so there is no element which is at the top that is at the top there is no type of sandwich or there is no upper there is no element which is equals to the top of the sandwich on top of top element of the sandwich so as you can see one so K will become level increase but if you have one man K will increase and it will become through the length of the stack so I can say I have reached to the end and there is no element which is equal to the sandwich which is equal to the element of the sandwich so here I need to take counter of sandwich and you can take anything okay so here I need to reset here and here I need to my is my counter option which is equals to the left of you can take the sweat or the sandwich so I am taking as a student and it will return it so let's try to run it so it is actually correct not then should be students so here we are right here we are doing only big off and time but here we are in setting at the end so we are traversing one of the element multiple times but it is in a linear fashion assume we have given the length of the sandwich and the student as a hundred so as if we have a one till 100 times and again we have a zero till anytime so here I have to work I have to I will pop it out I will insert at the end so there are no element which is equals to the first which is equals to the top of the sandwich so we will basically work how much what we need to do we need to only work 100 times because cable as cable becomes equals to as K will become equal to the length of the student or sandwich I can say I have Traverse all the student and there is no student remaining which is equal to the top of the sandwich so mainly we can work with the so the time complexity is big of an and it is faster as well so you have to practice by yourself though we don't ever be thought think that you cannot do it even can do whatever p and C can do C1 so you can also do I can also help you so I will beat in the next video till then bye
Number of Students Unable to Eat Lunch
minimum-time-to-make-rope-colorful
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches. The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step: * If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue. * Otherwise, they will **leave it** and go to the queue's end. This continues until none of the queue students want to take the top sandwich and are thus unable to eat. You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `i​​​​​​th` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `j​​​​​​th` student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._ **Example 1:** **Input:** students = \[1,1,0,0\], sandwiches = \[0,1,0,1\] **Output:** 0 **Explanation:** - Front student leaves the top sandwich and returns to the end of the line making students = \[1,0,0,1\]. - Front student leaves the top sandwich and returns to the end of the line making students = \[0,0,1,1\]. - Front student takes the top sandwich and leaves the line making students = \[0,1,1\] and sandwiches = \[1,0,1\]. - Front student leaves the top sandwich and returns to the end of the line making students = \[1,1,0\]. - Front student takes the top sandwich and leaves the line making students = \[1,0\] and sandwiches = \[0,1\]. - Front student leaves the top sandwich and returns to the end of the line making students = \[0,1\]. - Front student takes the top sandwich and leaves the line making students = \[1\] and sandwiches = \[1\]. - Front student takes the top sandwich and leaves the line making students = \[\] and sandwiches = \[\]. Hence all students are able to eat. **Example 2:** **Input:** students = \[1,1,1,0,0,1\], sandwiches = \[1,0,0,0,1,1\] **Output:** 3 **Constraints:** * `1 <= students.length, sandwiches.length <= 100` * `students.length == sandwiches.length` * `sandwiches[i]` is `0` or `1`. * `students[i]` is `0` or `1`.
Maintain the running sum and max value for repeated letters.
Array,String,Dynamic Programming,Greedy
Medium
null
368
it has been asked by Amazon Microsoft Bloomberg Apple Yahoo and Google hi guys good morning welcome back to a new video this we going see problem largest divisible subset and for most of you including me it was a problem like oh ASA this kind of reaction for sure might have come or will come uh if you will solve this problem let's see what the problem says uh given a set of distinct POS again please mark everything it's saying dis positive integers nums which means all the values in the nums will be distinct positive and all will be them integers return the largest subset answer again we have to return a subset as in not the just size of the subset we have to return the actual largest subset such that every pair which means if I have a subset of 1 2 3 four five elements then every pair I and J of the element of that subset every pair I and J should satisfy any of these either I answer of I this answer of I mod answer of J is zero or answer of J mod answer of I is zero any one of them and if they multiple such answer multiple such largest subsets please you can return any of them in any possible order you want now as you can see in this that my two divides 1 right again if I take a subset including only two elements 1 and two then my two divides one so for sure and again I just want all the pairs and one of the conditions either two my can divide one or my one can divide two from this only you must have understood that a smaller element cannot be in the numerator of a larger element when we are doing a modulo so for sure a higher element modul smaller element if that is a modul by one that's all that's a good subset so one good subset is 1A 2 other good subset is 2 comma 3 n because 3 more2 is not a zero other good subset is three and one so you can see that we have only two good subsets and the largest subset size is just for us as a two so we can return any of them and the same way it has all of them as good subsets Arian how can you say that because if you take a two mod one that is true that is which means 2 mod 1 is zero 4 mod 2 is0 4 mod 1 is zero 8 mod 2 is sorry 8 mod 4 is 0 8 mod 2 is 0 8 mod 1 is zero so you can see all the pairs I and J are covered thus this is entirely a good subset now uh one thing which you might have thought of as a boot force and tution part which you can tell the interviewer is I can generate all the subsets now you know to generate all the subsets what all you need right it is just generating all these subsets to generate a subset you will take or not take an element it is 2 power n and then you have to go and check that element okay check that element that okay if that element sorry if that group or if that elements in that subset are actually satisfying my condition so it can be of n squ because you have to go and try for all the possible pairs but then we can reduce that to O of n also which we can easily see that uh like although we will see this optimization later on future but yeah we can optimize it to O of n just remember for wrong but I'll prove that in the later part but right now I don't want to spend time in this so uh one thing we can do is okay we can still optimize to of 2 N into n still maybe if we want we can just keep it parallel computation so maybe we can optimize it to but still it is kind of having exponential complexity which is for sure never work for us so uh from the constraints we can see we can try of n squ for sure because n is 1K and 1 6 will work so now we'll come back and read the every statement again and see that what we can derive from it we wanted the distinct positive integers okay we have the distinct positive integers we want the largest subset again remember we want largest and we want a subset and such that every pair answer of I comma answer of J of that element in that subset it should satisfy the conditions which were answer of I mod answer of J is equal to Z or answer of J answer of I equal to Z now every pair and we have a subset which means if it is a subset so order doesn't matter for it because it's a subset of some elements and when I'm considering I have to go on for every pair I can just see okay if this is the subset which I have formed a b c so I have to go on to kind of all the pairs so I'll go on to B mod a then because B mod a I'll check then and as you have remembered I'll check B mod a or I can check a mod again that was vice versa I can check a C mod b or a B mod C I can check a C mod a or a mod C so I can check a b mod a or a mod b I can check a C mod a or a mod C I can check a C mod b or a B mod C now one thing is for sure that from here I checked okay B mod a or a mod b now out of these two one will be for sure false why because one if we comp two elements and two are different elements so for sure if I compare two and three I know both the elements are different so 2 mod 3 will for sure be never equal to zero which means two mod a larger value let's say four it can never be equal to zero it will always be and again remember it's a positive integers then will never be equal to zero so from here I can just remove this entire half a portion although you can see I just trying okay B to a c2b then a c to so I'm kind of trying for all the possible n Square combinations but still roughly half of them okay I'm ear I was trying for 2 into n Square combinations then half of them I can actually remove because I know only larger mod smaller value can be a zero again I'm not saying it should be zero it can be a zero but smaller more larger will never be zero so the entire half portion is gone now how to remove okay I by this we have seen okay we got to know that okay I is put larger by smaller so I can simply see now that I will simply sort this out so I will now simply sort and out of two into n Square pairs I'll only be doing it up to and check for only the N Square pairs now for this one thing okay now you will check for only n Square pairs which means these n Square pairs you will check a b c as you can see B mod a c mod b and a C mod a you will check now just a quick thing a quick glance on what you are doing a b mod a equal to Z you will check you will after that go and check a C Mod be equal to Z right and then you will have to go and check for C mod a equal to Z now if you look back very closely B mod a is Zer then I can represent my b as something as a into K because a into K mod a will actually be a zero right so like this is how not cross works but yeah a into K mod a will some will be a zero so I can easily say that can represent my b as something as a into K because I know that okay B mod a was a zero so I can represent the same thing I can replace this B by a into K I can say C mod a into K will be a zero if this is if this portion is zero then for sure C mod a will for sure be zero because if I'm saying that 6 mod 6 is a zero then 6 mod 2 or 6 mod 3 will for sure be zero no so one thing is for sure that I don't need to go and check for all the N Square pairs again it's a extra optimization but because you remembered it's an extra optimization why because you know that still you can try for all the N Square pairs because the question has given you a liberty of O of n square but still while we were thinking out loud we figured out that okay it is not actually important to go on to all the N Square pairs I can just simply go on and I can just simply erase this and I can only go on to consecutive pairs which means if I have a ABC I just I'll go and check okay B mod a is equal to Z if it is then I can easily go and check a C mod b equal to Z and I don't need to go and check a C mod a equal to Zer because if this is if this portion is true and if this portion was also true so for sure this portion is automatically true now like no worries we it's an extra optimization make sure it's an extra optimation because the question gave us the liberty of O of n squ by default now and again we will just Dy in the entire part no worries on that part so now we have got that we can just simply optimize it two of in and simply will sort it down sort the numbers down we have the numbers in the increasing order and that was the first optimization which we thought of next we thought of that okay we just only need to check the previous sorting because of sorting rather than 2 into n Square I will only be checking n Square pairs but then I thought okay uh now rather than n Square pairs if I just compare only the previous values then I don't have to go on all the values previous so as to make sure that what's a number if something is divisible or not so that is two operations or two hints which we have got so far now let's come back to our main question we had this we remembered we will simply sort it down so I'll simply sort it down because we remembered what's the benefit of sorting now we had 1 2 3 4 and six now simply whenever problem is there simply land on to any one index I will not say if you are in the very beginning stage then it is good to dry from the very beginning and write down every step but if you are in a very moderate State also like okay beginning and just post that step then land I always recommend land on to any index okay I land on to any index whatsoever and then start to find what how will you compute your answer and what all things you need for the existing values to compute the current answer so if I am at four my again your ultimate aim was find the largest subset of elements such that the condition is there condition you remember it is if I am at this location I have to find the largest subset now largest subset uh the condition was that I will have to have a j okay my J can be here all right I just want my nums of I mod nums of J should be equal to zero now you can see 4 3 is not equal to Z okay that is automatically gone this is automatically gone then I can try for 4 mod 2 which means my J is here then my 4 mod 2 is a zero yeah it is a zero 4 mod 2 is a zero so are you saying Arian that two and four can form one subset yeah it can form one subset which is actually great but you ultimately you remember you want to find the largest subset so would not have been good that you when you were telling us about ABC then you were saying that okay A C and A B can form a subset but what about a b could have also formed a subset with someone else let's say a then what then you can also have said okay your largest right now you're considering only B and C but you can actually go and try for a also then you can have a three size subset which actually larger so which means huh which means for two if I would have stored it that what could have been the possible maximum length up to two so two would have said okay bro if you say then I can make one I can make pair with my value which is one and thus I will make a subset size of two and then you know that you can pair with me which is two because 4 more 2 is zero and two knows that he had paired previously with one a simple pair because it has now got a size of two now I can simply say okay bro I'll only check you and if I only check you give me okay what all Maximum possible size you can make and for sure if for mod U value which means four mod let's say U value is a if 4 mod a is zero then for sure all these smaller values which it had made pair with will also be equal to zero so now because of my two storing a value of this how much maximum size he can make I can simply say that now my size is a three so that's how we got to know now if we go and relate to this now by so far you must have thought of that what existing problem we are talking about it is simply an Lis algorithm longest increasing subsequence and that is The Vow factor I was refering in the very beginning that okay oh it's a l problem that is what you realize but it is not a very visible thing that's the reason I said it is a vow Factor oh it's allies problem because it is not readly visible that it is Lis problem now if you don't know what is Lis please go and watch this Lis again write the Lis by RM you will get the video you'll get two videos o of n Square approach and O of n login approach now for this video o of n Square approach is more than sufficient but for the folks who are still wondering Aran why can't I optimize it because you told us that okay I can just try I know I have to find the see Lis is longest increasing subsequence and in this in the this problem also I know that my subsequence or subset which I have made will be increasing because I will do a nums of I more nums of J will for sure be small so I know okay it's a increasing subsequence with a condition that okay nums of I mod nums of J is equal to zero and it's a subsequence which is consider equal to my subset longest which means largest so both the problems are actually matching increasing was replaced because of the fact that we want a increasing subsequence because of nums of I mod nums of J should be equal to zero so this is the only sufficient thing for you to watch but again if you don't know it if you know and still if you're wondering AR why can't I apply my Lis in login approach then I have clearly explained in this video that why Lis and login approach cannot be applied on these kind of problems so if you have a doubt go and watch this video cool now coming on that we will simply apply Lis that is more than sufficient so now simply dry a small dry which we will have for short in the very beginning again Lis will store long no it's simply an Lis algorithm that's it longest increasing subsequence which is equal to again longest increasing subsequence it was largest increasing subset increasing because we knew that we will do a nums of I oh nums of I mod nums of J is equals to Z this is what we will do okay now you have remembered it's exactly same now how we will build the Lis ARR simple uh firstly Lis length will be one for sure L length minimum length for sure for every will be one now for this he will go and check his back bro are you divisible from me bro he will say bro yes I am so he will just simply say okay uh my length is one your length which you have given the maximum length up till you is one so okay up till us the length is two simply it will go on two three it will try with two nah three it will try with one yeah I can so one and one for three so length will become a two four he will try for three nah four and again by default the value will be one itself which means the element four itself but uh three he will try with four mhm because 4 more 3 is not equal to Z no four he will try with two yes if yes is the answer then okay I will try to maximize it so 2 + 1 so here will try to maximize it so 2 + 1 so here will try to maximize it so 2 + 1 so here will become a three four like L maximum L will become a three and then four will try with one okay four more one is zero yeah true so 1 + one so he will try zero yeah true so 1 + one so he will try zero yeah true so 1 + one so he will try to maximize this but three is already more than two so he will not put a two here now for six a 6 mod 4 is not a zero okay by the value is one a 6 more 3 is a zero great uh so the value will become a three 6 mod 2 yeah great the value will become a three but I already have a three so no please don't update it 6 mod 1 great a zero 6.1 is a zero great but 1 great a zero 6.1 is a zero great but 1 great a zero 6.1 is a zero great but value will be two so don't update it so this is the Lis length which we have made but if you make sure one thing that in the explanation or in the question we only want we only didn't wanted the Lis length we have got this length but we only didn't want this length we also wanted to get the subset actual subset also so one obvious thing which could have come to your mind is Arian while you were building this Lis array itself I will keep track of the answer also answer is nothing but the maximum subset size for this the maximum length is three I just want all these three elements right so what I can do is okay I know the value was one so I can just put a one here okay one value was here the length is one so I have one element which is one length is two so two will for short be here and then I was able to make a pair with this specific one so I'll make a one here okay great then this was a three was already there I can make I cannot make a pair with two I can make a pair with one so while building the answer which is the L length itself I can just allot a one here okay because I could make a pair with one as I update my Lis length with the maximum value I can simply get that specific Vector from him and put in me in that Vector which means for four by default I had only four but then 4 3 n 4 mod 2 mhm so 4 mod 2 yeah which means I'll get this Vector 2 comma 1 2 1 and then in that Vector I'll just push back the me element four so I'll just get this Vector as you can see it is a this vector and then okay um the next I can do is um at this point six I am at oh I am at this specific six I'll go on to four nah but right now I have six make sure okay I'll go on to three yeah so I'll get this Vector 3A 1 okay I'll get this Vector 3 comma 1 I'll push in me which is six okay this is the vector I'll go again if I maximize my length this length L if I maximize it only then I update my this answer Vector okay I'll get this specific two although length is three but this is not maximizing so please don't update it like keep it as it is so that is how I can simply solve it but if you know by default Lis will take o of n Square time right so time is O of n square that is for sure and that we can actually do also that is completely correct but because of this thing which we are building it will take a space and all the elements and for sure for every element I can have a maximum of n space so with this phenomena I'm taking of n square space also so again you can do this it's an optimization okay still it will be it will submit the code but still can you optimize it do you actually need to build the entire a at every point no right why can't okay you know that you had the answer as three can't you just store one fact that from where this answer three you got I say okay the answer three I got in from this two and I can say for this answer of two I got the answer from one so I can simply build the answer parall okay from four I can go to two from two I can go to one and that is my answer so to build this answer backwards and for sure one obvious way is to show the answer parall also but I'll not show it because I know it will be taking o of n square space and I don't want to take the O of n square space so this part I will not apply I will use o of n space and for that I need to store from where I updated my answer so for this value three where it came it from where it came in like from where it got big so three this value three it actually came in from this specific two if you remember four more two was zero so in this value two I added a one okay the length will increase by one because for two the length L length was two saying okay one two are the elements now I'm saying four is also coming in which means the length has increased to three so for three the from where he should go to next which means the smaller element will be a this specific length of two so I can just parall you from three I go to two from two I go to one so same this is number four go to number two go to number one so I just need to store this backward kind of like previous kind of information for every Lis length are just St the previous index which index I should go to or the same way from which index I came on at this current maximum value so I'll store an information called as previous index stay that from where I came in at this location which means the answer L length how it got big because of some index at location one you can see it got big because of the index one let's say 1 0 1 2 3 4 so it got big of the index one element so I simply how I will do it I'll by default make uh let's erase everything I'll by default make my previous index let's say previous index I by default make min-1 previous index I by default make min-1 previous index I by default make min-1 -1 -1 -1- one as the P indexes because -1 -1 -1- one as the P indexes because -1 -1 -1- one as the P indexes because by default it's minus one now okay for this one there's no previous index no worries move on uh for this two as you remember the answer again let's build the answer also parall and also previous index also par so by default the answer is one for everyone so one is it is a by default values now as soon as I was at two I go and I went back to actually one value and asked him bro can you please let me know the uh if you can actually improve my answer he will say yeah bro two mod one is zero so I can improve your answer so he can improve my answer which means he will upd update that to two so I know who increased my answer was increased by index zero so index zero is the one who increased me so my previous index is index zero same way 3 mod 2 is not zero okay 3 mod one is actually a zero hm great if 3 mod 1 is zero so I can improve your answer one will say I can improve your answer for three and if he can improve the answer huh great I can simply go and simply I can simply go and try and say now that okay your previous index is actually a zero for same for four uh he can go to Three N he can go to two yeah he updated his answer if he can updated the answer great uh simply say your answer will become a three and who updated the answer updated answer was by index one and that's how you can simply build this previous index now what how you will find the answer simply you know that this is the length of three this is the length of index of two that's it so now you know that you wanted the largest subset so you will take the largest length you will start off with this index which means element six you will take then you will go on to the index two which means index two I'll go on which is this index I'll take this value then I'll go on to his previous index which is zero I'll go on to the index 0o I'll take this value I'll go on to his index minus one okay then I will stop so this is how I have to go and try for the value so that my space use will be only o of n one array for Lis length other array for your previous index and that's how you can actually optimize your space cool let's have a quick glance um the code is exactly same as that of L exactly same and again please make sure I'm using a bottom of code and please for the folks who don't understand the Lis bottom up code I have seen many people just sck to top down code or no matter if it's a linear DP or not if it's a linear DP please get out of your bottom up code sorry please get out of the top down code there are many optimizations which can only be done in bottom up code and it is very beneficial that you should be knowing bottom of Bo at least for the standard problems especially for linear DP always again for 2 DP I can't say don't do it but for the linear DP always do the bottom of port for sure I have seen many people just feeling in interviews because the interviewer ask you to print the path of the DP like when I say path of DP this is the path of the DP and recently A friend of mine he failed because he could not build the path of the DP because he never knew how to write the cod in bottom up great that's a worst you can do to you and that's attitude I have seen in people just they will say okay I only want top down code I don't even understand the bottom of code that's what they have perception of themselves but if you have the perception please break it down right now because you have to understand the bottom of code for sure and again especially for again the minimum requirement is 1dp at least 1dp you should be knowing what up for sure 2D you can still skip it but 1D for sure now coming on back uh I will just simply keep track of my n as my size now this is my Lis length again I Nam the same Lis length longest increasing the subsequence length same just to not make sure that you Disturb This is the previous index which will help me to get the final answer and maximum length because if you remembered I will start off my entire iteration by saying okay this is about the maximum length at this specific index now start off with this value as six then go on to the previous index values so it's a reason I have to keep track of the maximum length and the index at which I got this specific maximum length then I'll simply sort it down again this is an extra optimization which you have done on top of the existing code if you don't sort it and still if you modify the code a bit again now many people will just simply come and say that okay I'll simply remove this and still it should work no it will not because you will have to modify this condition also that you should check both the possible pirs now uh if you sort it then you will have to check for this just the previous value okay if this is i j will be for sure small now I'll go and try for all the ver I and for every I'll go and try for all the previous JS again you can also do it see here I did from 0 to I which means I'm going increasing order in J you can also do the same thing as I was saying explanation from Jal to IUS 1 J is greater than equal to Z and G minus this is this will for sure work and uh talking consider Lally this is a better optimization on top of this code because this will break out like much faster than this specific Loop so yeah it's uh but yeah both of them have the same time complexity now coming on back uh we will have a quick check if num this is the only extra condition in your Lis algorithm only extra condition and then you will have check okay if the current Lis length of I and for from J you are coming on to I right with adding one more character which was the ls of I if this is more which means you should update your L length of I because you are at the index I so I update the length which means L index of length L length of I'll update it and say 1 plus L length of J and then I can just update that previous index of I also to my G because I know that in the future I will have to build back my subset also now when this portion is done which means for I have found the maximum for I index I have found the maximum L length I will just have a quick check uh and update my maximum length of the entire array of nums and say if the current all length of I if it is more than the maximum length then please simply read the maximum length which is L of length of I and also bu the index also this is needed because in the super end I have to go and start from the maximum index maximum elements index and then have to Traverse back so it's the reason I'm just storing that parallely now when this entire portion is done I good to find the actual subset answer out so I just make the answer as a vector I'll say while my index is not equal to minus one because if you remember my base by default everyone will be a minus one and it will stop here I'll just simply push back the current index values and then find the previous index and then assign to index and then the loop will keep on going and pushing my nums of index values and then simply return the answer by this you will solve it in of n Square time with the space optimation as o of n so from Brute Force which is exponential we optimized that and from that we went on to O of n s uh time and space and then from o of n Square time and space we went to O of n sare time and O of n space again if you go back and remember in the very beginning I told you that you can actually optimize this o of n squ to O of n now you remember right o of n Square was the comparisons which you had to do you can remove this those comparisons by simply sorting it down which is n log n in the very beginning that's a pre-competition in beginning that's a pre-competition in beginning that's a pre-competition in the very beginning and then you can simply compare that parallely in O of n itself that's so that was the optimization in Brute Force but that is just for you to just know okay the interviewer just might know that he can actually solve it but I highly recommend don't speak those words here because then it might feel that you actually know the answer so just say Okay The Brute Force is this and then continue forward to your optimization approach and then tell the ultimate and then first tell the approach having the extra space which is the O of n square space and then ultimately go and tell o of n space and that's Sol good see you bye-bye ta
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
639
hey everybody this is larry this is day 10 of the july league code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem decode race 2 okay i mean i will say well one is i usually solve these lives so if it's a little bit slow fast forward what do whatever you need to do um yeah and join me on discord because if you like um today is the contest day so i right after the contest we go over problems and just have fun and so forth uh today's form is decode race 2. so this one is dynamic programming it's a very well-known dynamic programming problem well-known dynamic programming problem well-known dynamic programming problem uh if you're a little bit rusty or whatever um this is definitely uh a given one and i'm not gonna lie one of my colleagues um from my respect a lot uh that used to be one of his interviewing problems so it is a thing so definitely um you know my song so definitely keep that in mind and it is a problem that some people do as an interview so anyway let's see which variation is this because there are a couple of variations and basically this one there's a star character and digits okay so that doesn't seem so bad okay so let's stop oh and there's a okay so basically to be honest with these problems way often it is going to be just being very careful with order cases because if you've done enough dynamic programming problems especially enumeration counting ones then this is actually not that bad it's just about being careful and getting all the edge cases and all the cases which to be honest sometimes i do not get all the time but yeah okay so let's go through it um so i'm going to do this bottoms up keeping in mind that i am going to do this with omo and space you can optimize this to over one space pretty trivially actually but i'm just going to do that for now let's set this up and then now we will go from left to right and in this one i think it's a little bit easier usually i do a top down to be honest to do it one digit at a time but here we can go from left to right and just look at the last one or two digits and then kind of get the prefix so then you can just get the prefix um the number of ways to do the prefix plus the suffix of whatever you are like the last couple of digits so let's do that so dp of zero is equal to one let's actually set this to two plus one so that we can get it so zero is the zeroth digit so one thing i would say with these and you can set it up however you like so you may see different variation of this but the way that i think about it is okay well let's get only three examples okay well let's say you have some number here we'll skip star for now but yeah so my indexing is actually not the numbers itself even though obviously there's a correspondence but the spaces between the oops the digits right so then here my zero is the number of ways that there are zero characters and for one there's a number rate that one characters and so forth and also there's one at the end so then and our dp of zero is the number of ways that are after n characters right so that's basically how i set this up and that's how my why my dps n plus one spaces right so okay so then now let's go for indexes range from n what does this mean so this means that let's so how many rays are there for there so dp sub i e goes to the number of ways to end on the i've uh space right which is the space when i say space i mean this spot right for example so number of ways after the zero space the first space and so forth that's basically the way i would say it um so now we animate all the possibilities so okay if oops this is actual code sub index is you go to so they're only a couple of cases right so and this is something that we have to enumerate so basically we go okay if this is let's start with one digit first if as a district is um yeah if it's between one and nine right i'm keeping in mind that with one digit you cannot have a zero because there's no leading zero and because a is maps to one for some reason instead of zero but it is what it is so if this is the case then dp sub index is equal to dp of index oh whoops this is a little bit awkward we just you just have to be careful um because db sub index is not the same as uh the string of sub index right so this is actually d p sub index plus one is equal to db of index um yeah and that is correct right i think this is right because this is the case of if there's one digit then yeah this is just one digit okay well with one digit we can also check that if in x index is equal to uh star then what happens if it's one digit and it is a star then it could be any one of the nine numbers again skipping zero so then we do vd plus one plus or minus nine times tp of index because it could be any of the nine possibilities right um and of course at ray n actually let's change this now to tp sub n um we can actually we should actually mod it along the way but i just want to make sure we get it right first um because you know i made this mistake before i forgot that later so it's okay so let's actually do it now because i sometimes i forget um okay so that's one digit and i think i took care of all the one-digit ones is there care of all the one-digit ones is there care of all the one-digit ones is there any other one-digit numbers now any other one-digit numbers now any other one-digit numbers now so then let's do the two-digit ones so then let's do the two-digit ones so then let's do the two-digit ones right um yeah and if index minus one is greater than zero something like that is that true yeah basically we just want to make sure that there are at least two digits that we can count then we check right if this is we have at least two digits then okay what are our cases right and this one is a little bit innumerative um at least the way that i do it maybe you know at least the first time i would just try to be exhaustive and try to figure that out and then maybe optimize the if statements later so that you have fewer if statements as you generalize the case but again correctness is what you should aim for in the beginning so that's basically what i would do okay so now let's just say previous is you go to s of index minus one and that's actually just that now as you go to s of index or current maybe so that we just keep things a little bit straightforward and you know stuff like that it's just kind of for me and it's an idea so that i don't kind of mix up with things but yeah um so what are the possibilities right well you just enumerate them if previous is equal to zero then nothing happens uh now we're doing two digits right two digit numbers two digit possibilities so if there's a two digit number starting with one then dp sub one let's see right and now we have only one thing again if zero then there's basically the ten oh no well yeah basically there's only one possible you know if the previous digit is a one and the current digit is zero to nine then you know there's one way to kind of ch lop that off we just lop off two characters and that's basically how we do the counting um okay else if i guess this could be an it could be an elsef but it doesn't really matter that much because if they're mutually exclusive it doesn't really change right um otherwise if current is equal to star what does that mean oops that means that it could be any one of the ten digits so then we do in um we do something like this because there's 10 ways to do it um and the reason just to kind of go over this very briefly the reason we have this is that we can this is kind of a shortcut what you would do maybe is actually something like dp index plus one same as we have here but then we would do this nine times and you could say okay if we substitute i can spell substitute as a one if we substitute it uh two and so forth right and that's basically the idea here um but yeah but instead obviously there's nine of them so we do this uh yeah so here in this case is the same so yeah so here in this case is the same because we have one for zero one for two one for three one for four and so forth okay and that's pretty much the same else for this one but if previous is equal to two then we go okay if zero then it is a number between zero and six and there's seven of these but yeah and of course this is the same as before we it just counts for one of them because now you lop up two digits you're able to lock up two digits otherwise if current is equal to zero or a star then we can we have zero one two three four five six so seven of these i think i messed up this once before um because of this last time i did this i might even have a video i don't know if i do but i think the last time i did a top drop down like really remember it but it's been a while right and then the last possibility of a two-digit number is two-digit number is two-digit number is if previous is equal to um a star right if this is equal to a star then again we just go for the cases of if um let's see and this is of course a combination of this and this so we can actually just copy and paste i think this one's a little bit sketchy yeah because that means that the previous number can be say as one or a two um and we just kind of do the math that way because we can lop it off assuming that the previous number is one or a two and yeah and then the other one is oh i guess this is not an elsef otherwise if current is another star then dp of index plus one then we lop up two digits but the two digits has 26 characters right because it could be any one of the 26. uh also i made a mistake here this should be minus one because we're still chopping off two digits i don't know why i did that not everything about it and that's pretty much it well except for this is one because we've been updating dp and xbox one but um yeah let's see if this is right this feels a little bit awkward right now oh did i miscount something well at least the good thing is i'm long on 19 which is um pretty good why am i wrong because that means that i'm off by one on one of the countings um why is this not 19 well hmm so it could be one so it's one digit yeah that's the hard part about this problem is that you really have to make sure all these are correct but sometimes you're not sometimes you're just not right on all of these but okay it seems like the good thing is that when you get something really easy wrong then you have an easy way of uh debugging it let's see so the previous is one and this is current then as you go to 10 times so we did summation of this and this is why is that one because there are 10 digits or 10 ways to interpret this can i mess up here why do i think there's 19. so yeah so this could be any one of the nine that's right oh is there no zeros okay maybe okay so zero is excluded for some reason huh so okay so i just misread the thing which is good because uh otherwise i'll be a little bit embarrassed going through this but it is annoying i just huh i need to be better about reading to be frank but why is zero excluded that's just a weird thing to remove but okay so let's go for it again then obviously now there are no zeros and obviously in this case um well there's this cannot be zero anyway but here that means that we cannot fill in uh zero so graphs this we have this and and what does this mean that means that this is not 26 anymore right that means it's 26 minus 10 and 20. so that's 24. okay so this looks good then okay so got me worried that i got i missed something really obvious but i'm glad that this happened um one thing that i would say is that i am to be frank very sloppy with the modular math um if you're not in pipe i do this because in python it doesn't matter as much because it has auto promotion and as long as you mod within reasonable amount of time um you don't get under or you don't get overflow but if you're in different languages i definitely recommend modding after every adding um i would even um oh let me give it a submit before i forget i would even um oh why didn't i test this okay that's fine i guess i should test more but yeah um for i would even what was i going to say yeah for different languages i would even have a big numbs class well not a big numbers class uh a modular math class just do it once so that you can understand all the implications and test it so that you don't have to worry about it in the future especially if you're into competitive a bit um okay so i am getting wrong the case where the two stars in the world so it seems like i am wrong here which is fine it's not a big deal but why is this not 24 um i mean clearly i think i just have this case wrong but again this is just enumeration so you can just think about all the possibilities and again i really should have tested this because this is very obvious example but i got a little cocky as i was talking about it um but why is this wrong so it's just that this number is wrong but what shouldn't it be if it's not 24 oh i am dumb okay it's not 24 because it also doesn't have to zero one the one digit one so i was i got lazy i said 26 minus 10 and 20. but it's actually 26 minus all the one digit ones which is from one to nine well yeah one to nine plus ten and so then we have to subtract another so okay so that's how many is that let's double check 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 so 15. right so these things like i said it's very simple it's just you have to be okay see there we go whoopsie daisies a little sloppy there uh for sure but that said it's not hard it's just that you have to be careful oh my oh because i don't i thought you can't get a zero in this ah this is way annoying to be honest because well this one maybe i just missed red um because i feel like this one's the trick cases wait can i okay this one's a little bit confusing with it's handling of zero but like i said um so the actual algorithm it's not that bad it's not that hard i hope and i hope that you understand it but i am running into some technical difficulties uh because of understanding the problem which is another problem but that's another story um so is it just that if this zero we just don't hold it at all that's really awkward though so star can be any from zero oh no well i think i just missed some okay maybe i misunderstood this one still so there can be zeros to nines it's just that the star cannot be that is that right okay so let me fix this again so there can be zero and whatever um and in this case we have to handle the case where the last digit is zero and the reason why this isn't valid it's because wait why is that invalid this can this all just be once i think i just don't handle zero correctly because i try to fix it and then i thought that zero is not possible but i was wrong on that one um sloppy but okay let's see and i'm doing a little bit of cheating by having some cases here but i'm trying to understand why this would be zero oh no why did i oh i misread this outfit okay i am having a fun day a fun morning it's too early in the day but i read that as the expected output is zero and what we get is world war but it's the other way around okay so then we can fix that and we kind of fixed it a little bit by adding this to zero and nine but it seems like we still we overcount already because so star and zero yeah we just slap it off we lob it off twice so why is this 11 oh this is 11 because we as we have one digit and then we assume we always assume that the last one had one digit but that's not the case oh this is not true that's why okay just have to be really careful it's very precise um as you can kind of see now okay this is good now um and as you can kind of see you have to be really precise and all these the reasons why i and i just kind of absent mind in the uh changed orders the ones back to zero to kind of fix it but i didn't really go through the cases right what i should have done is go for the cases and for one digit numbers we cannot have a zero so that's why here it should be still from one to nine where here it could be from zero because in two digit cases the second digit could be zero okay let's give it a submit again uh okay i think this is more right now uh i should have tested more as well still but i again i was sloppy and i don't know okay cool so this is accepted finally like so yeah so i think as i was saying the hard part about this is about just enumerating all the cases you can maybe clean this up a little bit the code but the idea is still the same which is that you just have to be really careful and really think about it um think about all the cases there's nothing that tricky about it in terms of that i mean okay there's something tricky maybe you want to say with respect to how to handle zeros and so forth but that's something that no with enough time you're able to stop there's no high level wizardry there's no like crazy algorithm that you have to do but yeah it's just me literally being really careful and in this in my case not being very careful but still eventually going through all the different cases um again uh the other thing i would urge is just be careful with the mods you should mod after operation so it might seem like that i'm doing it kind of haphazardly uh with respect to mods and maybe i should do its own separate video explaining um numbers and how they get stored and why you need to do mod and how to do mod correctly in a lot of cases i do it in a sloppy way because i know exactly how to get away with it and how to fix them and things come up but definitely do some reading up on it i don't think it's that important to be honest in real interviews but for competitive programming uh it does come up quite a bit so if you learn to do it once you're pretty good for the most part you know i would also say that when i change back to c plus or something uh a lot of my mistakes are because of using into long or mods so you mean i make these mistakes a lot um because i'm not as uh careful about it so yeah um what is the complexity you can kind of see that for each digit we just go through this assortment of if statements and only addition so this is going to be linear time um yeah and in terms of space as i said this is going to be linear space but you can actually reduce this to over one space by keeping um you know by noticing that we only look at the current uh well we look at two digits but we only look at also previously two counts right the dps of index and db of index minus one and as long as you're going to do a cascading type thing in a very small way similar to fibonacci you could get it to all one space i'm going to leave it as an exercise at home i'm going to make this slightly smaller so you could see all of it very briefly um but that's all i have linear time then your space but you can reduce it to all one space trivially or easily you can also look up my space optimization video i also have done space optimization forms in the past so maybe check into that's all i have for this one let me know what you think stay good stay cool have a great weekend and to good mental health i'll see you later bye
Decode Ways II
decode-ways-ii
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. **In addition** to the mapping above, an encoded message may contain the `'*'` character, which can represent any digit from `'1'` to `'9'` (`'0'` is excluded). For example, the encoded message `"1* "` may represent any of the encoded messages `"11 "`, `"12 "`, `"13 "`, `"14 "`, `"15 "`, `"16 "`, `"17 "`, `"18 "`, or `"19 "`. Decoding `"1* "` is equivalent to decoding **any** of the encoded messages it can represent. Given a string `s` consisting of digits and `'*'` characters, return _the **number** of ways to **decode** it_. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "\* " **Output:** 9 **Explanation:** The encoded message can represent any of the encoded messages "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", or "9 ". Each of these can be decoded to the strings "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", and "I " respectively. Hence, there are a total of 9 ways to decode "\* ". **Example 2:** **Input:** s = "1\* " **Output:** 18 **Explanation:** The encoded message can represent any of the encoded messages "11 ", "12 ", "13 ", "14 ", "15 ", "16 ", "17 ", "18 ", or "19 ". Each of these encoded messages have 2 ways to be decoded (e.g. "11 " can be decoded to "AA " or "K "). Hence, there are a total of 9 \* 2 = 18 ways to decode "1\* ". **Example 3:** **Input:** s = "2\* " **Output:** 15 **Explanation:** The encoded message can represent any of the encoded messages "21 ", "22 ", "23 ", "24 ", "25 ", "26 ", "27 ", "28 ", or "29 ". "21 ", "22 ", "23 ", "24 ", "25 ", and "26 " have 2 ways of being decoded, but "27 ", "28 ", and "29 " only have 1 way. Hence, there are a total of (6 \* 2) + (3 \* 1) = 12 + 3 = 15 ways to decode "2\* ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a digit or `'*'`.
null
String,Dynamic Programming
Hard
91,2091,2251
786
hey what's up guys this is chung here so today uh let's take a look at another lead code problem here number 786 case smallest prime fraction so okay you're given like a sorted array integer array containing a one and prime numbers only the one and the prime numbers again right so one is not a prime number right so prime numbers starting from two and where all the integers of the array are unique and you're also given like integer k so for the fraction right so for the fraction you know it basically it's a divide it's a result uh of uh one number divided by another number okay and so in this problem you know so we have a rule here so the so we have a the fraction defined as this one so array i divided by array j where i smaller than j so this one also means that you know since the array is sorted it means that you know array i is always smaller than array j right and also it's because all the numbers are distinct right and our task is to find the case smallest fraction consider and we need to return the answers of the of those two numbers basically what are the two numbers array i and the ray j who's uh who whose fraction is the k smallest one yeah so that's basically the description of the problem so we have example one here right so for this one we have four numbers uh we have one two three five so three five uh two three five are the prime numbers are prime numbers yeah and so the output is two and five because you know for all the fractions you know we have one five one three and after and we sorted we have one two three right so this one two divided by five is the third smallest fraction among all the fractions and in example two here you know of course there's since there's only one number only two numbers in the array here so that's why it's one seven and here are the constraints right so the constraints are a one thousand actually it's not that big and it's also guaranteed that guaranteeing that you know case valid basically you know so k will not be greater than this one because this is the total number of the fractions right and then all the numbers of array are unique and sorted in this strictly increasing order okay i mean the brutal first way of course is try to get all the fractions uh among this array here right that would be a n square time complexity right and then for all those kind of n square time uh n square like fractions we do what we do a sort right that's going to be a n square times log n square right and that's going to be the total time complexity for the brutal first way and after this one we just got the first we just get the k element uh from the other sorted list but that's not obviously it's not a very efficient solution because obviously we're not utilizing this sorted array uh property here right so how can we utilize this one so if you guys remember the case you know for the case small is a fraction we have a solution right we have like the uh we had like a similar problem let's say we have like unsorted list let's say we have unsorted list and then we're trying to get the uh the case smallest one among all those kind of unsorted list so how did we solve that problem basically we use like the priority queue right to help us solve that problem since you know the uh all the pr since each list is sorted we just need to uh at the beginning we push the smallest element from each of the leads into the priority queue right and then we just keep popping from the priority queue and as long as we have pop so the case number that we popped out from the smart the priority queue that would be our it'll be our like the uh the case smallest because you know in the product queue we're only we're always storing the current uh up to the length of the least smallest number in the priority queue right so that you know we can improve our time complexity by not enumerating all those kind of all the uh the possible fractions pairs so for this problem you know what are so how can we convert that can we convert this problem into that unsorted list the answer is yes right you know if we let's see if we have 1 2 3 5 11 right and then 13 what's the next one 17 i guess right so you if this is the list of the array here and assuming let's say we fix the first number you know if we have the first number equals to one you know the more we go to the right side the smaller the number is right so which means that you know for each of the elements let's say starting from one here you know the smallest one among all those kind of elements is the first one divided by the last item which is 17. this is basically one 1 divided by 17 is the smallest number uh by fixing the first element right because this one is greater than the 1 divided by 13. right also greater but greater than the uh also greater than 1 divided by 11 right so same thing for two right so for two is same so this one is the smallest by given like two at the beginning at the first number right this is a 2 divided by 13 right so on so for similar for 3 right so now as you guys can see now we have like a sorted array already right where the uh because at the each of the location of the index right we are using that index the number on index as the first element and then we're just simply moving to the left side we start from the end that'll because that's will be the uh the smallest one right and every time uh once we pop one element we pop the current smallest number from the product queue we'll just use that index we use the current index and then we find we'll find the ones on the one on the left side and then we push that a fraction into the product queue so similarly like how we solve the uh the to find the k smallest number among unsorted list and then we simply need to maintain that length of the length of n priority q and then we just need to do a case k times pop okay cool so let's try to code that things right the first approach where we have n equals to array here and then we have like priority queue right and then to start with right so we start from zero to n minus two right because we need at least two numbers so we do a priori q dot heap push right priority q and things we need to sort by the first add by the fraction that's why i'm going to store that fraction into the adds the first element into the priority queue right and then at the beginning it's o minus one right and while doing that since we're also gonna be uh after we pop the current one out we also want to find the next one in the current sorted list which means we also need to maintain that those two indices of the current fraction so at the beginning we have i the first index is i and the second one is at minus one right because we always we start from the log the current i divided by the last element which is the smallest and then we simply just need to do a while k minus one and let's do k you know um uh let we can do k minus one here so basically after doing the k minus one you know so the top one the first one in the product here will be the k smallest right and so we have this one i ing right so heap q dot heap pop product q okay and so we will uh we'll push we'll get the negative next one when the i is smaller than j minus one right because you know if the if j is smaller than if i equals to j minus one then basically those two numbers are next to each other which means there's no more fractions in this sorted list so heap q dot heap push right and i can just simply copy this part here by with a little bit of modification here so we have j minus one right so because we're moving to the left and this is also j minus one and then we decrease the k by one and then lastly we simply return the uh those two numbers on the priority queue on the first one of the particular because that will be the case smallest one right so the first one is the one it's the one second one is the uh the product qr.0.2 the product qr.0.2 the product qr.0.2 right yep so that's it right so if i run the code here go here okay submit okay cool so it works right i mean so how about the time complexity for this one you know so for the for loop here we have what we have uh we have unlock n right because we loop end times and the and we're going to do a push into the particle which is the log n that's why we have unlock it how about this how about second one so the second one is the k right so at the beginning we have k times what log n right yeah so that's why the time the total time complexity will be n plus k times log n so that's going to be the total time complexity for the priority q uh protocol solution okay and there's another solution for this problem and which is uh even faster than this one this is because you know the uh you know since we're getting the case smallest you know and the array sorted it's a i think it's a good candidate by using the product that's our the binary search so for the binary search you know the uh you know usually when we do the binary search you know we search the answer directly right but for this problem you know we cannot search the answers directly you know because and we want to find the case small as a fraction considered and we also want to maintain return the uh those two numbers from that fraction it's a little bit of different uh comparing to the regular binary search so what we can search for this problem is that you know we can search the uh that fraction so we can search that fraction and the range for search is from one to zero from zero to one since it's like uh since uh i is array i smaller than rhj so the total all the fractions they are in the range of zero to one and we can simply search this a fraction uh in this range and by give given like a fraction here right we want to count how many uh pairs right how many fractions are smaller than the current half right so if we can do that right if we find all the uh if we find the count for all the pairs whose fraction is smaller than the current f and then when we find the uh when we find the count who is equal to the k then that's the uh that's the fraction basically that's the fraction we can we're looking for right so let's say for example from one to zero at the beginning we have uh zero point five right and with 0.5 right and with 0.5 right and with 0.5 let's say we have so let's say k is equal to 7 right so after our calculation let's say if there are uh the count is equal to five which means that there are like five pairs whose fraction is smaller than seven sorry who is smaller than 0.5 sorry who is smaller than 0.5 sorry who is smaller than 0.5 it means that you know okay so this fraction is too small we need a bigger fraction so that we can find the uh the smallest frag the case smallest fraction so which means that we need to search from 0.5 to 1. from 0.5 to 1. from 0.5 to 1. right and so the moment when we find when the count equals to 7 equals 7 then we know okay so this fraction basically this fraction let's see the fraction is like zero point uh zero point eight five so when the fraction when the search fraction is zero point five eight five and then we have a count equals seven then we know okay so uh there are like uh seven pairs whose uh fraction is smaller than zero point eight five right but still even though we have this one but that this is not the answer we're looking for what we're looking for the pairs so what uh so what are the pairs so basically we want to find the pairs that's on the left side which okay so we want to find the pairs that's closest to this who has the fraction who is closest to this 0.85 right so which means that you know assuming we have 08.5 we have like assuming we have 08.5 we have like assuming we have 08.5 we have like several uh fractions we have seven fractions here we have this fraction one two three four five six seven so these seven fractions are the fraction fractions that smaller uh smaller than zero point five eight five and which is our answer is this one since we want to find the k smallest which is the uh the closest one right which is the one closest to the 0.85 okay and yep so i think that's the idea here so we uh we do a binary search and we'll the binary search will basically try to find the uh the proper uh threshold of this fro of this fraction where we can find exactly case uh k smallest smaller fractions um and then we will with the last thing is that we have to find somehow to find this uh this number this the closest number right uh comparing to this uh threshold here so to do that you know we can what we can do here is that while we're doing the binary search we can just maintain we can maintain this uh the pairs who is close who is the closest one comparing to the current threshold right and then so that you know once we have find that thing we can simply re use that return that value okay i'll try to explain a little bit more how can we maintain this uh these pairs uh while i'm writing the code here and so let me come out these things here so again we need uh do we need n here yeah i think we need that so n is going to be array here and then we have left equals zero and the right equals to one okay so while left is smaller than the right so we have a middle equals to left plus right divided by two so keep in mind we're doing like this decimal we're not doing this uh flooring we're doing this decimal uh division here and so for the count right so let's let me try to finish the main lot the main uh loop uh drainage search solution and then i will add the uh the logic to maintain that pair right who are who is the who's closest to that uh to this middle point here right so we have a count equals to zero and in range n minus one oh and another thing is that you know for each of the given like uh threshold the given fraction how can we efficiently count how many pairs are smaller than that right i mean we don't want to do a like uh a brutal force other possible scenarios because that will beat the uh the purpose of the binary search so how can we efficiently count how many pairs who are smaller than the current one so again let's say we have one two three five seven eleven and thirteen right so for example if we have this kind of uh array here given like uh given like a middle point we start from for compare starting from the first element and the second element okay so this is i and this is j right so one of the property since it's sorted you know if the array i divided by ray j is greater than m that means that we need to find like smaller fraction which means that no we need to we'll move this j to the right and we keep moving j to the right until this array i divided by a ray j is smaller than m so let's say for example if after moving j to here okay if j has moved to here and then which means uh one divided by seven this one is smaller than m it means that you know for one we have three numbers we have three pairs who are who's a fraction is smaller than m because you know five is five it's one divided by five is still uh it's all still greater than m but one divided by seven is smaller so which means that any numbers after seven to the end will be they will all be smaller than the current at right so we have j here and then the then we're moving so which means we have three here and then we're moving i uh to the right as well so now i is equal i pointing to here right so i pointing to two here so for two we now we need to count uh the pairs right uh who's the first whose array i equals two how many pairs of that is smaller than m but to calculate that since it's sorted we don't have to count js we don't need to move j back to here back to three because we can simply start from where it has been before and why is that now this is because you know um because we know one a one divided by seven is greater it's smaller than m and which means that you know two divided by seven two divided seven is greater it's greater than one divided by seven right so it means that you know we can simply check if the current uh if it's two divided by seven is still smaller than m right if it's still smaller than m then we know okay we have another three uh pairs whose fraction is smaller than m otherwise you know we keep moving the chase forward to the right side right maybe another way to explain this problem is that you know we know 1 divided by 5 is greater than m right because when we try to find the pairs for number 1 here you know 1 divided by 5 is greater than m so which means that you know 2 divided by 5 is going to be greater than 1 divided by 5. it's going to be greater than m right so which means you know we there's no point of checking the three and the five again so which means that we can simply start checking the uh the jade from where it was before right so now as you guys can see so since i and j they were all they're always moving to one direction so that you know this 4 will be of end time complexity right okay cool and let's finish what we have left and like i said while the j is smaller than n and the array i it's divided by a ray j is greater than m right then we keep moving js forward okay and what else so oh so if the j is greater than is equal to n we can we simply break right because if there we if we cannot find if okay so if by moving if j is equal uh after moving j to the end of the ray if we still cannot find the uh a valid one right so which means the j is now pointing outside of the ray here then we cannot find uh we cannot find the uh the valid pairs right then we simply just need to break because you know even though we move the eyes forward to the right side the fraction will become bigger and bigger right that's why we can simply break when the j has moved outside of the right here otherwise we're gonna we just increase the uh the count you know since j's you know on the left side are the all the pairs which are greater than the frag than the current threshold anything that's on the right side is smaller that's why we do a n minus j right and yeah so and after this one we do a simple check so if the count equals to k we think we can we'll return here else right i'll see if the count is smaller than k basically we'll discard the left part right otherwise we discard the right part so that's this is the basic uh for loop uh sorry the basic binary search template but now the problem is that how can we find this p and these two numbers you know like i said we want to find the uh the closest number the closest the fraction the number the fraction that closes to the middle point okay and how can we find that we can simply just define like another maybe another p and a q right and every time when we are uh when we find like the uh the current smallest the current is basically the biggest number right for the current uh loop here we can do a check here so if the uh this array i divided by a ray j is greater we can have like a max fraction here right equals to starting from zero if that's the case we do a p equals to a i a ray i right and then q equals to a rej and then we just update this max fraction equals to the p divided by q right and here i just simply return the p a p and q so what we're doing here is that you know let's say we have again right we have 1 2 3 5 7 and 11 and 13 right so let's say we stop at let's say i is here right and j is here so when we stop here so i and j are the first pair who is smaller than the m right uh given this i is the p is the first uh number right which means it is also the greatest the biggest one uh with this i which is so i as the first as the denominator right because you know if we move the js moving to forward to the right side so the fraction will become smaller and smaller okay right so which means since we're trying to find basically the number who has the biggest fraction right among all those kind of uh candidates here that's why you know the current j will be the biggest one uh given of fixing this i here that's why we can simply use this one to we can every time we find like a the first pair right who is smaller than the f here we can just use that smaller than the m here we can use that pair to update this p and q because you know and after this one so we will find basically we'll find the biggest fraction a biggest fraction among all those kind of uh candidates among others those fractions who are smaller than m which is exactly what we're looking for of x here okay um yeah i think that's it right so if i run the code oh i haven't defined the j yet so j starts from one okay cool so as you guys can see this one is much faster right and why is that this is because you know we have like a while the loop here from left to right and inside here is also it's an n right so we have n times what take 10 times n times log something this log is what it's a range between l and r and always a range so this is the range actually and i think it's the basically the pre precision is how many decimals is between 0 and 1 we're looking for here i think it's kind of uh normal to assume this one is like 10 to the power of nine because i think this pre with precision of nine digits of i nine that decimals is so this one should be uh accurate enough because you know when we have zero to one it will be divided to zero point five and then zero point five will be divided to zero point what two five right and then one two five and then so on and so forth right so it'll be divided to a lot of decimals i think night decimals should be enough should be accurate enough that's why you know we have n times log this like this which is uh pretty fast close to n right okay cool i think that's pretty much everything i want to talk about for this problem and uh yeah thank you for watching this video guys yeah stay tuned see you guys soon bye
K-th Smallest Prime Fraction
search-in-a-sorted-array-of-unknown-size
You are given a sorted integer array `arr` containing `1` and **prime** numbers, where all the integers of `arr` are unique. You are also given an integer `k`. For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j]`. Return _the_ `kth` _smallest fraction considered_. Return your answer as an array of integers of size `2`, where `answer[0] == arr[i]` and `answer[1] == arr[j]`. **Example 1:** **Input:** arr = \[1,2,3,5\], k = 3 **Output:** \[2,5\] **Explanation:** The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. The third fraction is 2/5. **Example 2:** **Input:** arr = \[1,7\], k = 1 **Output:** \[1,7\] **Constraints:** * `2 <= arr.length <= 1000` * `1 <= arr[i] <= 3 * 104` * `arr[0] == 1` * `arr[i]` is a **prime** number for `i > 0`. * All the numbers of `arr` are **unique** and sorted in **strictly increasing** order. * `1 <= k <= arr.length * (arr.length - 1) / 2` **Follow up:** Can you solve the problem with better than `O(n2)` complexity?
null
Array,Binary Search,Interactive
Medium
792,1672
82
Hello Hi Guys Welcome To Our Dhundhi See Today Will See The Question Remove Duplicates From Left To Delete All No Specific Number 19 Number From The Return Of The Value Of Three And Not Content With Values ​​But Only Of Three And Not Content With Values ​​But Only Of Three And Not Content With Values ​​But Only One To Three And Valid Notes Will Be To- Do List in Ascending Order To- Do List in Ascending Order To- Do List in Ascending Order Okay Listen Let's See How They Can Solve This Problem Lipstick Posting Sample Android Driver Solution of the Giver Input and Output 4999 Point to Point Subscribe to That You Traditional Compare the Value of Held and Not Get User Will Need to Subscribe Values Like this is the president of that this head and daughter are not able to bind this is not avoid eating food and good connected to this a sudra is all about the approach That Will Be Using Knowledge To Head And Shoulders Solution For Example Will And On Hua Hai Liye Suyogya Tummy Contains The Value Zero And Its Point To Subscribe To Yesterday Morning He Did Not Null At This Time Milkshake Is Pressed Next9 Tunnel And Digestive Values ​​Are Quite Beneficial That this minute that chapter notes pet is overpowered and accessible again taken by luhan directly notification alarms here source file this condition is true with you have equal to dot next then you try updowners pet dot com to k dot next to connect the next Previous Two Daughters Will Not Do A Serious Issue Will Do Everything Else Start Throwing Plates And Every Case You Also Need To Hold On To Daughters Day I Finally Got Into Middle Order Daughter X That Clutch Tried To Run This Code On Sunscreen Write Result Leg Submit That if submitted time complexity of and subscribe and they need to go through every day and complexity of
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
150
Hello everyone welcome, this is the question of my channel and such questions are very popular. Literally such questions are asked everywhere. I am fine in multiple times. Who asked who? Microsoft Amazon Apple Flipkart Transactions Okay. Let's understand by looking at the input and output of the question. What is the question? So the question is quite straight forward that you will be given a vector named Tokens, which will contain strings, it will be just strings and what can be in that string, that number will be -200. There can be numbers from 100 to 200, that number will be -200. There can be numbers from 100 to 200, look like man lo, this is you, no, ok, you are this van, plus a, what does it mean that whatever two operators will be there before that, then you have to add plus to them. If we have done plus then three is gone, okay so three is now instead of three, okay, let's write three in, one is gone, that means whatever is before this, we have to multiply the first two open, then the second is the first print. This one is three, the second one, we made three, da, na, it became three, if we want to multiply, then a is nine. Okay, so this is not your answer. Okay, so this is simple and easy to understand. Whenever you see an operator. So, just before that, you will have two numbers, velvet them, okay and here I have given you a plus. What did I say before the plus that I would like two offers, right here there is only one, if you add two kisses then it is like this. There will be no input, okay, this is invalid input, they will not give such input, they have given it, okay, let's go into the question and think one thing for yourself, here there are two and one, connect these two okay, after that later when you move ahead. You should have these three, only then you will be able to store them. Okay, that's why by the result of the past, you mean that it is going to be less in the future, then what would be a better data structure than this, to solve this, it is simple that brother two Came two, kept one, came one, kept plus A, went neither, what will you do last, friends, what to do brother, doing plus, made three A, okay, so this is, must have gone both, and the result that came, team it two. Back to tag three. Okay, now let's move on to three A's, let's go to three A's, multiply by three's, let's go to multiplication, go to the top of the stack, top the elements, pop this one, three A's, multiply. No, then the answer is not found, so pop this and put nine here and there is nothing beyond that, no, we have seen all the elements, so the top of the stack will be my answer, no, this is simple, no, the solution is very simple, that's it You had to think about the stack only, I was of the same opinion that you are thinking about sex. Generally in Amazon, I have noticed that they ask more stack related questions, they ask you to figure out, so date is something you want, you check if you are able to figure out. Are the questions made up of tags or not? Otherwise, I am not telling you either what it is in general or what is the call time. You have been studying this in college too. I was told the same in college that all the solutions of these value eight ones have been told that what is simple? We will take the stack and whatever is the input, like what we did here is the input device, you are one, plus is 3, these are all the strings, okay all the strings are okay, simple, we will take a stack and input it in the stack like I take mine, I just came here, okay, you got me, okay, if you are there, then I have given it to him, after that I have come here, I have got a van, if there is a number, then let's give it to me, after that, I have given it to you, I have come here, see. I have got the operator and I have got the printer, so what to do if I get Plus, okay, I have fired the van, you have also fired me and will send it back to the start, okay, this is done, now I am moving ahead. I came here, what did I get, the number is 3, so brother, quietly give me the number, here I came, the operator was found, so what did I say, top you top the element, he is asking for multiplication, so I made it nine, now it has started, something further. If it is not there, then I will do the character in our last, returns start, one thing is that these are strings, right, and you are doing string plus string, three will be a bit, so convert it, see, there is a function called s2i, what does it do? It will take the string, convert it and give it to the waiting person. Ok, it is a simple thing and it is possible that if the input is large then multiplication becomes over flow. Sometimes multiplication and flow happens, so we will do it like this. No, we will make it long, like it is 3 *3, we will *3, we will *3, we will convert it, there was a test case where it was spread, it is fine for me, it was very simple, it must have been understood, so let's code it once, but the code Do not wait after doing this. I will tell you a very important and very fancy way to solve this question through the map and in this I will teach you how to write Lambda. We will write Lambda with one sentence which will make our life even easier. It will make the code more symbolic, so this is just for learning, it helps a lot, this thing is fine for you, if there is a coding competition, if it is a challenge anywhere, then this will also increase your knowledge and you will also get the code simple and It will clean, okay, so let's code it first, it is a simple one, no, it is a simple question, okay, the question is quite good, so let's solve it, okay, what did I say, we will take intelligent ones, okay, after that, what am I saying? That is, we will start attracting on this, okay for string and token in token, okay, I will get the tokens, okay and I will check if sadness is equal to plus or else okay, we will push it into the question state and operate. Let's write a function named, which will take A, B, and which operator, right now the operator is fine for me and will send only the result that comes, I will push it here, it's fine, something is two here, not simple. And if this does not happen then it means if there is none of these then it means there will be some number only then simply start.ush will push hd dot start.ush will push hd dot start.ush will push hd dot but remember if there is internal group in the stack then s2i will be pushed n this thing is clear Top will be my result, okay, now what is left, let's write the operate function, okay, this is simple, this is also the end operation, what is it taking, brother, in A, it is taking end B, and the string is taking token, right? Okay, this is also simple, there is nothing much, what I said in this is that if ok and if it is not so then we write down the minuses for multiply, if there are minuses for divide, then A - B are minuses for divide, then A - B are minuses for divide, then A - B is ok, after that there is one. Done in multiplication what will you do so sorry let's no run great now let's submit and see I hope all should pass great c have solved this question c have passed all the test cases ok this was very easy I understand now I will tell you a fancy way by which there will be no need to write such a big separate function. I can incorporate it in the map itself using a very fancy Lambda and you will also learn to write Lambda. If you want then you can learn all that stuff well. Let's learn that too, okay, then let's come to the solution. It's okay, it's very helpful, and I have given all this in my positive also. If you see, STD C Plus Quick Hill, it is my depository. Okay, go there and look at my GetUp repo, you will find it there, you have my profile on GetUp, I have given all this there, okay, I have also given an example as to which question, which Lambda should the lead get, okay, helpful. So let's learn here what not so remember that in the code we just did we saw that now we had to write a separate function in which for plus we are returning A plus B. The mines. For multiplication and division we are returning A-B. And so For multiplication and division we are returning A-B. And so For multiplication and division we are returning A-B. And so on for multiplication and division. Okay, so we know that for plus we have to do A + B. For minus we have to do A - B. A + B. For minus we have to do A - B. A + B. For minus we have to do A - B. For multiplication A * To For multiplication A * To For multiplication A * To divide we have to do B. We know that we have to divide by B. So, reduce one and make a map. I am telling you what the map will be like. Plus, what is there in the map? The map has keys and values. What happens is that two numbers B, which will take two numbers in A, B and will turn them into A + B, how lovely isn't it, and there will be a min, A + B, how lovely isn't it, and there will be a min, A + B, how lovely isn't it, and there will be a min, which will correspond to A, whatever mines, these will turn into B, and what will return will be A - B. Similarly for what will return will be A - B. Similarly for what will return will be A - B. Similarly for Multiply Individual, so now let us see how to write such lambda, so watch when I write, listen to it properly, now samjhaunga, why am I writing and what does it mean, okay, so look carefully, I have First of all, what did you say, okay, the map will be okay, remember that it was mine, okay, so what is the camera, it is a string, okay, it is clear even here, it is clear, after this I change the color, what did I say, the function? Right, every stinkings will be read, it is a function, it is ok, what is the meaning of function and function, how to write it, let's write like this, brother, what will return do, return will wait, that is ok, what will it take in parameter, will it take hint and brick, neither is that what I have written, so this is I have defined the function till now it is clear, ok, let me put the function, ok till this point it is clear, it is equal, you are ok, I am defining what was the first, my key value will be, started the bracket here Ok and What will this return do? Return A plus B was so simple, okay and what will it do here with these two numbers and which number to send A and also, this will give my result A, simple result, let's try it once, okay. So look, this is what we had written, what did I say, I am going to remove the operator, okay MP, which token is running brother, which operator is there for that, what else am I sending A B, that's it. Now I just define the MP underar map in it, see how simple it was, okay, what was the extering in which the operator you are using and the confirmed value of the string is a function, isn't it? What is the prototype of the function? Wait will return and what will it take in the input? Will it take two numbers of parameter A B? This is the function ok. I am also the first element of the map. Plus plus Return A minus B. Have we made any mistake? Multiplication has been done and divide has been written. Remember in multiplication, I had said that by doing the type as, just avoid other overflows. I hope that we have written everything correctly. Let's see and run. Let's see, it is a bit ok. Have passed all date is cases and see have solved this question with very fancy method ok see my pearl is that I can teach as much as I know so this is a good thing which I thought I should tell you my thoughts I have spread it as well, the more you learn, the better it is for you, and if you want to see more such lambdas and understand with a simple example, see, this was a simple example, so don't do anything, just go in the getup, okay, mine. Go to the place where there is rape, sorry, I have given a lot of things, look below, writing Lambda for an order map, you make life simple, don't you see, this is what I have told you, okay, I have also given questions, if I get more, I will update more. If you get questions like this then I am fine but you should come, I have given many such questions, I have also told in the lead code what happened to him in which question, see here, in two questions he has happened, this one, Lambda, this method, whatever. If yes then brother you will learn from here go visit here ok I am there I was able you help any doubt please reside in comment section ultra next video thank you
Evaluate Reverse Polish Notation
evaluate-reverse-polish-notation
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). Evaluate the expression. Return _an integer that represents the value of the expression_. **Note** that: * The valid operators are `'+'`, `'-'`, `'*'`, and `'/'`. * Each operand may be an integer or another expression. * The division between two integers always **truncates toward zero**. * There will not be any division by zero. * The input represents a valid arithmetic expression in a reverse polish notation. * The answer and all the intermediate calculations can be represented in a **32-bit** integer. **Example 1:** **Input:** tokens = \[ "2 ", "1 ", "+ ", "3 ", "\* "\] **Output:** 9 **Explanation:** ((2 + 1) \* 3) = 9 **Example 2:** **Input:** tokens = \[ "4 ", "13 ", "5 ", "/ ", "+ "\] **Output:** 6 **Explanation:** (4 + (13 / 5)) = 6 **Example 3:** **Input:** tokens = \[ "10 ", "6 ", "9 ", "3 ", "+ ", "-11 ", "\* ", "/ ", "\* ", "17 ", "+ ", "5 ", "+ "\] **Output:** 22 **Explanation:** ((10 \* (6 / ((9 + 3) \* -11))) + 17) + 5 = ((10 \* (6 / (12 \* -11))) + 17) + 5 = ((10 \* (6 / -132)) + 17) + 5 = ((10 \* 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 **Constraints:** * `1 <= tokens.length <= 104` * `tokens[i]` is either an operator: `"+ "`, `"- "`, `"* "`, or `"/ "`, or an integer in the range `[-200, 200]`.
null
Array,Math,Stack
Medium
224,282
1,975
hi everyone it's sorin today we have a problem when we are given n to n Matrix and we can do the following operation to The Matrix so we can take the two any adjacent two elements and multiply that 2 minus one so for example in this case we have 1 - one - one and one right so we have 1 - one - one and one right so we have 1 - one - one and one right so we can take any two elements and the multiply to minus one and we are going to get a new Matrix and um also we need to our goal is to maximize the summation of the Matrix elements so for example we can do that any number of times right we can do that operation any number of times so for example we are doing here we are doing it here twice first we are multiplying these two elements now we get the one and the minus one and we are then multiplying these two to minus one and we are getting the ele we are getting our sum is four the maximum sum okay let's take a look at this example the approach that we are going to use here is a gedia approach so we are going to use a gedia approach so let's take this example right so what is the maximum sum that we can get from this Matrix so by requirement we can multiply right that operation of multiplying two cells to minus one is two adjacent cells to minus we can do that number of times any number of times right let's say that we choose first multiply these two right these two to minus one it becomes + 5 this one minus one it becomes + 5 this one minus one it becomes + 5 this one becomes minus 4 and now we are multiplying these two so it becomes Plus+ 7 + 4 and plus 7 right and we are Plus+ 7 + 4 and plus 7 right and we are Plus+ 7 + 4 and plus 7 right and we are just getting the sum of all the sum of the Matrix so what's that mean it means that if there are two right doesn't matter in which location so it they can be here - 7 and - 6 so it they can be here - 7 and - 6 so it they can be here - 7 and - 6 right so we can for example multiply these two elements then multiply these two elements and finally multiply these two elements and get all them positive so it means that if we have even number of right if we have even number of elements right then in that case we can just take the sum of our Matrix right we can just summarize our Matrix so what we are doing here we are going over our Matrix and we are counting the number of negative elements right negative elements so we are counting the number of negative elements if the number of negative elements right if they are even what we are doing in that case we are just uh we are just the summar they taking the absolute value of each element and returning that the absolute returning the sum of the all elements because doesn't matter in which locations right they are located our minus so we can be because we can do minus multiplying to minus one we can do number of times right so we can always make that positive we can always make these two elements positive so we are returning the sum of our Matrix but what in case if it's not even let's say that if it's odd right if it's odd what we are doing in that case so basically what we can do we need to maximize our Pro we need to maximize our sum right so what we can do in that case we can find the element that is the minimum element so for example in this case is two right because it doesn't matter like we can for example let's say that um we have one more minus here let's say we have one more negative element here let's say one more negative element so we have for example let's say we have - 7 - 6 and uh example let's say we have - 7 - 6 and uh example let's say we have - 7 - 6 and uh we have minus5 right so we can again we can make these all these elements positive but the during that process one of the element we will have one negative element right doesn't matter how many times we multiply at the end we are going to have one negative element that negative element in our case if we want to make our sum maximum so we are taking the minimum element right so in our case the minimum element doesn't matter the absolute minimum element so regard of is it positive or negative if it is meaning like that we are taking the absolute value of five absolute value of seven absolute value of all elements in that case the minimum element is two right so what we are doing in that case if our so we are going over our array the first step right we are counting the negative elements if the negative elements are even then in that case we are just returning the sum of the all values Absolut abute values right if it's OD in that case we are choosing the negative element as we go over our uh as we go over our Matrix we are maintaining our negative element our minimum element and we are substracting the that element we are subtracting the value of that element from our total sum and uh that's how we are getting the maximum sum in this case Okay uh first thing to do let's create an actually let's make it long because our total sum can be overd done range of the integer so let's call it total sum right total sum let's for now set that to zero also we need to maintain the negative sum right how many negative numbers we have negative numbers actually negative numbers and let's also set that to zero and also we need to a minimum number right minimum number by absolute value in our two- dimensional array in our two- dimensional array in our two- dimensional array in our Matrix so minimum number let's for now set that to integer max value right max value okay now we can go over our array our two dimensional array over our Matrix and uh and add the total sum and also count the negative numbers so let's do that so in X is equals to Z x is less than Matrix length and also x++ it's our xaxis and also we need to x++ it's our xaxis and also we need to x++ it's our xaxis and also we need to do the exactly the same for our y AIS let's just copy paste P that here so y AIS and Y and zero here right zero and Y okay so what we do first let's check that if our Matrix if our X and Y right if at that position if the value at the position if it is less Les than zero if it's negative if it's less than or equal to zero then in that case what we do we are going to increment our negative numbers right negative numbers we are going to increment the value okay and also we are going to add that to our total sum but we are going to add that by the ABS absolute value right because it might be also negative so absolute value of we are taking the absolute value of Matrix X and Y so we are taking that element and the taking the absolute value of it and the next one is we also need to update our minimum uh minimum number so minimum number in our case we are going to take the math minimum of our minimum number and by absolute value math absolute value of the of our Matrix X and Y okay so after doing that After exiting this Loop we have a total sum and what we need to do we need to first check the negative numbers right negative numbers we need to check that the if it whether it's even or not so we are taking the modul of two right modu of two if that equals to zero it means that it's even in that case we are just returning our total sum if it's not it means that we have odd number of the negative numbers so in that case we need to subtract the minimum number from our total sum right so we are returning our total sum returning we are returning our total sum minus our minimum number multiplied by two why multiplied by two let's say that we have added that number right we have to subtract that number and also we have to let's say that we have our minimum number is minus two but we added already two to our total sum we have to subtract the two and we have to subtract one more time because it's because of the negative uh minus 2 all right uh let's run it numbers all right great it works as expected let's calculate our time and space complexity what's our time complexity is of um our rows multiplied by our column so size of our rows multiplied by size of our column and uh how about the space complexity space complexities we don't use any space here so it's constant okay um that's it for today hope you like my content if you like it please hit the like button and subscribe my channel see you next time bye
Maximum Matrix Sum
minimum-distance-to-the-target-element
You are given an `n x n` integer `matrix`. You can do the following operation **any** number of times: * Choose any two **adjacent** elements of `matrix` and **multiply** each of them by `-1`. Two elements are considered **adjacent** if and only if they share a **border**. Your goal is to **maximize** the summation of the matrix's elements. Return _the **maximum** sum of the matrix's elements using the operation mentioned above._ **Example 1:** **Input:** matrix = \[\[1,-1\],\[-1,1\]\] **Output:** 4 **Explanation:** We can follow the following steps to reach sum equals 4: - Multiply the 2 elements in the first row by -1. - Multiply the 2 elements in the first column by -1. **Example 2:** **Input:** matrix = \[\[1,2,3\],\[-1,-2,-3\],\[1,2,3\]\] **Output:** 16 **Explanation:** We can follow the following step to reach sum equals 16: - Multiply the 2 last elements in the second row by -1. **Constraints:** * `n == matrix.length == matrix[i].length` * `2 <= n <= 250` * `-105 <= matrix[i][j] <= 105`
Loop in both directions until you find the target element. For each index i such that nums[i] == target calculate abs(i - start).
Array
Easy
null
47
um hello so today we are going to take a look at this problem called uh permutations with duplicates so what this problem asks us to do is to return all possible permutations of a list of integers that may contain duplicates so for example here we have a list of integers two to three and we want to return the all the permutations but without duplicate all unique permutations so for example here we get two three two we don't get these two twos here we don't permute them and get two permutations that have the same um organization of numbers right and so this is what we want to do so let's see how we can solve it um okay so let's see how we can solve this problem so let's first pick the um the example that we have so that's two three right so usually with permutation here um if we want to solve it right we can choose a number fix it and then permute the rest and do that again recursively um and this is one of the famous um backtracking problems so we just apply backtracking template to solve it um if we take a look at this if we just do the normal permutations without like doing something smash special for the duplicates with fixed 2 and then permute and then add to that the permutation of um the permutation of two three right so that if we can recurse and then do that one but that would be two three and then three two right so this would be fixing the first two and so this here would give us with that we would get two to three and then um two three two and then we'll do it again but this time fixing this two instead right so that would be 2 here plus permute the rest which is 2 3 again so you can see this will give us the same result so this would give us 2 3 and then 3 2. and this way we'll get as well the same permutations right so you can see here if we just do it in the same way that we do normal permutation we'll get duplicates right so we'll get this one here duplicates right and the same thing for this one here this is a duplicate as well right so we can't do just the normal um and if of course if we just continue here this would mean that here we would get three and we will commute to two and you can see here as well we'll get two and then two again right and so this here will give us three two so again we'd have duplication one more time right so um and so how can we avoid this duplication right so um and one thing that with this problem is that the original array is not sorted right the original array called nums is not sorted if we suppose that our input is nums so we might get something like um three two four two so we still have duplicates but we uh but it's not sorted so what we can do is very simple right so the main problem here is that when we process it two we processed another two after it so what we can do is just when we have encounter a number just process the first occurrence don't process the rest right so this is the main key idea for this is when encountering duplicates process only the first one or you could decide to process only the last one and skip all the first ones whichever one you would do it the main idea is to process only one of them and here processing means just doing this operation here taking it and then doing the permutation for the rest that's what we mean by processing so processing here means take the element in the chosen permutation and permit the rest right so we so this is what that means so what this will mean is that we won't do this step here we want to do it right so we will scratch this which means we won't get to have these duplicates so great we have two three two those are unique and then here even also in the recursive solution we'll process only the first one and we'll not process this one right this one we won't process it and that way we could remove we would remove this as well and so with we're doing this operation by skipping the by skipping these um duplicates here we can just end up with um we'll end up with the following so this here will end up just with two three two and three two which is the unique all the unique combinations here all the unique permutations here um okay so what this would mean is that the step one for our algorithm to be to easily be able to skip if we encounter an element here we don't want to have to look through the entire array to find it and that would be often right so we can just sort the array first that way we could have the elements that are equal close to each other and that way we could just to check if an element is equal like if it's if the previous element of an element is equal to it then we can skip it right so basically what we will do here is that for three two four two for example we will source it three two sorry um so if we sorted it will be two three four so what we can do here is that just we encounter this element so we process it but then if we move to the next two we check before so if before it which means here let's say i if nums of i minus 1 is equal to the numbers of i that means we just skip because we already process so we don't process i because we already processed i minus 1 that is equal to it right so this is the main idea so we do the same permutations with the for the normal permutation except if we encounter an element that is equal to the previous element we skip it so that we don't get duplicate permutations um and that's pretty much it so let's write this down so this would be stations with duplicates and we'll get an array um so with backtracking we need um two things we need a couple of things here let me write them down here so we need what is our state that we are going to handle which is why we are going to pass as a parameter to the recursive function the backtracking request a function we need the base case and then we need a couple of other operations which are the like the core of the uh of the backtracking solution so what are the choices that we are going to make and for each choice we need to decide to do what is the choosing step like how are we going to accomplish choosing so choose and then what is the explore stuff this would be the recursive call and then what is the intros step which would be just reverting the two step right um and that's pretty much it so what is the state here so for permutations in general every at every step what we need is so for example let's say if i have one two three right what i know here is that well i haven't chosen anything right my current permutation is empty so let's say this is this color here is permutation or chosen permutation right and then let's pick another color here let's say for example maybe this one here this is the remaining that the remaining element in the array that we haven't chosen yet so at this step we haven't chosen anything so we have the entire array because the info like for example here when i pick two i want to be able to just pick from two and three and if i pick um three here then i should be able to choose just from the remaining two right so that's the main idea here and so from that two to three well i have a couple of choices uh i said well i will skip through over the next one right but here the remaining element would be so here i would have this right and then the empty it's not the empty list so here i choose let's say two so if i choose two here what this would mean is that i have chosen two so the chosen array contains two and the remaining are just two and three right and in the since i skipped the second two i don't have a path for it but i should have a path for three so the chosen now contains three and the remaining are just two right um and so i continue again here um so continuing again here um so i choose only from the remaining right and so i have two possibilities two or three right so either two or 3 so here the chosen is 2 and the remaining is just 3. and here i choose 3 so the chosen is 2 3 and the remaining is 2 right and so we keep going and then here we have only one choice left which is taking three and so chosen is two to three and the remaining is empty and i'm done right and now i go here again i have only one choice which is two and so my chosen would be two three two and the remaining is empty so i'm done so you can see whenever the remaining is empty i'm done and then here i have two choices i can have the pick but since i'm doing um with duplicates so i skip the second two because it's a duplicate right so i do only one so here i have just two um and that would mean that the chosen is three two and the remaining is two and so here i have only one choice which is two so i get three two and the remaining is empty and so i'm done so you can see we got the three two by just doing the same the idea here of skipping over the duplicates and doing the permutation and so just looking at this at every stage i needed to know what i have chosen so far and the elements remaining elements that i need to choose from right and so to do what this would mean here is my state is two things the remaining elements and chosen permutation so far right and what is my base case you can see here i ended processing every time the remaining list became empty so here what we can say that this is if length of remaining is equal to zero and in python we can just say not remaining in this case now for each case for each choice what did i do here so for each choice i took the element and i added it to chosen array right the red one here to the chosen permutation and so what this would be in here is that the step that i would need to do for choose is well take chosen and add in python that's append the number right and what else did i do so when i chose 2 i added to the chosen but i also removed it from the remaining because i can't pick it again right so i will need to remove it from the remaining which means here i will need to do remaining that remove the number um let me just give some space here so then we have explore and then we have and choose here okay so how can i explore explorer is just recursing what we did here which is just passing the state to the helper function um that has the two parameters so the recursive helper function so this would be we would pass the remaining and the chosen permutation so far right and the entries is just reverting the um true step so for choose chosen um what the element that we added here that's the last element that was added so we can just use pop to remove it so that would be chosen.pop that would be chosen.pop that would be chosen.pop and for the remaining that's just removing the element so suppose the choice here is i we have i and we have the number right so what this would mean is i could just say remaining that remove or that insert so i removed it here so i need to insert it right so this would mean insert it at position i insert i num right and so here i these are in the enumerate so these elements are in the remaining right so every time every choice i make it in the remaining um list as you can see here 2 3 i made choices 2 and 3 from the remaining list right and so what this would mean is that i and num are in the remaining array and that's pretty much all i need for my back tracking solution is to come up with these states uh with these values and so now i can just write it down so the first thing i need my recursive function because it has two different sets of parameters remaining in shows and chosen right so let's just write that down we need two things helper needs remaining and chosen now i could write my base case which is if not remaining which means remaining list is empty what do i need to do i can just have an array right i will define the initialize that array later on let's initialize it down here so and launch the call to helper so initially the first helper call remaining is all the elements in the array and chosen is an empty list and at the end i could just return the areas and so here if not remaining i can add the element i can add the chosen permutation to the list of permutations so that would be just append chosen um and then here one thing to note is that i want to solve the array first before passing it to the helper function right because my arrow assumes it's sorted and assumes um to every equal elements are next to each other right so that would mean that here i would need to sort the array then called the helper function with the remaining being the numbers and the chosen is empty for now and then we return res now in the else case here what do i need to do so in the else case the first thing i need to do is go through each choice so i can do four i num and numerate of remaining what do i need to do for each choice first choose then explore then and choose so for first the choose portion i will need to show add chosen add the number to chosen so chosen that append num then i will need to remove it from the remaining elements right so what that would mean is that remaining remove the number then i will need to explore and so exploring here means i'm calling the helper function again with the remaining and the chosen then after that i need to unchoose right so unchoosing means reverting the chosen operation here so that would mean chosen the pop and then after that i will need to remove the element from the remaining and the element was at position i so i can just insert to the back right so what this would mean is i can insert back in remaining um at position i insert the number and that's it i'm done so that's the only two the only uh steps i need base case go through the choices choose explore um and then um insert so this is the just the normal uh backtracking right but i didn't do the uh skipping over the next element skipping over this one like here i didn't explore two right i didn't explore two here so i need to do that here right so what this would mean is that before uh so i need to kind of remove this so that i can do it so before exploring checking if the number at position i minus 1 is equal to the number at position i need to skip it and skipping it here i can just do continue so here i just for i minus 1 to be correct i need i to be bigger than 0 right then continue but otherwise we can continue and do the choose and choosing step so that would mean lost writer again chosen that append number and then with the remaining remove the number and here you could see we skipped the next element if it's equal so we want to explore this two here same thing here we want to explore this two here would explore it only once and so um after that we need to call the helper so helper with remaining and chosen and then we could and choose and with that will be done so let's try this again chosen that remove that pop right to remove that element and then the last step is removing from the remaining sorry inserting back and remaining and that's pretty much it and so the main difference between this and the normal permutations without duplicates is this step here um and uh yeah so that's pretty much it so again um template of backtracking um and then sometimes you need a modification to remove some choices because the um the num the choice because the um the enumeration that we are looking for as an extra um an extra constraint um and so two things here we added is the sorting so that we can have the elements that are equal next to each other um and then this here and since the number of permutations that we have anyway are n factorial at most doing an overlap and operation here to sort that's really nothing compared to the n factorial and so this is definitely worth it right um okay so let's go this upfront on some examples and make sure it works um okay so i wrote down the solution that we just saw in the overview um and so we get a number a list of numbers um and that may contain duplicates and so here we just define like um we actually don't need this just need the list and then we solve the array right and then we call visualize the call to our cursor function that has the two states the remaining number of elements and the chosen permutation the currently chosen permutation and if we reach the base case which means the remaining list is empty we add the permutation to the list of permutations we just copy it here this is equivalent to doing copy and we are doing this because later on we modify the chosen array um and chosen modified here by popping the element and so we don't want that to affect the reference to this list that we already added um because that's the final permutation and so we copy it so it doesn't get modified later and then we go through all the choices um we remove here the we don't process the duplicates right so by checking if the previous element was equal to it that means we already processed i minus 1 um if it was the first occurrence of the element and then we would skip the next one so always we process only the first occurrence of a number and we ignore the um the equal numbers after right and since we are we sorted the equal numbers are next to each other right and so we do that step the additional step here and then we do the inch the choosing step which means adding to the chosen permutation and removing from the remaining elements we explore by the cursing on the uh recursive function here and then we and choose by removing by reversing these two um two steps of the choosing uh operation which are which means here we pop so that we remove the latest added element which is num here and then we insert back into remaining because we removed it here and the index was i because we are going through the remaining here so we just insert it back um so that's the main idea i have here two examples that we can run it with and so let's just run it so for two three we got two three two so that's that works um same thing with truth three two three four so we source it first and then we didn't get any duplicates um yeah so that's the main idea behind this um there is slight optimization that we can do here which is we don't actually need to do this step explicitly we can just do it in the parameter here and if we do it in the parabeta we don't need to do this either so we can just comment this out so first let's just do the chosen so instead of doing instead of adding and removing it we can just pass a new list that has the stator that we want right and so i can simplify this for the remaining instead of removing it and then um so i removed the wrong element i should remove this instead of this and so here for the remaining instead of removing it and then inserting it back we can just pass a list that doesn't have the element and so a list that doesn't have the element means we just take everything before i and take everything after i right and so that would mean we no longer need these two either but it's always good with backtracking to write them down um just so they can get used to the pattern of choosing exploring and then choosing and yeah so that's pretty much it so let's run this again so still um we have the same results um yeah so that's it pretty much for this problem um thanks for watching and see you on the next one bye
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
1,706
welcome to Lakewood JavaScript a channel where we solve every single little question using JavaScript today we have 1706 where will the ball fall this is a medium question um the implementation really isn't that difficult but it might be a bit harder to understand initially so let's begin we have a 2d grid of size M times n representing a box we have M Bose the Box stop being brought at the top and the bottom and each results has a diagonal board that makes it will fall either to the right or the left and we're going to represent slanting to the right with one Atlanta with Mark negative one and we want to know whether our roles actually hit the bottom and fall down and there are two cases where this doesn't happen one is this v-shaped doesn't happen one is this v-shaped doesn't happen one is this v-shaped butter that we see over here and the other one would be hidden a wall for example if this was nothing to the left this ball would just hit the wall and would never fall um and we want to return an answer of size n which is an array where our answer I is the column that the ball falls out of at the bottom and we represent one if it does and negative one if it does not um so again just so we're super clear uh we have slanting that can occur in either direction and we just want to follow the part of each pole and see whether if you eventually reach the bottom and assign that value to one and negative one if we do not reach the bottom and in this case only this ball which is so we have one and the rest is negative one now we're gonna use that for search the for this problem because as you can see we just gotta follow are both too older than it goes and that's how we're gonna find out whether or not we get what you want so let's start by initializer answer and that's what's going to be a new array upsize grid zero dot length and that means how many columns they are there are and since this numeric we're going to fill it with zero is something which you do in JavaScript because it's not initialized to any particular value at the beginning now we need some sort of the first search this is actually create a line in an inner function for that um could simply do some black concept of research and how are we going to do that we are concerned with I and J as the coordinates and there's nothing else that we're concerned with given the grid that we already have we just want to know what I and J and one asset that we actually reached the bottom but that's relatively simple we reach the bottom when I is equal to grid that length meaning reach the bottom when we find I is it the last row and in that case we just reached the bottom and in that case we can return J or we can return one doesn't really matter now we gotta check when we actually have either a collision or a b shape so EJ is less than zero or J is greater or equal to Great zero that length well in that case we're just going to turn negative one meaning if we hit a wall in other side we just return negative one because we know we're not gonna find the end now here's one because maybe a bit more complicated um we're gonna do this for both sides and what's up with IJ if that's equal to one meaning if it is landing to the right then we're gonna if that's the case we're gonna check with J plus one is less than root zero deadline Central double checking we don't hit any wall and then we do add grid i j plus one because if we're planted the right we're gonna drop down row but we're also going to move one column to the right so it's going to be I and then it's gonna be J Plus 1. well in that case that's if that's also equal to one then we're gonna have a little precautious recursive set I mean return DFS of I plus 1 again move one to down and J plus one to the right um now we'll actually repeat this um we can do this with else f green i j does equal to negative one minimum if it's landed to the left and sorry and J minus one is greater or equal to zero it was led to the right left and we don't hit the wall and grid I and J minus one is equal to negative one then we're gonna return DFS of I plus one that's gonna be one down and J minus one that's going to be also one to the left which is J minus one and I really guess we're going to a negative one and the reasoning is relatively simple we simply check whether we have a space to go down because if these conditions don't do not apply that also means we have a v-shaped that also means we have a v-shaped that also means we have a v-shaped pattern in that case we cannot go down because we just get stuck there now once we have the resource function the rest is super simple we're going to do a for Loop start with J equal to zero and J is going to be equal to grid zero that length and we do J plus and now we're simply going to assign ends J to DFS of zero comma J and what does this precisely mean so we're iterating through the first row essentially and we're also going to start always going to start row zero and we're just going to be dropping from zero both in column zero one two three and so on so forth so that's where we place zero here and the J there finally we're going to return the answer array and we're going to use the initial test case to see how this is going and we're accepted let's submit this and there we go this is quite a fast Solutions faster than 76 percent of JavaScript online submissions and thank you very much for watching don't forget to like And subscribe
Where Will the Ball Fall
min-cost-to-connect-all-points
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._ **Example 1:** **Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\] **Output:** \[1,-1,-1,-1,-1\] **Explanation:** This example is shown in the photo. Ball b0 is dropped at column 0 and falls out of the box at column 1. Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1. Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0. Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0. Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1. **Example 2:** **Input:** grid = \[\[-1\]\] **Output:** \[-1\] **Explanation:** The ball gets stuck against the left wall. **Example 3:** **Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\] **Output:** \[0,1,2,3,4,-1\] **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 100` * `grid[i][j]` is `1` or `-1`.
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
Array,Union Find,Minimum Spanning Tree
Medium
2287
507
that is equal to the sum of its positive devices excluding the number itself a divisor of an integer X is an integer that can divide X evenly so given integer and we can prove if it is a perfect number otherwise rate of false so what do you mean by perfect numbers you have given a number and we have to check whether the sum of all the devices except that number is equals to m in given number so what do you remember the devices of r28 artists plus and printed also our device eraser so accepted 28 if you sum up all the numbers and if it is equal to 28 then you return equal to 28 minutes so in this case when I get the devices are um one two four seven forty so if given number is 28 devices are 1 2 then 4 then 7 then 14 then 28. but they have said a perfect number is that is equal to sum of its positive devices excluding the number itself so exclude this number that is supposed to write if you add this number of course the sum won't be equal to the given number because it will be more than the Giveaway number so excluding the number if all these sums all this sum if it is equal to the given number then you write them if it is not equal generator false of a number so one thing uh you know is that usually let's take an example of 16. so what are the devices of 16 it's a one then two is a divisor 16 3 no 4 is final six no seven or eight years then 9 10 11 nothing is directly 16. so these are the devices so accept this you have to sum up these four so eight plus four will be 12 13 14 15 it will sum up to 15 so it's not a divisor so how do you get a number is a device or not one thing is we can run from for I equal to 1 to I lesser than naught equal to n if you Traverse this and check whether n modulus I is equal to 0 then you add that to the sum but this will take a lot of time you can cut down this for Loop by half of the time how do you do that so you know the square root of 14 what is it right so we'll write this fact the second devices again so for one if you take one how much the 1 into how much will be 16 1 into 16 will be 16. so next comes to 2 how much will be 6 into 8 so 16. then divisor is 4 into 4 is 16. then after 4 it is 8 into 2 is 16. then the last 16 will be the one is 16. so if You observe if it is one the 16 we have obtained how do you operate 16 this is 16 by 1. here it is 16 by 2 if you do that will give you 8 and how it will give 4 16 by 4. how will it give 5 16 by 5. sorry 16 by 8. and how will it give 1 16 by 16. so what all the numbers divided by this I the number by I so if number of modulus I equal to 0 one divisor will be 5. other devices will be number by I so it will take 2 here now 16 module is 2 equal to 0. so one divisor will be two other devices will be 16 by 2. that is how much it so there is another two numbers you can add these two simultaneously so if You observe the above this part and below this part RC so you can develop this you can compute here itself both 162 radical computer itself is I is equal to zero then I comma M plus uh number I will be added to this one so this these are available when you come to this you cannot add four plus four I comma I plus num by I that is I is not equal to number num by I so in our case one is 90.602 is not so in our case one is 90.602 is not so in our case one is 90.602 is not equal to eight so in that such case number otherwise what you do you add only I so if I equals equal to number I you add only four like you add only plus I some plus I U if it is sum is the total sum then some plus I go so after doing all this sum so how what is this what whole is nothing but the square root of the given number until this is otherwise num by 2 also you can do let's call it of your number is best so after a class you have to say butter this sum is equal to the given original number if it is equal then you return to otherwise Direction yeah this is fine so now we will code this now before coding one more thing which you have to notice is they have told that we have to exclude the given number so here the given number was 16 and we have to exclude 16. how many x equals 16. for that ux exclude this Loop itself you start loop from for I equal to 2. till I less than equal to square root of M now so if we start from here we'll exclude abnormally the another divisor so we are but you have to add one right so you do some initialize it to one itself in the beginning so that this will be excluded and this will be added so we'll start from Loop here it will move it here so these two will be added and this will be added this one right that is how you solve it so initially what is the number is one what if the number is one then that cannot be a perfect number because they have to sum of all is positive device excluding number itself if the number is one we have x squared one then there will be any divisor for it no that will be 0 then 0 it won't be equal to so you written points okay now equal to 0.1 so written points okay now equal to 0.1 so written points okay now equal to 0.1 so you directly return false square root also we will uh insurance so let's say this because sqrt is a NBA function is now traces that will be mat dot square root of how much so now run the follow for this right now I equal to because one we have some added over here and that number will be excluded so I equal to 2 then I less than or equal to square root then I plus you could use SQ art itself because mat dot square root is working in Java only the square root won't work so but still will not use it so now we have to check if num modulus I equal to zero then we have to add that new sum so sum plus equals to I again after this you have to check if cell should be inside right so after this you have to check if I is not equal to sum by I then you have to add number I also so some s equals to multiply I will just give a bracket Now by e button so I will always be added we'll add number is so here 4 is equal to 4 so if such is equal to number so we will not add number will not include the other four all four will be so this will mod this included and this will be include only if I is not equal to the number so that's it now at last you return the sum foreign false if you understood the concept please do like the video and subscribe to the channel and keep learning thank you
Perfect Number
perfect-number
A [**perfect number**](https://en.wikipedia.org/wiki/Perfect_number) is a **positive integer** that is equal to the sum of its **positive divisors**, excluding the number itself. A **divisor** of an integer `x` is an integer that can divide `x` evenly. Given an integer `n`, return `true` _if_ `n` _is a perfect number, otherwise return_ `false`. **Example 1:** **Input:** num = 28 **Output:** true **Explanation:** 28 = 1 + 2 + 4 + 7 + 14 1, 2, 4, 7, and 14 are all divisors of 28. **Example 2:** **Input:** num = 7 **Output:** false **Constraints:** * `1 <= num <= 108`
null
Math
Easy
728
368
hello everyone this is DSS zindabad let's talk about the daily challenge for today on code so the problem given to us as largest divisible subset let's jump into the problem statement given a set of distinct positive integers nums we need to return the largest subset answer such that every pair that means answer I comma answer J of the elements in the subset satisfies this condition that means if you take the Modelo of the two elements right they will be equal to zero that means they're multiple of each other okay so if there are multiple Solutions we can return n so basically this problem statement is saying that you will be given something like a vector num it has it will have different values right suppose these are the different values that this Vector has so what I have to do is from this Vector I need to figure out the largest subset right now basically when you talk about a subset it is not Contin in form so that means you can skip certain elements so what I need to do is I need to find the largest subset now how I need to figure it out it needs to satisfy a particular condition that is that one element for example there were just two elements in my vector or we can say in the largest subset I was creating right so if I take a modulo I'll get a zero right so that means that these are multiples of one another and I need to return the largest possible subset I hope the problem is clear right so now let's talk about its approach considering this example what I can see is that see for me to figure out at any point of time which will be the largest subset I need to know that what all elements El can come together right so what all elements can come together so that means I should know the multiples for each element in the array okay so when we do that I need to make a choice that means if I am constructing a subset which will satisfy the above condition right and figuring out the multiples I need to make a choice now how do I need to make a choice the choice will be at any point of time should this element be added into the subset or not so I'll have two choices that is you can either take the element or you can not take the element sounds familiar yes it is recursion now alongside this the first step that you need to take care of is before making these choices you need to sort the given array now why do we need to sort the given array it is because see when you'll be making this choices the end goal is to find the multiple of a particular number right so what happens is each time when you're making this Choice it will be dependent on a condition right and that condition says that you need to use a previous element so that you can keep a track of what all is added into your subset for example let us suppose I had something like 1 2 4 and I'm standing on8 now for me to know that does this eight Al is also multiple of this subset which has been created I need to know the previous one it is easiest to know the previous one right so you will be maintaining a previous now why does it need to be sorted is because suppose I had something like it was not sorted I had 4 2 1 and here I was standing on the third index I had to figure out uh the this element that has a value three now if one is the previous in this case you see one modulo 3 will give you zero but if you'll say four modulo 3 that will not give you zero right so that is why we need to S the given AR I hope it is clear I'll quickly write down the approach the first step is to sort the given array as soon as you've sorted the given array the Second Step that you will be doing is you'll say I have to use recursion right wherein I'll have two choices to take or to not take and while I am figuring out these choices I'll be maintaining a pre element for understanding that does the particular element I'm standing on belongs to this group or not okay so I can say to check the belongingness for an element to a group and this belongingness basically depends upon is this element a multiple of the subset or not okay I hope the approach is clear to you let's quickly code this up and then we'll talk about its time and space complexity okay so this is the problem statement so what I'll do is I'll quickly first say let's sort the given Vector that has been given to me right so we'll use the STL function and after that okay so once we have sorted the given and right which was our step one so after sorting I need to what I need to do is I need to use recursion right so for that purpose what I'll do is I'll create a function right let's call it solve we'll pass in the current nums Vector that has been given to us I'll pass in the current index we're standing on let us assume we're standing on the zeroth index right now as I told you we have to take care for previous so in this case I'll pass previous as one and now as you can see final answer that needs to be return should be of type Vector in so you can have something as Vector in um supposedly let's call it um temp right and I'm passing my 10 here now you might ask that why have we used one here in the case of previous so we have taken previous equals to one because according to mathematics one is a multiple of for every number okay so this has been done because one is the multiple for every number in the number system okay so now as I have done this I need to finally return an answer so what I can do is I can have something as see every time this St is going to be updated this will be holding my subset value that means the largest subset recursion could find so it needs a comparison right so for that let's simply create a vector int answer right it's a global vector and we'll be making comparison with this Vector right and I'll return answer eventually return answer now let's quickly create the solve function as you know that here we are basically forming something we're adding or subtracting something from a vector so the function will be of VO type solve right I'll quickly copy paste this part here then we have the index and then we have the previous and the pictor that we have created that is passed by reference yeah so now let's quickly write the code see whenever you're writing recursion is divided into three parts first one being the base condition then the recursive fall and then exploring all the possible things you can do on that recursion right so for the time being let's leave the base condition as it is we'll write it later what I'll do is I'll quickly jump onto the take and not take part so basically if at any point of time I have to take something that means I have to take that element into my subset so how will I do that I can do that if I check this one condition I say if nums of index and if you take a modulus with the previous that means there are a multiple in that case what you can do is you can push this element into the temp which is maintaining the current possible subset which has which satisfies the following condition so this will be num's I right else once you've done this you'll go to the next element so you'll say solve right and you'll just pass nums index will be implemented because we started from zero previous will get changed now previous will be what we were currently standing on that is num's I and temp is also passed after that once this call is completed right we've reached the very end after that what we'll do is as discussed we'll pop this element we'll say suppose this element was not taken then right so after this we'll go to the not take condition we in I'll quickly copy paste this only here the previous will not be changed so though we are incrementing by one index the previous remains this same why because it is a not take condition okay so now as we've written the recursive code of take and not take now let's talk about the base condition see basically you'll reach the base condition only when at any point of time your index becomes greater than what is the size of the given Vector that is nums do size if this happens what you can do is you can simply compare that is the current temp which you were building which was storing the possible largest sub that which satisfies this condition that is its size greater than what is the size of the global Vector that we've created that we'll finally return and if that is the case you simply say that answer is equals to 10 and you return okay I think we're good to go let's quickly run and check once okay yeah because we have used index here so let's write index quickly I think we're good to go and it is running fine this was the example that we taken right uh if we submit it we'll get a tle so let's quickly submit it and see it is taking some time yeah and see we got a t that is because the present code has a Time complexity which is exponential in nature now let's quickly copy paste this code have a dry run discuss its time and space complexity and how we can optimize it so basically this was the code that we were working on right and we know that this is a Time complexity issue so let us have a dry run and understand how can we possibly have an optimization for it so let us assume the nums array that was given to me was 2 1 C 5 6 4 and 7 right so this is what I have right now 0 1 2 3 4 5 6 Seven Elements so I'll start from here first this will get sorted so I'll have 1 2 3 4 5 6 7 I have these elements in the sorted order once I have sorted them I'll create a vector in 10 and I'll call the first function so I'll be creating both the recursion stack space as well as the recursion tree for you to understand so basically I have 01 0 is the index and one is the previous right so the base condition is not satisfied because the size of nums is seven right so uh as index is zero it is not satisfied we come to these if condition so you're standing here on the Zero index you'll say is one divisible by one is it giving zero that means are they multip Le you say yes so you'll push that in temp so now your temp has one and now you'll call the solve function solve index gets incremented index becomes one now previous is what was nums index was one right so this is the other call that has been made so basically you have S01 initially now S11 is added into a recursion stack space once you come here you'll check for the if condition index is one and the size of the nums Vector is seven not satisfied you go in this condition you are standing on two now you'll check is two divisible by the previous 3 ver 1 and the answer is true so you'll add it into 10 right now two is added another function call is made now I becomes two previous as it is standing here will become two and this call is added so you have two comma two in the recursion stack space so when you're standing here on 2 comma 2 what happens next is that means you'll see as the index is two less it is less than seven not satisfied you come here you'll say nums index so on two you get a three as you get a three you'll say is three a multiple of two and the answer is false so you'll not go in this if condition you'll come directly here and now this call is made s the previous is not incremented right that mean the previous is not changed only the index is implemented so you have 3 comma 2 so now you go to the third index the condition is still not satisfied you come here you're standing on the third index that means on four so you'll say is four divisible of the previous was two so it is it says yes you say add that into the 10 once you did that you'll have another recursion call and I'll quickly zoom out a little right you'll have another recursion call that will be S and now your index will be four and your previous will also be four so now your recursion tax base has as earlier it had S3 comma 2 right after this now it will have S 4 comma 4 and they standing here now as you can see four is less than seven if condition is not satisfied the standing on the fourth index you get a five so you'll say is five a multiple of four and the answer is no you will not go inside this if Loop you'll come here so s you'll go to the fifth index and the previous Remains the Same four as you go to the fifth index you get a six you'll say is six a multiple of four answer is no so what happens is U these all are added into the recursion tax base so here you have s5a 4 and uh on the top you have something like s 6A 4 now what happens is as this condition was not satisfied you'll come here and you as I told you this function call will be made you will check the sixth index that is seven and as seven see this if condition is not satisfied yet why because I is six and we need it to be at least greater than or equal to 7even for it to be satisfied you come in this if condition this is also not satisfied because seven is not a divisible of previous was four so this is not happening another solve call is made now here you'll see you get index 7even and the previous Remains the Same as soon as you get this right now if this is being satisfied so you are standing here now this is satisfied why because index is equal to the num size so in this case you will compare and see answer had a size zero temp had a size three so you'll say answer initially has my answer right so answer is equal to C right so here now as we've made this becomes the answer right so now my answer has this value and you can simply return it so that means you'll return back here and once you return back here as in 6 comma 4 right you had you were here only so it has completed it life cycle it will return back similarly this will return back as soon as you standing on 4 comma 4 right because in the case of 4 comma 4 you had you were standing here when the function call was made now you'll pop back the element that has been added that means you'll subtract four from here that you'll say that four is not a part right and once you have done with it you'll make another call so here the call will be going to the fourth Index right and the previous Remains the Same the previous was two so now again another tree of recursion will be developed from here now what happens is I'll say that okay as I'm standing here on the fourth index and my previous is two so I'll say on the fourth index I have a five I'll check is five divisible by two I get no as an answer and my 10th is currently 1 comma 2 right so after that another if as this is not satisfied you'll go to the other condition so this is says increment index becomes five and previous Remains Two on Fifth you get a six so six is a multiple of two so now it gets added so now temp will have 1 2 and six right and another call will be made from here you'll go to s six comma and the current element that you had was six as the previous so now as you're standing here right you'll check that is the element that means it's seven divisible by previous that was six and the answer is no so you'll simply skip the If part you'll go s you'll go and say s move the index previous Remains the Same now again you have reached seven and this satisfies the base condition it will check for this value but as you can see that temp has a value three so does answer so basically this does not get updated you simply return and this tree will be created so from this tree what you can see is at for every element you have a choice and that choice comprises of two things so you have two choices you can not take it or you can take it so because of that the time complexity becomes exponential in nature right so that is big of 2 to the power n and similarly the space complexity is O of n why because at every point of time or recursion stack space is being formed and in the worst case we can assume all the elements are there in the reion TA now whenever we have such problems what we do is we'll use something as DP now why am I saying that we'll be using dynamic programming is because if you will draw a tree a recursive tree for the above question with a smaller Vector you'll be able to see overlapping sub problems right so whenever you have overlapping sub problems you can use something as DP okay so what happens in DP is it says that once you have figured out a certain answer you will not recompute it you just simply store it in one place and once you need it use it from here rather than recomputing it from the code of life now let's quickly make the changes in the DP right that is simply by adding a DP Vector which is known as memorization nothing new is being done only a vector will be added and the tle error will be resolved okay now let's jump into the code space okay so this was the code that we've written so far what I'll do is I'll quickly create a DP Vector right and let's it will be a 1D DP right so basically I'll have something like Inn nums dot size SI n and I'll initialize it with minus1 I'll pass it to my solve function here we have the DP pass as a reference right now basically what you need to know is this DP here that we are using right I'll quickly write it here now this DP Vector it is basically stored to store the length of the longest divisible subset ending at that index okay so it is to store the longest divisible subset at that index okay so now what happens here is as we have this base condition right this base condition will remain as it is we will not change anything we'll make a minor change here right where we were checking this nums condition we'll check alongside this we'll have we'll add an and condition we'll say that if the temp do size is less than BT's Index right if this is the case then what you'll do is you'll say DPI that means that DP index should store whatever is the size of that subset that we are potentially considering to be the longest upset answer okay then you'll push it you'll call the solve function and this code remains as it is now let's quickly run and check if it's working fine I think it should H okay yeah basically we did not pass DP in the Sol function calls that we are making later let's quickly add that I think we're good to go now and yeah it's working fine let's submit it so yeah it is working fine now let's discuss it's time and space complexity so basically what is happening here is I'm using a DP Vector right and that DP Vector is basically it is used to memorize the length of the longest divisible subset ending at the index I okay and while I'm using this now my time complexity has boiled down to linear and my space complexity is also of n because I'm using an extra DP Vector right nothing has changed only we've added DP this is known as memorization okay I hope this is clear you can quickly have a dry run right basically this DP Vector at each point of time will be storing nothing but the size of the potential subset till index I right so it is really easy you can have a dry if there's any problem you can always comment and we can discuss it thank you so much for watching the video please like share and subcribe
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
349
hey and welcome today we will solve intersection of two arrays interview question this question has been mostly asked by Google as well as some other companies like so we will explore two solutions for this problem so without further Ado let's Dive In so first example here we have two arrays and we only look upon numbers that are shared in between these two there's only two in this case so we will return it as a result second example we have two arrays again but there's only nine and four shared in between these two arrays so again we will return them as a result let's see how we are going to solve this problem as of something to start with we can come up with an algorithm like this here where we literally iterate over the first array and check to see if any value of it exists in second array but we will end up with all of any Square time complexity because of for Loop and the usage of array that include in this case in order to improve this think about sorting both arrays if we sort them we can put one pointer in each array and check number simultaneously using both pointers so if two pointers from two sorted arrays will end up having same value like in this case we will push it into a result array and if not we will try as much that we finish iterating both array and finally at the end of iteration we will return all possible matches but this solution ties itself to one fundamental demand of arrays has to be both sorted because that clears the past for us to be able to use two pointer search on both of arrays and yes sorting array has a Time complexity of n log n and it will dominate or linear search time complexity in this case okay how we can improve it further to achieve all of and time complexity think about or Brute Force solution where we use array that includes for or check which was costing us an extra woven time complexity one way to convert this or event search into all one constant search is using JavaScript set if we convert or nums array into a JavaScript set in order to search for some value within that it will give us constant of one lookup type that is one advantage of using set instead of array but for that or sets we'll go into require some space so if we have each array instead we can iterate over one and look for each value of it in the other set but the point is this time it will be constant lookup not linear the solution with sets will look like a bit to the same one that we had with Bruce Force but again this time we will have all of One lookup time it is all the matter of space versus time complexity trade-off in this case if we complexity trade-off in this case if we complexity trade-off in this case if we need to save a space it will cost you a bit more time and in the other hand if you want to save time it will cost you a bit of space so let's see how we are going to implement this in code here we are in lead code for sorting solution first we need to sort both arrays like nums one that sort we are going to a b Arrow function a minus B and the same thing for secondary then we are going to need two variables for our pointers let P1 equal to zero and let P2 equal to zero then or result array let result equal to an empty array okay now we need to do our wide load for both sorted arrays while as long as P1 is less than nums one that length and P2 is less than nums two dot length if that is the case we need to do some stuff inside so we will have three possible cases if values from both array are equal if value from number one is bigger than number two or last case if value from number two is bigger than number one for first situation we need to push the item into array and simply increment both pointers because we are done with both of synthesis so we will do if Norms 1 at pointer 1 is equal to Norms 2 at pointer 2. if that is the case we need to do a result that push nums 1 at P1 since they are equal it doesn't matter if you grab the value from nums one array or nums two array and then we will do P1 plus and P2 plus for second situation if pointer bonds value is bigger than other we need to increment other pointer from other array because that is the one that currently falling behind of this numbers raised so we will do else if nums 1 at index P1 is larger than nums two at index P2 if that is the case then we need to increment P2 and finally the other way around for last situation we'll do else if Norms 1 at P1 is less than nums two at P2 we are going to increment the P1 at the end we need to return the result array but keep in mind that this array could have some 2 locate values in fact there might be some test cases only for making your logic to produce some duplicate values in your result array so we will convert it to a set and then spread the unified values from set back into a new array like return dot new set out of results so if I run this every test case is passing and if I submit we are in a good shape for set solution first we will convert both nums into their set equivalents so we will do const nums 1 is going to be new set of norms one the same thing for nums two then we will have a result Ray const result equal to as an empty array then we need to iterate over any one of those sets and check for each value inside of that to see if it exists in the other side in order to iterate over a sets value in JavaScript we can use for of statement but you also can use for each as well you will use four off so I'll do four let num of nums one for each of that inside of this for Loop we will do our constant check if nums 2 dot has is number and if that is the case we need to do result dot push no and at the end we need to return or result now if I run this test cases are passing and if I submit everything is good now let's jump back into slides for time and space complexity analysis for time complexity we will have all of n log n for sorting solution just because of sorting itself and we will have oop and time complexity for our solution bits set for space complexity sorting solution will have all of one constant space complexity but for set solution we will have all of n plus m space complexity where n is the length of our unified first array and M is the same for the second array with that I can say that was it for this video and make sure to subscribe to the channel in order to not miss out new videos I will also put the link for arrays playlist in videos description where we go through solve array problems from lead code so thanks for watching and please like comment and subscribe to the channel and finally hope you enjoyed this video and see you on the next one
Intersection of Two Arrays
intersection-of-two-arrays
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[9,4\] **Explanation:** \[4,9\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000`
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
350,1149,1392,2190,2282
1,768
hey everyone welcome to Tech quiet in this video we are going to solve problem number 1768 merge strings alternately first we will see the explanation of the problem statement then the logic and the code now let's dive into the solution so here I have taken an example so here we are given two words right word one and word two and we need to pick each and every character from word one and word two for example first I will pick the first character in word one first character in the word two I will just append them A and P right then I will pick the second character in both the words then I will open B and Q to the result string so we need to open alternatively from both the words right so this is a very simple problem so now we will see how we are going to do this so I'm going to use two pointer approach and I will be having a empty string result right also have the two pointers I and J here so first I will write a while loop I will only run the while loop until we have a valid index in both the words right so now I will pick A and P I will append that to my result empty string right then I will move my ing at the same time now I will append B and Q now again I will move my ing at the same time now I will pick C and R I will append that to my result then finally I will return the result variable and there is also another case what if the word 2 has more characters like d and e at the end if this is the case we need to append them in the last of the result string right what if I had d and e at the end of word one again I will append them at the end of the string this is valid for both the words right so I will append this using the pointers we are using ing I will show you guys in the code right so the time complexity is order of n and space will be order of n as well since we are using result variable right now we will see the code so before we go 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 will be having empty string that is result then I will be having inj pointers which will be initialized as 0 at this start then I will write a while loop I will run this while loop until it is less than the word length of the word one and word two right both the pointers should be less than the word length in both the words right then I will just append that to my result string I will just append the character in the word one and the character in the word using I and J pointers then I will just increment the I and J pointers at the same time then at the end I will just append the word one remaining characters and I will just append the both two remaining characters if there is any characters left at the end I will just append that in the end of the result string right then finally I will return the result string that's all the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting happy learning cheers guys
Merge Strings Alternately
design-an-expression-tree-with-evaluate-function
You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. Return _the merged string._ **Example 1:** **Input:** word1 = "abc ", word2 = "pqr " **Output:** "apbqcr " **Explanation:** The merged string will be merged as so: word1: a b c word2: p q r merged: a p b q c r **Example 2:** **Input:** word1 = "ab ", word2 = "pqrs " **Output:** "apbqrs " **Explanation:** Notice that as word2 is longer, "rs " is appended to the end. word1: a b word2: p q r s merged: a p b q r s **Example 3:** **Input:** word1 = "abcd ", word2 = "pq " **Output:** "apbqcd " **Explanation:** Notice that as word1 is longer, "cd " is appended to the end. word1: a b c d word2: p q merged: a p b q c d **Constraints:** * `1 <= word1.length, word2.length <= 100` * `word1` and `word2` consist of lowercase English letters.
Apply the concept of Polymorphism to get a good design Implement the Node class using NumericNode and OperatorNode classes. NumericNode only maintains the value and evaluate returns this value. OperatorNode Maintains the left and right nodes representing the left and right operands, and the evaluate function applies the operator to them.
Math,Stack,Tree,Design,Binary Tree
Medium
null
1,837
lead code 1837 sum of digits in base K given an integer n in base 10 and a base K return the sum of the digits of n after converting n from base 10 to base K after converting each digit should be interpreted as a base 10 number and the sum should be returned in base 10 so basically what they're saying is they'll give a number for example I'll take number to be say five and K to be say two k is the base so five is a base 10 number as of now okay and I need to convert it into base two how will I do that so I know binary representation of five that would be 101 right and how would I convert five into this right once I convert this I can get the digits and add them up so this would be added to 1 + 0 + 1 is equal to 2 and this to 1 + 0 + 1 is equal to 2 and this to 1 + 0 + 1 is equal to 2 and this would be my answer okay so only missing this pie now this part where I need to convert this into base 10 into binary how do I do that so if you see if I take five and divide it by two and take the remainder what do I get a one okay then I take five and divide it by two and take the flowed version of it so 5 / 2 gives me 2.5 the so 5 / 2 gives me 2.5 the so 5 / 2 gives me 2.5 the flowed and flowed version of it would be two right so now I'll repeat with two again two divide it by two and I'll take the remainder is zero right and then I'll again divide 2 by 2 so that gives me 1 again I'll check what is the remainder if I divide 1 by 2 I get one right and then I'll divide 1 by two and take the flowed value of it so 1 / 2 take the flowed value of it so 1 / 2 take the flowed value of it so 1 / 2 gives me 0.5 and the flo value of 0.5 is gives me 0.5 and the flo value of 0.5 is gives me 0.5 and the flo value of 0.5 is 0 so I've reached zero I need not go any further so in this if you have if you see every time I before dividing further if I take the remainder that would be the digit of the binary version of it similarly if I want to convert this five into base 3 I can do by three right I can divide by three and take the remainder so in that case it would be two and this would be 5 / 3 it would be two and this would be 5 / 3 it would be two and this would be 5 / 3 so that would come the flow value would come out to be 1 divided by 3 uh that gives me a remainder of one right and then 1 / 3 so I get the float value then 1 / 3 so I get the float value then 1 / 3 so I get the float value would be zero okay so in this case the digits are 1 and two okay I can add this up and return so that would give me three so this is what we can do we can simply in code how will we do it we'll take an S where we'll add up all the digits I'll carry on some operation on N until it is greater than zero so while n i could write this as while n is greater than zero or simply while n then I'll what I'll do I'll add the remainder of n percent K into s okay s is something I will be returning at the end so I'll add the remainder to S and then update n by taking the flow value of dividing it by K okay and finally I'll return s so that should work let's run and see that worked for these two test cases let's submit it and that worked 16 milliseconds even the best solution you'll see all the solutions good Solutions are done in this way so that's how you solve 1837 sum of digits and bask
Sum of Digits in Base K
daily-leads-and-partners
Given an integer `n` (in base `10`) and a base `k`, return _the **sum** of the digits of_ `n` _**after** converting_ `n` _from base_ `10` _to base_ `k`. After converting, each digit should be interpreted as a base `10` number, and the sum should be returned in base `10`. **Example 1:** **Input:** n = 34, k = 6 **Output:** 9 **Explanation:** 34 (base 10) expressed in base 6 is 54. 5 + 4 = 9. **Example 2:** **Input:** n = 10, k = 10 **Output:** 1 **Explanation:** n is already in base 10. 1 + 0 = 1. **Constraints:** * `1 <= n <= 100` * `2 <= k <= 10`
null
Database
Easy
null
873
hey everybody this is larry this is august 20th 2022. um we're gonna try to do me let's just say a medium one uh and a bonus question for the day and hopefully one day i haven't done b well it'll have to be one i haven't done before but i'm gonna choose a medium one usually i don't choose the difficulty but we did a hard one earlier and i'm gonna take a nap before the contest that's in two hours uh that's what i'm feeling right now so let's get started or let's hopefully get started hopefully subscribe or whatever uh so yeah so hit the like button hit subscribe and join me on discord let me know uh what you want to you know see on here just me live solving okay length of the longest fibonacci sub uh subsequence okay so that the given is strictly increasing array forming length of the okay so one two three five eight one's eleven twelve okay so n is equal to a thousand that's just something to keep in mind so n squared is gonna be good enough um yeah trying to think what's the cleanest way of doing it um i guess there isn't really that much difficulty right it's just with force maybe now is that n cube i think before if you just start like by taking every two number and then expand out the sequence that's going to be um and cube but can we build dp from that um let's say 12 11 and then we go to one but that's also n cube but we're not careful right so we have to think about okay here um does it have to start from any number now okay just want to make sure um okay and then i mean my other second thing is just thinking about dp and dp is going to be for example 11 when we go backwards then we can go 11 and 7 4 and then i don't know how to do this in a funky way hmm what do you think about this even though this is only a medium man i was supposed to thinking about it as you know just resting but because this entire length can be flipping oh well okay i see so i think one observation which i did not make because i was just thinking about a generic on a general case one optimization that you can think about is that well n is over only a thousand but it cannot be a thousand length why because also this is strictly increasing i was just trying to wonder if you know you can go backwards so if it's strictly increasing that will always be left to right which is something that's simplifying but because this is 10 to the 9 and 10 to the 9 is um so the fibonacci kind of grows relative to about like 1.6 to the n about like 1.6 to the n about like 1.6 to the n um and that's you know less than or slower than two to the n but that also means that let's say you know um that means that at most there'll be say 60 operations right um let's say there is 60 operations i don't know the actual map what's one what's uh but the actual math is 10 to the nine um log of base 1.6 or something like that right um 1.6 or something like that right um 1.6 or something like that right um so this 10 to the nine i'm trying to find i actually don't know how to do it but well i guess i could use google uh 10 to the nine three one two three uh log base uh 1.6 of this base uh 1.6 of this base uh 1.6 of this right uh okay google's not really telling me that but anyway my point is that it'll be less than like 40 or 50 or something like this right so that means that now for every pair we are we can just it only goes up to 50 wide i think that's basically the idea and from that we can just look it do it in a brute force way um i think this is still a little bit sloppy and python and that may be a little bit too slow but i think it should be okay right so basically you have for i in range of uh uh n say and then for j in range of i plus one and then now you know you have i j right and then now you're trying to find um k so whatever so you have a b is equal to um r sub i r sub j and then while so c is equal to a plus b and then while c is in set you know we have uh count is equal to two uh this discount is equal to two and while saying that we increment by one and then we have you know bc is equal sorry a b is equal to um b a plus b and maybe i could just do wow b is an s yeah maybe something like that maybe about b is an s and then we do this right um yeah and this will run out in at most like 30 or 40 so then here we can you know get the answer that way there are also maybe some optimizations that you we can do as well but let's see if this works to kick it off um again this is more should be correct unless i have some weird typo but it's all about the tle so let's give it a submit and then see how that goes this is of course also not one million it's not and squares and choose two so that's half as fast maybe oh snap oh because it has to be at least does that have to be at least three or something oh and has to be at least three okay fine so i messed up there because i was a little bit lazy um oops no don't show me come on button i just wanted to put in here ah silly mistake but hopefully i'm getting this out of the way for this practice and not doing a contest actually was thinking about it while i was writing it but then i just forgot i'm really sloppy on the memory these days um okay so that looks good uh two seconds uh yeah and this is gonna be n square um the key thing is that knowing that this goes out of bounds in like 30 to 40 attempts so this will always be false anyway pretty soon um is there a better okay so this is basically it um yeah so 43 times i that was the number i was looking for um dp i was also thinking about dp but i didn't know if there was going to be a way where like i could couldn't figure out um because i didn't think that this was going to be fast enough or like i didn't think that like the constants are big but oh well um that's pretty much all i have let me know what you think i need to people this is self analysis is that i really need to be not doing these silly mistakes i've been doing that too many times on the contest um like this exact thing even as i figured it out so uh so but this one's a good practice for me um i used to be okay at it but i feel like recently i've been bad about it which is to look at constraints very tightly um with respect to this particular thing because then now it goes up to 43 years or something like that right um and then this is a half a million say so like it takes 20 million operations in the worst case which is fast enough but yeah uh cool let me know what you think let me know how you did this problem let me know if you got it with no issues because larry is a little silly today but yeah stay good stay healthy take on mental health i'll see y'all later and take care bye
Length of Longest Fibonacci Subsequence
guess-the-word
A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if: * `n >= 3` * `xi + xi+1 == xi+2` for all `i + 2 <= n` Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`. A **subsequence** is derived from another sequence `arr` by deleting any number of elements (including none) from `arr`, without changing the order of the remaining elements. For example, `[3, 5, 8]` is a subsequence of `[3, 4, 5, 6, 7, 8]`. **Example 1:** **Input:** arr = \[1,2,3,4,5,6,7,8\] **Output:** 5 **Explanation:** The longest subsequence that is fibonacci-like: \[1,2,3,5,8\]. **Example 2:** **Input:** arr = \[1,3,7,11,12,14,18\] **Output:** 3 **Explanation**: The longest subsequence that is fibonacci-like: \[1,11,12\], \[3,11,14\] or \[7,11,18\]. **Constraints:** * `3 <= arr.length <= 1000` * `1 <= arr[i] < arr[i + 1] <= 109`
null
Array,Math,String,Interactive,Game Theory
Hard
null
9
everyone welcome back and let's write some more neat code today so today let's solve the problem palindrome number in this problem we're given an integer x and we want to return true if and only if this integer x is a palindrome number and what exactly is a palindrome well basically a number that reads the same way as it does backward as it does forward basically reverse it and it's the exact same and you probably know if you're familiar with palindromes you probably know how to detect palindromes when it comes to strings so you might think okay we can just take this entire number right one two one convert it into a string like one two one and then it'll be easy to determine if it's a palindrome that's a good idea but if you read down below the follow-up question they have for us the follow-up question they have for us the follow-up question they have for us is can we do it without converting the integer to a string so that's going to make this problem a little bit more tricky for us but i'm still going to show you how to do it so with a string it would be easy because we could have two pointers right a pointer at the beginning and a pointer at the end and then we could just compare each character or each digit and if they're equal we continue if they're unequal then we return false because then we know it's not a palindrome basically i'm going to use that same idea but i'm going to use it without creating a string i'm going to use it just by doing the math operations on this input integer so suppose we have a value one two one we wanna know if it's a palindrome so one what we wanna do is we wanna get the ones place and get the left value right the left value and the right value how do we get the right value that's the easy part right in math uh you might know from some programming problems you've done if you mod something by 10 we get the ones place right if you take 121 mod it by 10 we get the value one right which is what we wanted to get we want to get this right value next what we want to do is get the left value so how are we going to get this left value because once we get the left value then we can compare it with the right value and then we can check if it's a palindrome or not right well what math operation could we do on this to get this value we are asking ourselves this is 121. we want to know what value goes here in other words we want to know what digit is in the hundreds place how can you do that in a math well if we divide this by 10 not by 10 but if we divide it by a hundred then that will tell us how many a hundred how many hundreds go in this value and it'll always round down towards zero so in this case 121 divided by a hundred is going to evaluate to one because we're rounding down right if instead we were doing 220 divided by a hundred then we would get two because we have two hundreds in this value right so that's kind of the idea okay so now we have the left value and the right value we compare these two together they are equal to each other right so then we can continue right but now we compared these values so we want to chop them off how can i get rid of the left and right values so if i have 121 i want to get rid of the right value because we already compared it right how can i do that well i can take this divide it by 10 that will chop off the ones place so if i divide it by 10 it'll round down and then we'll get the value 12. that's awesome because that's what we wanted to do so we have 121 and now we want to get rid of the left digit because we already used it how do we get rid of this left digit well we had a hundred up above right we were taking this and dividing it by a hundred because we know that a hundred is the most significant digit for this right we couldn't do a thousand because a thousand would be too big right so if we take a hundred and actually take 121 and mod it by a hundred and this is the kind of the tricky part that makes this problem difficult right that's why this is a follow-up because that's why this is a follow-up because that's why this is a follow-up because you probably wouldn't guess to do something like this at least it would take some thought to figure it out right so if we take a hundred it take 121 mod this by a hundred that'll get rid of this first digit for us because it'll give us all the remaining stuff in this portion right so when we do this operation we're left with 21 right our goal was to get rid of this ones place this one digit and we did that our next goal is to get rid of this digit right because we used this digit and we used this digit we want to get rid of them how do we get rid of this one over here let me show you how so this is the easy part right we have 21 if we divide 21 by 10 that's how we can get rid of the ones place right and it'll always round down right so 21 divided by 10 is going to be 2 because it's rounding down so we successfully did what we wanted to do we chopped off the left and right digits right so now we're left with 2. and then now that we have our new digit or the new value we're basically going to repeat what we just did up above except the only difference is going to be up here to get th to get the obviously the left and right digits since this is just one value the left and right digit are going to be the exact same right so up above to get the left digit what we did was we divided it by a hundred first right now instead of dividing this by a hundred we're actually going to be dividing this by one because we chopped off two digits remember so before we had a value that was at least greater than a hundred now we chopped off two digits so now we're gonna have a value that's at least greater than one that's why we're when we get the left digit every time we're going to be taking this value and basically removing two digits from it so i hope that this makes sense so far and let me just repeat this on a different example to give you a slightly more clear explanation and one other thing i want to mention is down below in the second example you can see that we have 121 except it's negative right so it is a palindrome but it is negative so negative numbers in this case are always going to be false because you can see once we reverse it we have that negative sign on the right side right so we don't want that so any negative numbers are always going to be false now let's take a look quickly at a different example slightly different one two one so this is just one extra digit so if in this case we want to get the right digit which is one once again we're going to take this mod it by 10 we get the one value on the right if we want to get the one the value on the left we're going to take one two one and divide it by a thousand right a thousand because this value is in the thousands place right so we divide that and once we've done that we'll get a one which is the one from the left side right so now we compared it right we did what we wanted to do now what we're going to do is chop off the left digit and the right digit so once we do that we're going to be left with 22 right now we want to get the right digit how do we do that once again just mod it by 10 right that's what we did up above it works this time as well we mod it by 10 we get the right two how do we get the left two right in this case 22 previously we divided this by a thousand right that's how we got the left digit from over here right now we want to get the left digit again instead of dividing by a thousand now i'm gonna divide by 10 right instead of a thousand because we got rid of two digits right so we have to get rid of two digits from here so when we take this from a thousand now it becomes ten and then we get that same left digit two right so what i'm saying is this value that we have here it's going to go from a thousand to being ten right before what we had was a hundred and that hundred went to being one so on each iteration this value it could be really big right it could be ten thousand right every iteration it's going to lose two digits so it's going to go from being 10 000 to maybe being a hundred and then once again losing two digits it's now just going to be one until the loop has basically been done executing once we have no digits remaining so i hope that this is helpful because this is the math that we're going to be doing and the rest of the problem becomes pretty simple once you can figure this out so let's jump into the code now okay so let's dive into the code now we're given an input value x and the first thing we're going to check is this value negative is it less than zero because if it is then we can basically return false immediately right that's what we discussed from the second input example the next thing we're going to do is basically come up with that divider value that we were using remember that value that could be a hundred it could be a thousand it could be anything right initially it's one we want to know how large should this be so how are we going to determine that well basically if x is even greater than 10 times the divider and not just greater but maybe greater than or equal if it's greater then that means we're going to continue to increase our divider right base basically divider multiplied by 10 right because we're trying to get the most significant divider that we can that is still less than or equal to this x value right that's what we're trying to do right if we have a value 121 we want to get at least a hundred right if we have 121 one if we have a value 1200 then we want to get to at least a thousand right that's what we're trying to do here with this while loop once we have that then we're ready to roll with the rest of the algorithm we're gonna check okay while x is non-zero right check okay while x is non-zero right check okay while x is non-zero right we're gonna keep comparing the left and right digits how do we get the right digit well remember all we have to do is take x mod it by 10. how do we get the left digit that's slightly more difficult but we can still do it all we got to do is take x and divide it by the div the divider value that we determined up above i'm using two slashes because in python this is how you do integer division and once we have these left and right digits what are we going to check well we just want to know if left does not equal right then we can return false so now we want to chop off the left and right digits right because we just used them up above how do we chop off the left digit well you might remember if we take x mod it by the div that we determined up above that will chop off the left digit so now we chopped off the left digit how do you chop off the right digit well basically take this integer division by 10 and then you're good so we chopped off the left and the right digit with this single line of code that i just showed you and remember last but not least that divider value up above div we don't have to we can't forget to update this as well how do we update this well every time we just want to chop off two digits from it right so how do you do that we'll just take div take itself divide it by a hundred that will chop off two digits for us and believe it or not this is the entire code once we're done with this while loop we will have successfully determined that it is a palindrome so we can return true out here we return false inside if it's not a palindrome and this is the entire code and i'll run it to make sure it works and it is efficient and yes it is and one last thing i want to mention you can actually take these two lines of code up above left and right we don't actually need variables for them i just used that to kind of make it simple for you can take the right value and then cut it and then just paste it in here for this condition and take the left value cut it and then paste it here and then we can get rid of those two lines of code and you know then the solution looks pretty short and easy it's definitely not as easy as it looks i would say this is this follow-up portion at least is a is this follow-up portion at least is a is this follow-up portion at least is a medium problem because it's not easy to come up with but 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 thanks for watching
Palindrome Number
palindrome-number
Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_. **Example 1:** **Input:** x = 121 **Output:** true **Explanation:** 121 reads as 121 from left to right and from right to left. **Example 2:** **Input:** x = -121 **Output:** false **Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. **Example 3:** **Input:** x = 10 **Output:** false **Explanation:** Reads 01 from right to left. Therefore it is not a palindrome. **Constraints:** * `-231 <= x <= 231 - 1` **Follow up:** Could you solve it without converting the integer to a string?
Beware of overflow when you reverse the integer.
Math
Easy
234,1375
1,189
all right so let's talk about the maximum number of balloons so you're giving it a string text so you want to use a character of text to form as many as instant of the word balloon as possible so in this example okay i'm just giving two examples so uh this is b this is a and double l and double and y so balloon is spelled like this right so if i spell correctly this is slightly so there are two characters for all two characters for l and then um in this example you do have one balloon two balloons right so basically it's super simple let me redraw again i need to include the definition so basically it's like you have to return the maximum number but what happens if you only have one a and you have the rest of the more than three right or more than four doesn't matter so you're still going to return one right this is because you only have one a right so uh for the minimum so we just take the minimum between a and b and then n right and then we also have to take the minimum at l and all right but in this case l uh else occurs twice for the world right so you have to divide by two so minimum so mean between uh entire distance so this is the answer so uh let me just quickly uh dive into the question so p equal to 0 and then a equal to 0 l equal to 0. a equal to zero l equal to zero and then all equal to zero are equal to zero right so i will traverse the entire string text to char array and then i would have a switch case so sushi is going to depend on the c so i will say case b and i will break okay uh a case a and then i will break case l and i will break and in case of and i will break case and then i will pray i'll have the people right nlp so let me do this correctly okay son i will increment my e oh sorry case b and that case then i will have a case a increment my a ksl increment by l okay so increment my o okay certain increment so when i want to return right uh you can basically just return right over here but you're going to have a lot of input so okay it doesn't matter let me just do it with you so i will say methamine and messed up mean i have to between two methamine right so for this one is going to say l and all right l and o right but it has to divide it by two this is because you take two character for the word and in this case it's going to be what uh a b and i a b and n but in meta me you only can take two input so i will also have to use another method i mean in e comma n and this is a solution so let me run again all right submit and here we go so let's talk about time and space forever for every single character you traverse is going to be all of them for the time for the space this is actually constant and you can when you compare right the time is actually all one for sure so time is all of n space is all one and this will be the solution and i'll see you next time bye
Maximum Number of Balloons
encode-number
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible. You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. **Example 1:** **Input:** text = "nlaebolko " **Output:** 1 **Example 2:** **Input:** text = "loonbalxballpoon " **Output:** 2 **Example 3:** **Input:** text = "leetcode " **Output:** 0 **Constraints:** * `1 <= text.length <= 104` * `text` consists of lower case English letters only.
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
Math,String,Bit Manipulation
Medium
1070
525
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you not like the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started so problem is contiguous array in this problem we'll learn a very important concept right so stay tuned so what we have to do in this problem is we'll be given a array of numbers it's a binary array so we'll have 0 and 1 return the maximum length of contiguous sub array with an equal number of zeros and ones so we have to find a sub array which will have equal number of zeros and ones and the maximum sub array which is you have to return its length so if you see over here this is the sub array of two length and it has equal number of zero and ones so one zero and one two is the output and if you see in this area we have uh this sub array which has one zero and one so its length is two and this could be also another sub array which has equal number of zeros and ones right so output is two now let's see how we can approach this problem over here see we will be taking this test case so uh over here we have to find what we need to do is see we need to find a sub area we need to find a sub array and that sub array should have equal number of zeros and ones right and maximum length of such array we need to find maximum length and that max maximum length we need to return that will be our output so over here see this is one sub array which has equal number of zeros equal number of ones two zeros two ones this is one sub array if you see this one this has again three zeros and three ones so this is also a sub array of equal number of zeros and ones and this one this is also a sub array see this one it has also equal number of zeros and one so there are four ones and four zeros so from these all these three sub arrays also we have this smallest sub array this also has equal number of zeros and ones so among all these sub arrays which have equal number of zeros and ones the maximum length one is this one the yellow one and its length is what one two three four five six seven eight so the output for this will be eight output will be eight right so this is the problem now see guys how will approach so whenever there is sub subway given sub array we have to find a sub array so whenever sub array is given nested loop approach is the brute force approach that will have two nested loops we will find all the sub arrays we will find the sub arrays which have equal number of zeros and one and we'll be calculating like we'll be finding the max length accordingly that is how c we have this now we have this test case so what we will do is we will have two loops like i loop here and j loop here so we'll have two nested loops for i in this length till n from like it will start from zero and it will go till length and j will be starting from i and it will go till n right so what will happen is every time we will be considering all sub arrays we will have two variables zeros and ones we will be storing the count of zeros and ones how many zeros are there how many ones are there so first of all this sub array will be considered then this sub array will be considered whenever see when this sub array this fourth sub array is being considered zeros will be two ones will be two so zeros and ones are equal so this could be our one sub array so we will have a length variable in which we will be calculating the length um of uh how like what is the maximum length till now of the sub array which has equal number of zeros and ones so when zeros and ones like if your zeros is equal to ones when zeros and ones become equal so we will see what is the length is what four so we will update 4 right like this you will calculate for this all the sub arrays you will consider then your i will increment i will come here so now you will be calculating for these so like this will happen so all the sub arrays you will be considering and all the sub arrays you will you know find like you will be keeping zeros and ones and you will check where the zeros and ones become equal so like over here for this sub array zeros and ones will become equal zeros will be what zeros will be three and one also will be three so this could be your one sub array so what the what is its size is six so you will update this like this right and similarly if you go forward again if you go ahead for this and when it will come to here zeros will become four and once also will become four so this is of length what 8 so 8 will get updated right so this is brute force approach we are having two nested loops and we will be calculating the maximum length accordingly so o of n square will be time complexity for this n square because we have two nested loops and space complexity uh will be what space complexity will be nothing like we are not using any extra data structure so we are just taking this length variable and these variables zeros ones and right so it will be constant space complexity will be constant right now we need to see we need to uh optimize it right o n square will not get uh accepted if you see over here constraint is what the max length is 10 raised to the power 5 so 10 raised to the power 5 is if n is 10 raised to the power 5 then n square will be what 10 raised to the 5 into 10 raised to 5 10 raised to the power 10 so this is greater than 10 raised to the power 9 so this will give you tla this n square approach will give you tle right that this will not get accepted so we need to think of a optimized approach right so see how we will think of that what we are doing every time we are what we are doing is we are calculating for all sub errors we are going and we are calculating for all subways let's do one thing just a second uh i'll write this test case again see this is in this problem now you will learn a new concept right you will learn a new concept so the extra work we are doing over here is that every time for each sub area for each sub array we are calculating the sum right for each sub area we are for every sub array we are doing that right how we can avoid that see what we first of all before going to this let's take a random case like we have some numbers let's say we have this array a b c uh we have b e f so these are some numbers like a b c d e f these are some numbers right and let's say sum of a b c sum of abc is 5 that is a if you do a plus b plus c these are some variables if you do a plus b plus c that comes out to be 5 right and if you take some of this whole thing that is if you take sum of a plus b plus c plus d plus e plus f that also comes out to be 5 so what was that like a plus b plus c is 5 that is this thing is 5. so what do you think this thing will be 0 right because if this a plus b is 5 and this whole thing is 5 then this will be 0 only right so this problem is this problem which we are doing over here this is this problem contiguous area this problem is a extension is extension of a sub tot count this is a count of sub arrays having some zero so this problem is an extension of that same concept is used in this problem count of sub error is having some zero right so if you will solve this problem you will be able to solve this problem also right so oversee like if we have to find a sub array which has zero sum so what is what will that be this now this one because this sub array has some 0 this array has some 0 so what we can do is like if this is 5 and this whole thing is again five means whatever is this one this part whatever is this part that will be zero so we found our sub array which has some zero right this is one concept so just this is this was for understanding so just keep this in mind now let's see how we will solve this problem so what we will do now we will use same concept the concept is what that what we will do first of all we will replace all these zeros we will replace all the zeros with minus one right my zero is there so we will replace it when minus one will be as such zero will get replaced by minus 1 then this 1 will be as such this 0 will be minus 1 this one will be as such this 0 will be minus 1 and this one will be 1 you will understand why we are replacing 0 with minus 1 this is do we are doing because see if sub array if a sub array has equal number of zeros and ones so if you change these zeros to minus one then the sum of this sub array which has equal number of zeros and ones will come out to be zero minus one plus one minus i so that's why in order to get some 0 we are converting 0 to minus 1 we are changing 0 to -1 so that minus 1 we are changing 0 to -1 so that minus 1 we are changing 0 to -1 so that we can know that if sum of a sub array is coming zero is zero then it means that it has equal number of zeros and ones right it has equal number of zeros and ones why because zero is changing to minus one so if zeros are two so what will be minus one minus two and if ones are also same count so one plus one will be two so two minus two will come out to zero right for example if here there are not equal of number of zeros and ones here is zero one zero and here also there is one so zero will be minus one minus two but ones will be one plus two plus three so one will be this so here sum will not come out to be zero so if the sum is zero if sum is zero it means it has equal number of zeros and ones so this will be the this approach we will use this will be the deciding factor that whether we are we'll be finding sub arrays only if a sub array is there and its sum is zero then it means it has equal number of zeros and ones and that could be uh one of th that could be our answer right so let's see how we'll do this how we will do this i hope you are getting this point so see what we will do now we will take a hash mark you will understand why we are taking a hash map we will take a map unordered map or a hash map right and what we will do is we will take few variables first will be you can say uh first will be max length this will be storing the maximum length of the sub array right initially give it zero then we will be taking uh we will have a variable uh this one like we'll have some we'll be having a sum variable right and we will iterate on this area so right now just look now this is your area right this is our area you have to look into this now we have changed zeros to minus one right this is your area so i'll do indexing quickly so 0 1 2 3 4 5 6 7 and 8. so what we will do is what we will do we will start iterating so here i will start from zero so uh this has minus one so our sum will become minus one right now we'll go ahead is changed to one now this is one so some will become what minus one plus one sum becomes zero so now sum becomes zero means we got a sub array which has equal number of zeros and ones that is this see this one zero and one was there now so this is equal number of zeros and ones sub array so sum becomes zero that means we got a sub array with equal number of zeros and ones right see also earlier before this step what was the sum was minus one when i was here when i sum was minus one when i was here so sum was minus 1 so what we will do now we will store this sum and its index in a hash map so sum we got what minus 1 and index was what zero so you'll understand why we are storing it but just for now we are storing sum and the index so then after that we go to i was here so i came here and then sum becomes zero sum becomes 0 means we got we caught a sub array we got a sub array with equal number of zeros and ones so we will update our maximum length will be what i maximum length will be i uh i minus i plus 1 that is i is here what 1 but length is what 2 now so i plus 1 will be the length so i is 1 plus 1 2 so max length is right now 2 and here we got 0 sum 0 we will store in the hash map so hash map zero sum was occurring at what index occurring at one index like as in we are storing this sum that this sum is coming is still what index it's still one index right zero sum is still one index now i will go ahead i will go here so i will be at 2 now what is this minus 1 so 0 minus 1 it becomes minus 1 now see now it's a very important point over here we got minus 1 till now see what are elements minus 1 and minus 1 so starting from this till this sum we got is minus 1 right we got minus 1 and earlier also if you remember we got minus 1 at what we got minus one at zero index that is for this thing just for this thing this sub array one element is also a sub arena so for this sub array we also got a sum minus one we got some minus one so guys see same concept which we discussed earlier if this is a b and c if a is equal to minus one and if a plus b plus c is equal to minus 1 is equal to a plus b plus c is equal to minus 1 right then a is minus 1 so what will this be this will be 0 so b plus c will be zero that is b plus c one and minus one this is zero and we know that if sum is coming out to be zero it means it has equal number of zeros and ones here see one and zero equal number of zeros and ones so that's why we are storing this sum at every index we are storing in the hash map so that we get to know where was the same sum occurring last time and the elements between these elements will be a sub array having some zero because this sum is occurring again here this sum is here again so this between elements will have some zero right so now what we will do we will see that okay this sum is minus one and is this sum present in the hash map yes it's present means we already earlier got this sum we earlier got this so the elements which are between have some zero will have some zero and if they have some zero means they have equal number of zeros and ones so that could be our sub array so we will find the length of these we'll find the length and how we'll find the length it will be what it will be this is i minus uh this index which is where we where the last sum minus 1 was occurred so that we will get from what map of what minus 1 is what sum so i is currently 2 minus m of sum is what minus 1 so minus 1 is what 0 2 minus 0 is what 2 so this is how we get the length so right now max length is 2 so we'll not update it this is how you get the length one way is getting length this like this way we get length when we are starting a sub array from zero and we get a sum zero and this will this is the way if the sub array is occurring between like some between sub air is there right so this is how we calculate so now let's go ahead and see you will understand if you are not able to we'll when i will further i treat me you will understand so let's go forward so over here what will happen i will go to 3 now i will go to 3 and we will not update this minus 1 is 0 only because we need to have the maximum length so the first index will keep so here minus one plus one will become what zero and zero we are getting so if we are getting some zero means from here to here see from here to here we have a sub array with equal number of zeros and ones so length will be what i plus one is what three plus one four so here we have played and this will become four this will be four we will not update zero here zero's index will be one only because see we have to have minimum index here so that we can have maximum length if we have this minimum this length will increase now so we will not update this 0 with now 3 this will not change to 3 because otherwise this will be minus thinner and if we do not update it then it will be minus one so we have to have maximum length so we will be keeping the earliest index only that is one right now let's go for forward and i will come here so this will be 0 minus 1 now just pay attention guys see again we get minus 1 and minus 1 was occurring uh earlier at what zero index so he see this array we have minus one and minus one so this whole sum is coming out to be minus one and earlier we got minus one at what here so between all these all will be having some zero right these all will be having some zero so how we will calculate the length i is what four minus m of sum is what minus 1 so minus 1 is what 0 4 minus 0 is 4 so 4 is already max length is 4 so we will not update it so we'll go ahead now i know it's bit of tricky but it's very easy right once you understand it's very easy so i will come here this will become minus one it becomes minus two so minus two is or not in the map now so we'll add its entry minus two sum at what index at index five then we'll go further so this will be one so minus two plus one it will be minus one see guys again we got minus one so see what the array is what it is minus 1 and for whole this whole thing we are getting some minus 1 and earlier minus 1 we got for what 0 this thing so this whole thing will have some zero let's see why this is zero and this is zero so how we will calculate the length i is what six minus m of sum is what minus 1 so m of minus 1 is what 0 6 minus 0 6 so the length is of the sub array is 6 so we'll update this so this 4 will now update to 6. right i hope you are getting very easy and then let's iterate further so i will go ahead i will come here so this will be what minus 1 so minus 1 minus 2 so now see earlier we got minus 2 and again we are getting minus 2 so earlier we got minus 2 at index 5 so how we will calculate the length the sub array length i is seven minus m of minus two is what five so two see this area this array is a sub array which has zero sum so this is equal number of zeros and ones so two length six already is greater so will not update it will go ahead so i will now come here now see very important see 1 so minus 2 plus 1 will be minus 1 now again we are getting minus 1 see guys again we are getting minus 1 right so whole sum whole array sum is minus 1 and minus 1 what we get where we got at 0 index that is here so this whole these whole elements will have some 0 how will get it i is 8 minus m of minus 1 is what 0 so 8 so here we'll update eight and we got max length we have traversed the entire area and we got the max length right i hope you understood the dryer and the approach guys very simple so see whenever you have sub arena you have sub array and you need to find equal number of zeros and ones sub array sum equal to zero you will use this approach the hash map approach where you will be storing this sum and its index right so let's see the code see very simple code we have taken this map in command because what we are storing sum and the index so in comment and firstly what we did we changed all the zeros to minus one so all the zeros are changed to minus one we have this loop after that what we are taking we have this uh two variables now we have two variables one is the sum and one is the max length so here i am taking sum as zero and max length i have taken this rest variable and then i'm calculating iterating and every time i'm finding the sum and if the sum is 0 means the length is i plus 1 that is from starting only starting till some index we get a sub array of equal zeros and ones so that will be how it's how we'll calculate its length i current index plus one because plus one why because its index is now so one length you need to increase one you need to add and otherwise if the sum is in the hash map this will check if the sum is in hash map some is in hash is in map then if right if you remember minus was minus 1 was in the map so what we did this to find the length i minus m of sum so i minus sum this will give you the length and you will compare with the rest and update it otherwise if it's not in the map sum is not in the map like minus 2 was not in the map so you added it so sum add in the index of it add it and at last you will return the max length so i hope you understood it if you submit this it gets accepted and the time complexity for this is o of n why because we are doing the single traversal c and in unordered map this find is o of one time average case o one and uh extra space we are taking so extra space complexity will be often space complexity will be oven and time complexity is over fine so right i hope you understood guys very easy problem right very easy problem and if you found the video helpful please like it subscribe to my channel and i'll see in the next video
Contiguous Array
contiguous-array
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1. **Example 2:** **Input:** nums = \[0,1,0\] **Output:** 2 **Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Hash Table,Prefix Sum
Medium
325
333
hey guys what's up today's question what we're going to say is 363 the largest bic sub-tree bic sub-tree bic sub-tree it says that given the root of binary tree find the largest sub tree which will also be aps t and just so you can see from this graph uh the original root for from this tree will not might not be a bst right however some of the partial tree can be a bsd for example this one can be the bstd however if you see the right of the rule uh this part cannot be constructed to a bst so that we will only calculate this part which is the result will be three right and the variable came across uh you know uh the three problem the first thing we need to consider about is to which kind of message should we use to traverse the tree you can use bfs or dfs and for this problem we can actually use the dfs and the post order specifically what is post order because we need to know the shell information before we handle before we deal with you know the root of the rule otherwise if you're just not gonna first deal with the rule node and then you're just gonna deal with the left and right you're just gonna lack some kind of information that you want for example how large the last tree because you want to if you want from the bst you need to know that the largest value for the left part and the mean value the red part and compare them to the values that you uh you are currently in which will be root of value and then you can just make sure that uh this can be a valid tree or not right so yeah that's basically the post order thing and what are we going to do we will encapsulate one node which will contain our node and our you know me and the max and also the size will you know be made to you know record it's a record to see how many nodes itself can contain for example uh take five uh you say five will be like the size of five will be three because uh the node five can contain like itself and the left and the right so will be you know three and if say the size will be if the size the valuable size will be zero then the max and the mean value will be meaningless because uh we only will only see that meaningful whenever it's you know a value bst right and then we're just going to use in the post order traversal and here we're first to initialize root of the size equal to one and to use that and to post order that in order to get the information from the child both the left and the right and then we're just going to judge because we need to both the left tree to be valid and relative value in order to process the you know the middle to see whether or not it can be you know and then we're just going to update the root of size and also to update the domain root of max however if say one side or both sides of the root will be invalid we're just going to update it with outside equal to zero this will just kind of mean that we can validate no matter how large how small the max and the mean value is if the result side is equal to zero we are just going to not see it right and then we're just gonna update our result and finally we're just gonna handle that so that's basically a classic question of a post order traversal so that's the home story for this 363 the largest substrate
Largest BST Subtree
largest-bst-subtree
Given the root of a binary tree, find the largest subtree, which is also a Binary Search Tree (BST), where the largest means subtree has the largest number of nodes. A **Binary Search Tree (BST)** is a tree in which all the nodes follow the below-mentioned properties: * The left subtree values are less than the value of their parent (root) node's value. * The right subtree values are greater than the value of their parent (root) node's value. **Note:** A subtree must include all of its descendants. **Example 1:** **Input:** root = \[10,5,15,1,8,null,7\] **Output:** 3 **Explanation:** The Largest BST Subtree in this case is the highlighted one. The return value is the subtree's size, which is 3. **Example 2:** **Input:** root = \[4,2,7,2,3,5,null,2,null,null,null,null,null,1\] **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-104 <= Node.val <= 104` **Follow up:** Can you figure out ways to solve it with `O(n)` time complexity?
You can recursively use algorithm similar to 98. Validate Binary Search Tree at each node of the tree, which will result in O(nlogn) time complexity.
Dynamic Programming,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
null
1,464
hey guys this is yessir has been going this video I'm going to take a look at 1:46 for a easy one maximum product 1:46 for a easy one maximum product 1:46 for a easy one maximum product of two elements in the array we're giving array of integers I will choose two different indices I and J that of the array return the maximum this well actually - one doesn't matter because actually - one doesn't matter because actually - one doesn't matter because they are all wait a minute the numbers are bigger than one so you all be positive so it doesn't matter it's the same actually with the product of the two elements there's no need to subtract with one so the problem becomes that we need just need to choose two different two top two right we need to get the top two largest numbers so how can we do that well which is the cricket say top two with the initialize with infinity right this is the usual trick I'm doing and then we just loop through the array and update this to the top two okay for nom if num is bigger than the larger one I mean the larger one should be put at the up index zero so if it is bigger or equal to it top to zero we update it to one equals top to zero and then tap to zero equals unum if it's for the net but is bigger than the second one else if num is bigger then top two is one we update top to one right and then if it's smaller than a second one there's no need to put it into your range so we ignore it and at last we just return top to zero minus one times top to 1 minus 1 so this is the top two numbers we get I think we should do it's very simple I think cool well we're accepted it's very simple but actually this is a special case of the two elements right you forgetting like three elements we using these playing if close but not have anything it's just to make the code verbose so let's try to rewrite it into more general way well as we said this is if you think uh if you generalize the two into a different like K you will see that this is a top k question max to get the top a big K largest elements in the array right so our solution which is what it should be prior to Q right so okay this is how prior to Q but up don't worry I have a separate have another video explaining how we can improve implement the product in JavaScript please search on my channel I won't do it here so you can just tell the interviewer that we have my suppose we can use prior to Q directly so okay here is product you and then what we're gonna you do is okay we rather than using array and do the comparing by itself we were creating a product you so pry already Q and then another comes on you would take classes party Q okay new product you when we are inserting a new number the smaller Y should be gone so we should be ascending order so right Jenna creating a new product you like this top two okay and then we just to for let number plums top to add nombre and then if top two sides is bigger than two we pop put remove the smallest one so we pull cool and then we get at last we will get two elements in the park you so we get it so past top al okay that's the product equals one while top size is bigger than 0 we constant numb okay you just say product times by the top to hole you just multiply all the elements left it in the Parata cube and return in the prior product oh I'm sorry it should be this one so this is a general form of this problem I think let's try top size is not function ah we just gather mist I'm sorry together so it should be yes cool so we are also doing good in this case let's try to analyze our time and space complexity for time here we just look through all the elements right so it's linear time of course space use the two elements yeah here so o to its constant okay for chronic you it's the same basically constructing dozen constant in time for this we use a linear time but the ad and PO is not at poor actually it should be log K which is 2 so it's actually 2 and we add an appalled so 2 times this and this will be also the o2 blog - okay so this will be also the o2 blog - okay so this will be also the o2 blog - okay so if the no enemies weigh much weight like - is spent like the K is something - is spent like the K is something - is spent like the K is something between the half of N or something is big block very large larger than 2 but smaller than n this general formula will help because it will improve the linear time okay so the solution here is actually is still linear time but in another format space rock it's the same - okay so space rock it's the same - okay so space rock it's the same - okay so that's a two approaches to this problem with the one a special case with two we can write the if by itself but if like the is not select when a this if not is not gonna work for that we could use a product you and yeah it will help our just make things concise okay so okay that's all for this one hopefully else see you next time bye
Maximum Product of Two Elements in an Array
reduce-array-size-to-the-half
Given the array of integers `nums`, you will choose two different indices `i` and `j` of that array. _Return the maximum value of_ `(nums[i]-1)*(nums[j]-1)`. **Example 1:** **Input:** nums = \[3,4,5,2\] **Output:** 12 **Explanation:** If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums\[1\]-1)\*(nums\[2\]-1) = (4-1)\*(5-1) = 3\*4 = 12. **Example 2:** **Input:** nums = \[1,5,4,5\] **Output:** 16 **Explanation:** Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)\*(5-1) = 16. **Example 3:** **Input:** nums = \[3,7\] **Output:** 12 **Constraints:** * `2 <= nums.length <= 500` * `1 <= nums[i] <= 10^3`
Count the frequency of each integer in the array. Start with an empty set, add to the set the integer with the maximum frequency. Keep Adding the integer with the max frequency until you remove at least half of the integers.
Array,Hash Table,Greedy,Sorting,Heap (Priority Queue)
Medium
null
1,696
hello everyone welcome to learn how flow in this video we will look into another difficult problem that is a jump game six so this is an a medium level problem we will go through the question and then try to understand what the question is asking us to do and how exactly we can uh do that question uh in a better way we'll understand the thought process behind uh do it solving a question like this we'll look into the examples and ultimately we'll write some code to solve this question okay so let's start this video it says like you were given a zero index integer uh that is called nums and an integer k so you are you have a nums array and an integer case and those are the two things you have over here a further like you are initially standing at index zero fine and in one move you can jump at most k step so when it says at most case step that means you can jump either one step or uh any number of steps up to k steps like i like two steps step up to case steps okay uh so it says that you can jump at most k steps forward without going outside the boundary of the array so you cannot go outside the boundary of the array so you should remain in it and by uh it does say you should go forward you cannot go backward from it okay what is uh it says like that is you can jump from index i to any index in the range of i plus one till either n minus one or i plus k whichever is the minimum you can jump in that inclusive of both in conclusion of the range okay so we'll understand clearly all this what they're saying and then uh for this case you want to reach the last index of the array being index n minus one so target is to reach n minus one index okay that's the target if it says like your score is the sum of all uh numbers of j so whatever with the value at particular position in the nums array or whatever we are jumping so all the hell's sum will be our total score okay so that will be our score uh like j being there visited like the index visited in there okay so our target is to maximize the scope okay our target is first to maximize our score now let's see whenever we find something like maximum of minimum the first thing we should think of is whether this is a greedy problem or not whether we can be greedy in terms of achieving our goal or not let's try to see an example we uh have over here that is uh see if we go for greedy then we the biggest problem we may face is like we will first sort the array or kind of sorted with like all the biggest number at one place and then we'll try to find out which are the maximum values we have and thus uh we will uh try to like take all those uh scores but is it a case like uh see like there are continuous like k is two in this scale let's understand this uh example one the first is one then minus one minus two four minus seven three if we have a greedy kind of approach then what would have been date like it would be uh minus one then minus two then minus seven like well knows for starting with minus seven minus one minus two one four three so we'll end up taking all the bigger number like one four three and we'll keep on the lesser numbers that are taking our total score to be uh less so with that approach can we find like that we can reach a maximum score but are we actually able to follow the all the guidelines over given over here no because we are not sure whether we are taking k steps actually or not if there are continuously uh negative numbers uh in our array then our like after k steps or at most case step our total score will go down right but we are not sure whether our score is going down or going up if we i take a greedy approach over here so when you cannot take a greedy approach next think of an approach uh that is a dynamic programming approach okay let's uh understand this example and then i will explain how this uh approach will be helpful for us it seems like uh we you these are the elements given to us k is two so the final output is seven how they are saying like you can choose jump from the sequence like you first you are here at one and you need to reach three right so that's the target element that you need to reach uh n minus one and you are at the index zero so uh this is the starting index and you need to reach over here right these two are given in top for us so in that they are saying like first jump to minus one then jump to four and uh then jump to three so the sum over here is seven okay a very good example now let's try to uh actually see how a particular case can be done okay how exactly we can visualize this question let's uh i will go ahead with example two over here okay now let's try to see uh how actually we can uh find a solution to this so yeah here we have our exact numbers array now we are sure that we need to reach at uh position n minus one right and we are starting from position zero uh our index zero okay now uh if we're sure that we need to reach equation n minus one that means our total score like the sum of all the score we are getting our total score of the value like the ultimate answer will have three right so uh it will be like the like three the value at this position must be added to our total score right that would be the case for us so anyways we cannot skip three like i am starting from the end like we are we need to reach three so we must get a value three over here okay now uh let's understand uh towards the back we and now we are at position uh like at this position okay what can happen from zero how many steps we can take we can go to uh like we can directly go to three or are there any kind of steps can we take like we cannot go like more than three uh jobs like we cannot skip three positions but from zero we cannot go uh not even three we can give go only one position jump right so like from zero if we're at zero we can go only till the next question and that is the end so if we take zero like if we land on zero then what can be our steps our state count can be like on the total score will be become like only three plus like uh zero plus three so there's a count over here okay now say we are at next we move back and we are at four okay uh so if we're at four we can go to our zero fine or we can go to our three like uh this is case three we can skip zero and we can directly go to our three like so if we can uh if we like from four if we go to zero then what will be our score will be 4 plus 0 like 4 plus 3 like score at 0 is 3 so 4 plus 3 is we find 7 okay and if we directly go from 4 to 3 we find it 7 anyways right so we find it that either way we take we have only two ways over here and either way we take we find that the answer remains uh seven for us like the seven four so form of four we know that is our total score uh forward four will be seven right now we are at minus two fine we are at minus two if we take a single step okay uh say we take a single step uh that is uh two four okay so what becomes our value so for like from four we get a value of seven so seven minus two that is uh we'll get say uh five being our score if we put a step to four okay from two if we take a step to 0 so we know from 0 we have a score of 3 so 2 like 3 minus 2 will be our 1 fine and from 2 if we directly take a step to 3 our value again becomes one right so we'll see what is our a minimum like maximum score from minus two like if we have to step on minus two then what is our maximum score for minus two the maximum score being we find that five being the maximum so we write it as five fine so that's the value we have over here now move back we are moving back to minus five say we are over here and from minus five we find that if we take one step from minus five we can land into uh like minus two so one step from minus two like we say minus five plus five that is zero we got one step and then again if we take uh two step like skip one and take two steps to uh reach minus four like reach four then or one being a total score that is minus five plus seven being two fine and see like minus five four minus five we can take another step that is directly take to three so that's our k equals three so that's the three steps that we're taking so we directly reach to zero and so minus five plus three becomes uh minus two right so what being the maximum score we can get if we land on minus five so maximum score we get is uh two itself uh being two over here is the maximum so we get a maximum score of two fine now we are over uh at this position initial position over here okay so it's we are sure that we will start from here now what can be our steps again our steps if you look carefully our steps will be we can jump from 0 10 to -5 right so if we jump for 10 minus 5 -5 right so if we jump for 10 minus 5 -5 right so if we jump for 10 minus 5 our score will be 10 plus 2 that is uh 12 okay yes so that will be 12 then we if we jump to directly to this position this minus 2 position then what will your score 10 plus 5 that is we find a score of 15 fine and what is we can jump from here we can jump directly from 10 till this 4 because those are the spaces we can like k equal to three we can have jump at most three elements right so we jump till four and what is the output we find over here we find that ah ten plus for like this seven being the score from here so ten plus seven is for our 17 right so when we find the all the values over here what can be our answer at this like uh total score from 10 we find that the maximum score is 17 right so we find the maximum score 17 and ultimately what being our answer says it's 17 so we found our answer okay so this is an approach that i took from the right hand side so if you go ahead with the left-hand side even if you go ahead to left-hand side even if you go ahead to left-hand side even if you go ahead to the left-hand side that will be even the left-hand side that will be even the left-hand side that will be even the same thing if we uh go to the left side it will be like 10 being the first value okay then i add this minus 5 we will go 10 minus 5 will be 5 okay or we cannot go back like from minus 2 will be 10 minus 2 or this minus like 5 minus 2 or 10 minus 2 that would be 8 being the maximum score then we will come across 4 will be 4 minus like 8 minus 4 uh will be 4 or a 5 minus 4 will be 1 or 10 minus 4 or 10 plus 4 will be uh sorry not minus what are you saying 8 plus 4 will be 12 then 5 plus 4 will be 9 and 10 plus 4 will be 14 so we find the maximum score variance 14 and then we will again at zero we can look back and we'll find like 0 plus 4 is giving me the maximum that is 14 again and then it from 3 it will be maximum to 17. so ultimately if we go from left hand side or you go from right hand side however we go we will find out a same answer okay so it's uh the same thing we're doing but look carefully this is a naive way you actually found out a dp solution to this okay or either db you can say or you can actually not idp you can actually keep updating the values in the nums and based on the value in the nums array you can actually keep a track of the final answer thing nums n minus 1 if you return so that would be our final answer okay but think carefully isn't it something like we are doing the same task repeatedly can we optimize our code uh how what i mean exactly is uh say we have uh we have like uh we are checking for all the elements say for uh four when you are at four we are checking for all the uh like uh k like at this position i we are taking all the i minus k elements right or all these elements from four and when you get zero we are taking all these elements from zero when we're at 3 we are taking all these elements at 3. like isn't it like we have a loop uh like you're going through the loop of nums array and within that we are again going through uh like another loop of the k number of elements for each element so it's like we are traversing a like order of n uh order of m num okay and with order of n or on each of the inde uh or n value or each of the values at n we keep on uh doing uh a k step or the k uh being the complexity i mean like we keep on checking k elements at each position right so is it something we can optimize it here because we are checking for k again and again so is it something we can have a notation that okay uh if we are finding this is the max value till now is uh like max value for the last three elements is some value and we need to uh we need to keep a track of that value okay so we can do that like can we like more or less we are trying to reduce this a because if k becomes something like 10 to the power 5 that's what we have been given to us as a constraint think of the complexity we need to uh go ahead with think of the exact values that you need to go ahead with right because if that is 10 to the 5 then we need to keep checking for all the elements actually to uh find out okay where is our key like how much is the value we are getting fine now uh how can we reduce this like each of the uh fine see this is more or less uh kind of an uh sliding window you are sliding a window like these are the windows they say uh these are the windows you keep on sliding the window based on whatever position you are at okay so that's a kind of a sliding window problem you can think of in this way now uh to reduce the complexity of like this kind of window we have a wire okay like this kind of window we find how can we do that we can keep a track using our priority queue i mean a max if find a maxi whenever uh whenever the for the last three limits you find the maximum value keep on tracking the elements based on that will be a very good way to do that because you keep on uh keep a proper track on your uh elements uh you directly find the maximum value and you add and remove so from that k will reduce to a value of log of k like uh adding and removing uh values in a maximum or a priority is log update so that this you can reduce from n to n like n k to n of uh n log k fine can i think of anything further is like we can have uh not a priority queue but we can also go into that three map like a tree map uh that will store our all the mapping for the last three elements each okay that will also be if you remember that you are going to three map and that will also end up having a log of k uh value also there can be another approach to reduce this log of k is like if you use a decreasing dq like you use uh dq where you store the indexes uh being the maximum values we have okay so we'll store the indices of uh this nums element and the elements will be in decreasing order so we'll store the indices and that will be in decreasing order at the front of the uh like a front of the dq will have like a max value over here okay and at the end we will find the mean value fine like after uh it will have a length of the k uh k being its length or like that and how would like when adding a new number syndrome i will element like will eliminate the elements which is less than or equal to number okay and uh which will never choose in the future like if we have a greater value we are adding so all the values like whenever adding 14 over here so all the values less than this have no point over here right if you have a point like attending already there in the uh dq so what's the point of adding five for eight and uh eight or something like right so once we are like it won't be any value once we get at this position the maximum value we have is still and we will work with it fine and after like at this position if once we are here like what is the panel of like 10 being not there at that time okay once we are pointing over here so once i found 14 being our largest value till now so there's no point keeping a track of five and eight right and uh once you have reached 17 then there's no point uh giving a track of eight right we have 40 we only kept our maximum value being the 14 and we uh once we find out greater value we'll add it and add 70 to our dq okay so that's the basic idea so if we go ahead with something like that then what can we do we actually can reduce this whole uh k like whole complexity of k to an order of one so ultimately we can reduce this to an order of n like the whole question be an order of n so once we can do something like that our a whole uh question of the whole time complexity is reduced by many posts fine so that will be our approach over here now uh let's quote this and after that i will make you understand what exactly i was trying to say the whole time and how exactly we can do this okay now let's quote it further okay so here we wrote a whole question and let's uh see how fast or how slow it works so we find that this is the 40 ms solution that we came across with so let's uh let's understand what exactly the question is trying to say and what uh like how we solve it okay let's understand this code actually so what we did we just took the length being the numbers of length n okay after that we took a dq our dq know you remember something where we can add at the front and also like add and remove at the front and end like at the both ends like a double ended cube we have over here okay so we are using as you say the added eq for that purpose and we uh like this particular dq will help us in like storing the index of the elements okay like whatever the elements will come across it will help us to store the index so for that purpose we actually took the tp like i'll explain further in the court how it is working but we'll keep a track that all the like the elements the front will be something like the maximum element pointing to max values and the elements and then towards the last is the minimum element the whole dq will be in a decreasing order okay that's our idea behind the whole eq now let's understand so we just initially offered zero being the first uh index of the array so we just offered zero now we started our uh position something like this like a loop a single loop we can find that's a order of n as i say so single loop and in that we were finding like we were studying for one till n being the length okay that we simply did our nums of i let's like get this current position number y is plus equal to numser dq that peak first big first is uh at the in the front whatever be the elements uh we are just pick uh to the element and we find like till now we have only zero so we find that the q numbers of zero l is there so the quick first return zero and num sub i is one so uh we just did we just summed up the value of the elements over here okay like if i just uh taken small example for you example two i was going out with so let's take this example and let me show you what exactly it means so add initially you insert a zero into our uh particular dq fine after that numbers of i when you are at this position fine what do we say like a minus five plus uh numbers of zero peak first returns are 0 so minus 5 plus 0 is written as 5 and we added that to our uh particular numbers of y we are just changing the num survey so that we are not using extra space for that okay for that we check like if dq uh like while dequeued or not empty like while we can keep continuing and uh we are checking the dequeue at p class is what p cluster is zero that till now or sql only the l is less than equal to num supply now is it less than equal to num supply is currently 5 and pick last names of p class is 10 so is it less no so this loop will initially not work then we are adding detailed offer last we added what current value that is one to our uh dq so that is one being added over here fine so that's the step we did and we find that if i minus dq dot first i is one minus dq dot first degree first is zero like current is zero is there so uh decrease of first is greater than equal to k we simply pull the first element so once we have uh our like k being the length of this window we are looking for once we are done with our maximum uh window then we remove the uh value over here like we remove the initial like the map farther most values we have got and we're removing that so that's what the idea over here so what we did basically we keep on adding the indices till the indices we find that uh it is uh if our numbers of i that is norms of peak last that is the last element we inserted is less than num sub i fine if it is less than num supply we will uh remove the last element we will just keep a track of all the bigger element we have uh in our the whole area okay so that's the idea behind the whole liquid and you as you saw like it actually worked for us in a 40 millisecond solution uh if you think there can be further uh upgradation or further modification the solution if you think that can actually help in reducing the time complexity i would love to know your uh thoughts in the comments as well so but until then uh this is the whole uh concept behind this uh question and this is how you can actually solve it on a like a very fast solution so i know i can make you understand how this solution works and what you need to do to solve it so thank you all for watching this video also make sure to uh comment down below any kind of thoughts you have or uh make sure to like the video so that gives a motivation for me as always uh also if you haven't subscribed to this channel already make sure to subscribe that also you will get regular liquid videos on daily problems thank you all for watching this video hope to see you soon in my next video you
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
230
Hello Everyone Today's Question Obscene Statement in BSC 1st Friday Function K Small Is To Find The K Smallest Element Pith Not Given May Zoom K Is Always Valid K Always Get Victory In The Districts To Bsc Total Elements Nine Inmates Of Paper Near Whole And Cents Questions And You Will Not Get Solution On Soi Pawar Ke Iss Pawan Din Or Twitter The First Most Molested Element Tak Hai Ke Is Maulik Element In Minority Shapath Lentil Soup Band MP3 Hai Ki Iss MP3 Looks 3 Yeh Dil Luta Third Most Molest Element Which Is The Smallest Element Agency We First Tourists Molested In These Small Streams Of Vital And Mental Condition For This Question On G's Name Vishal This Problem Using Inorder Traversal 100 As Cursor In Operation Research By Doing So Will Try To All Of You Know The Benefit Of Previous Song 150 Hans Travels Most Diving Inverter Council I Think All Love You Know The Answer OK video9 Electronic Media Trial For This Jhal Inverter Is The Left Root And In Right Inverter Course Roots In Between Left And Right The Calling And Free Information Flow Su The First Thing Buddha Left element left his left most element is ok din hui hai to increase loot element rates on value 100 yudhishthir play increase and account which pizza bread one slow work out is band that is not left and right element sujavat enough two one and can cause Skin value is equal to increase and account in back to call taken back to three loan account is free leg subject no check account is equal to this industry object here no templaten rudd daily point and account is equal to days Please play list true value in a bowl address intimidation part day you will understand it's better ok on this occasion da the first is ok now comfortable 80 good night inverter function on 15910 inverter function a professional day from the first year returns that this these days online And the function was reduced and the fluidity channel oil increased to derive Vande Nischay is and counter so equal to today no Bluetooth the best dialogue in reservation written on the country its Note 3 available to call the inverter function powder right leader we call the Inverter function to market molestation and finally they return from daughters will submit or code and this was not Jhalawar accepted thank you for watching my video that this YouTube channel please consider subscribe and dont bell icon thank you for watching my video
Kth Smallest Element in a BST
kth-smallest-element-in-a-bst
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_. **Example 1:** **Input:** root = \[3,1,4,null,2\], k = 1 **Output:** 1 **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], k = 3 **Output:** 3 **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104` * `0 <= Node.val <= 104` **Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,671
307
Text is so ifine messages Gautam Cheeni to update the past behavior subscribe Free 087 subscribe and subscribe the Video then subscribe to the Page article check brothers where kids note and this is interfering subscribe 9 hai to victim of and twenty - victim of and twenty - victim of and twenty - 20 of - 151 - Davidson The whole 20 of - 151 - Davidson The whole 20 of - 151 - Davidson The whole time complexity of this app gives you are able to find out video operation in this knowledge talk about extraction updated on this sunnah ki delivery want to update the index to vis volume subscribe is effective to this time complexity ko Update Operation Software Mode of Subscribe and Subscribe To 200 Let's Talk About Doctor Mahesh Bhatt Veerwal Node The Video then subscribe to subscribe our A6 Plus 1422 A Text Message Left And Right Side And Not Believe All Subject Individual Lieutenant Android Subscribe 23 Ki Nau Comes The question how is this free help in reducing time complexity of update operation on the return very unlimited scene obligation which will not difficult given will go up till deficit in milk and finds no value and with us the findings and similarly I want you all Dual App Difficult note and water not withdrawn in this particular road do subscribe a positive parents note enter in this family tree minus plus 6 just value - point suggested value - point suggested value - point suggested that similarly divided of rudra factory patience are you will attract 2014 plus 6 prices fall g22 two 220 Vikram Seth Nutri SS Gill this Video not amazon update operation from mode of middle order to login that boat compassion house free help in the wedding gift so let's check the color of bank e want you want to very sagittarius sea note starting from appeal against 1019 Subscribe That Dead Game Entries Contra Voucher Entry To Minutes From Dengue Subscribers 98100 Notice Alive In Roots Rotting Hormone Dominant Subscribe To Hai So What We Do Will Perform To Operations And Nurses Right Side And Subscribe And Objects From To Hai So They Want to search for these two notes in the dream are using a comparison with raw current made in the decision where you want to include option or the direction and searching for these notes can be done in order after log in time to a user who is pot of The day and use this nodes in log in the middle of a research key technique that and 150 rates note servi sure plus 6 minutes and software videos destitute from 4 to 6 to subscribe my channel thank you are considered this template for segment real fog Video then subscribe to the Video then subscribe to A Report in DUSU Defined and Class Se Country Not Lost Its 65th Private Label Starting Index of the Video then subscribe to the Page if you liked The Video then subscribe to the world will Subscribe The Building The Right Left Hand Will Return Sambhog Solid Vikram Dasham Into The Free Liquid Only Rich Wasted In The Middle Of The Is Therefore Case West And South Africa Tour And If Water Resources Development Otherwise Create New Note Office Entry Withstand Electronic Prophet In Christmas Terms Of Birds And Half Inch Slicer Bollywood Subscribe Button And This Particular Person That If Back I Don't Calculate The Mid Point Of The Indicators And Left Side Notes Left Side Tours And Ride Point Idma Labs Do I Want Family Is Imperative Carrier With U I just talk about the decade nine in the laptop model time complexity of December quarter mode of and habitual building mystery that many times for this is 102 build nut and operation I in it root dot bluetooth on suvvi subscribe to e Want You Will Wash If That Mid Point Then Please Member Point Presentation Iodine Middle Point Middle Index Using Its Independence mid-2012 Subscribe To That Independence mid-2012 Subscribe To That Independence mid-2012 Subscribe To That Bigg Boss Performance Abroad In The Middle Volume Of The Current Route Otherwise Tubelight 's Last Days Till Simply Of Debt Contract 's Last Days Till Simply Of Debt Contract 's Last Days Till Simply Of Debt Contract Soft left side and its right side is the British and so on but what is the time complexity of this approach to time complexity of this approach will be border of long and that a let's talk about the final meter time when data is picture and subscribe to Their Roots Rotting Index Don't Be Equal To Start Internet Searching For All Fruits And Extension To Absolutely To Videos Thanks For Watching This Video Don't Do Computer Labs For You Guys 200ns Output Which Node New Delhi Match That Your Search Hands Free Mode On Play List On It's bear and half a minute Indra Singh Was Walking Dead decided that they want to search for give one capsules mode turn adhoi do go for mid-day mode turn adhoi do go for mid-day mode turn adhoi do go for mid-day Joe Adharm I'll find out the metal index dat is field under current root plus dual Audio In Defense That Aunty Inquest And Dash And Index The Real Looking For This Lesson Will Do A Middle Element Wool Federation Otherwise Check Weather Subscribe To Subscribe Our Channel Subscribe I Left Affair Amazon You Hunger Right Related Distributor Ko Logic And Difficult Make The Decision This Quote Notes Into Operation That Consider Bodh [Praise] The [Praise] The [Praise] The Modes A Look At How Were Playing Around Which Gives Nod To Traffic To Start From Abroad And Drive From Its Laxman Comment Similar Thing Doing Subscribe I Am Android Like Share Subscribe And Like Subscribe And Thank You
Range Sum Query - Mutable
range-sum-query-mutable
Given an integer array `nums`, handle multiple queries of the following types: 1. **Update** the value of an element in `nums`. 2. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`. Implement the `NumArray` class: * `NumArray(int[] nums)` Initializes the object with the integer array `nums`. * `void update(int index, int val)` **Updates** the value of `nums[index]` to be `val`. * `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`). **Example 1:** **Input** \[ "NumArray ", "sumRange ", "update ", "sumRange "\] \[\[\[1, 3, 5\]\], \[0, 2\], \[1, 2\], \[0, 2\]\] **Output** \[null, 9, null, 8\] **Explanation** NumArray numArray = new NumArray(\[1, 3, 5\]); numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9 numArray.update(1, 2); // nums = \[1, 2, 5\] numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-100 <= nums[i] <= 100` * `0 <= index < nums.length` * `-100 <= val <= 100` * `0 <= left <= right < nums.length` * At most `3 * 104` calls will be made to `update` and `sumRange`.
null
Array,Design,Binary Indexed Tree,Segment Tree
Medium
303,308
1,284
hey guys welcome to my channel i am napia so today we will be solving read good question number one two eight four minimum number of lips to convert binary matrix to a zero matrix so let's see what the question is along with some given examples so uh the question says that we are given an n m cross n binary matrix so by binary matrix that means that you can have either one or zero present in the matrix so in one step you can choose one cell and flip it so that means uh when you flip it means that if there is a zero you make it one and if there is a one you make it zero so you flip that cell and also you're going to flip all the four neighbors of it right so if they exist so basically we need to do this flipping till the point where we get all the matrix elements as 0. so we this is called being a 0 matrix so we have to convert it in the minimum number of possible steps that will be required to make this given matrix to a zero matrix and they can be cases where uh we cannot convert it so in that case we need to return minus one so let's see uh by walking through this example that we have given as a test case so we are given this matrix i have drawn this matrix over here so that it can be used for a clear explanation so this is the given matrix and now let's see that what are the type of operations that we can do to make it reach the 0 matrix right so you can see this matrix over here so i have made a 2 cross 2 matrix and i have labeled the indexes of the row and column so if i say that you choose this cell and you say that i want to flip this uh element present in this cell right so since it's a zero flipping it will mean to make it one so if you flip this bit right you can just flip only one bit so i choose to flip this bit and i make it one right so if i am flipping this i also need to flip all its possible four neighbors so in this case we have only two neighbors possible because the up and left neighbor is not present because it's the starting cell so they're only light and down neighbors right so we need to flip these two also so we also have to uh make them sorry to be 1 because 0 is present here so we write 1 here and 0 is also here so we have to flip it to make it 1. but we don't have to do anything with the rest of any element so the this one will be the same one right so this is the new state that we form by flipping this cell from zero to one so its neighbors are also flipped so this is one possible case uh you know one possible state that can be achieved while we are flipping bits so this is just to show you how the flipping is actually happening right so let's take another case if i say that i want to flip this bit and the state of the matrix previously was this right so if i want to flip this so first i'll flip it by making 1 to 0 and i make it i may also flip its neighbors so 0 will be flipped to 1 and here also 0 will be up to 1 but this 0 will remain the same because it's not the neighbor of this cell right so now if you see that from this state that we had previously we are able to reach to uh two different states if we flip uh suppose if we chose to flip two cells then we are able to reach to two different states so similarly if we had flipped the other two cells like this one and this one you would have got two more states so it's like that in a matrix you from one state you can have around uh m cross n state so basically m is the number of rows and n is the number of columns so you can have uh up to m cross n distinct states that you can achieve by flipping each of the bit right so if i talk about this since uh it's 2 cross 2 so if i flip every element in it i have just shown two if i flip these elements also both of them so i'll achieve two different states so total number of states will be m cross and that is two right so from one previous state i am able to achieve four different states so using these states also i can get many other different states right following the similar ideology of flipping the bits so in this way we have to tell that what would be the number of uh you know steps so basically it's like the number of states that you have to go through to reach a matrix where all the elements are zero so we have to do this so um the algorithm for solving this would be a simple bfs right uh it's very uh like it's something like you can also think about it because we are asked to tell the minimum number of steps to achieve a possible state from a given state right so uh the basic very simple kind of algorithm that could come into our minds is bfs because it gets very easy to traverse level by level so by that you will be able to actually count what is the minimum number of steps that you will be needing to achieve the zero to reach the zero matrix so um i said that we'll be using pfs but we also need to think about that we have a matrix over here right so and we also need to flip the bits of it and we have to create a lot of states right so how are we going to handle that matrix in case of bfs because we have actually not seen many such problems where we are needed to handle a matrix while doing bfs right so uh my approach here would be that you don't need to handle a matrix while you are applying vfs in your code you just have to uh think of us like a smart way to deal with this matrix so my way was to actually convert this matrix into a string of m cross n length so if you see this matrix i have written this 0 1 2 3 over here just to show you this fact that you don't need to handle the matrix in every stage of pfs you need to con you just can convert it into a string so let's start from here you have this initial matrix right so now i can convert this matrix into this string 0 and 1 so this is my initial string given to me so i'll be traversing row wise and then converting it into a string but you should also know that every time the length of this string is going to be m cross n that is from the index 0 to the index 3 in this case because m cross n here will be 4 so the indexing will be from 0 to 3. so in this similar way you can deal it with in it in the form of a string and that will make your work very easier to handle so um i hope that you must have understood this uh smart trick that i am going to use here but a question might come to your mind that how are we actually going to flip the uh bits like it's like you can flip the bit of that particular index but how are you going to identify that what are its neighbors that need to be flipped according to uh the matrix position of the elements right because this is something we have converted into a linear fashion and this is a 2d fashion right so we need to uh flip the elements uh based on the position they are actually in the matrix right so for this element the neighbors will be this and this one so we have to find actually that what is their position in the given string because in when it is being converted into a string then they need not be adjacent right so we need to figure out what are the actual neighbors that need to be flipped so i hope that it's clear so firstly uh i would like to write that how are we actually going to convert this matrix into a string so uh it's a very like it's kind of a formula just to tell you how i actually derived this uh thinking so if i say that i converted uh this matrix into a string uh which is of length m cross n right so there will be indexes from 0 to m cross n minus 1 in the string so for every index so new index can be represented as j plus i star n so by j plus i star n what i mean is so this is a formula that i derived myself while i was trying to figure out that how can i convert it into a string so uh this is just simple math even if you sit and try for just 5 minutes you'll figure it out that how can i convert it into uh like in a fashion from 0 to m cross 10 right so you can see over here that we have this first element right so the new index for the string will have to be zero uh for this element the index will be one for this element it has to be two and for this element it has to be three that is how the string will be formed right so let's figure out that how did it actually came so if you see that for this element i is 0 and j is 0 so you get 0 for this element j is 1 and i is 0 so ah 0 into n is 0 and you are left with 1 only so that's your new index for the string position of this element right and then in this case the i is 1 and a j is 0 so j is 0 then 1 cross n here is 2 we are given n is 2 cross 2 matrix so you have 2 here in this case it's 1 comma 1 i j is 1 so you can figure it out it is going to be 3 so this is how using this formula uh i actually thought of converting this matrix into a string right so this formula is going to be very helpful for us uh while we are going to find the neighbors that need to be flipped so i hope you got the party now so we made us made it a string right now uh let's take an example of how are we going to flip this so now you have this initial string so uh by applying the concepts of vfs you put this initial string into a queue right so when you pop it out you just have an element that is just string so now we have to uh as i already mentioned that from this string we can get four different possible states in this case uh because we can flip uh try flipping every of every one of its bit uh every one of its like you can flip this zero and this one so there are four possible bits that can be flipped right so you can get four different possible states so we will try to do the same thing so when you've got when you pop this string from the cube then you try to loop over this string that you got so you come to zero over here the first element is zero and its index is zero now um when you see it you only know that it's an element of a string but you need to find its coordinate that was uh its original coordinates in the matrix right so you need to translate back now so how do you get uh if this elements coordinates that were there in the matrix so for that uh i already told about this formula so if we think uh some mathematically so you'll see that the index of this element is 0 and if you divide this elements index by n so n here is 2 right so you will get this will be the x coordinate and using this formula substituting uh it the values in this then you can get the value of j that will be the y coordinate so i'll show you how so suppose uh let's say that you had uh you had this x just a minute yeah so uh we are on the index 0 of this string right so you have the index 0 as i said you divided by 2 so you divided by 2 and you got it as 0 and that is going to be the x coordinate of this element in the matrix so now how do you get the y coordinate so now you know that my x coordinate is 0 so my new index is also 0 the new index of string so this is 0 and then i have to find j that will be my y and then i have the uh i that i found here that is the x as 0 and then i am going to multiply it by 2. so you just substitute it in this formula to get the value of j back so now you find you'll find that y is also 0 so now you know this is the position 0 comma 0 is the position of this element in the original matrix that we had so similarly you can you know translate back the position of the elements uh by using this concept right so using just the same concept we are going to find its neighbors also so if this card we got its original coordinates in the matrix right so what we are going to do is so we have this element so we'll flip this first so first i'll make this as one right so i made it as when i flipped it now i need to flip its neighbors so neighbors can only be find found out only if we know its original coordinates that were there in the matrix so now you also found out the original coordinates over here right so it was 0 comma 0. so now finding its neighbors is really very easy you just have to go one step down one step right one step up and one step left so it is actually very easy that's what you just have to do so uh using this formula only so now you know the i and j right so now you know the i and j you just need to like do i plus 1 if you have to go to the right neighbor you have to do i minus 1 if you have to go to the left neighbor similarly j plus 1 for going down and j minus one for going up so you are going to get the new index of its neighbors in the string so you can flip it the way you flipped it uh flip this element right so i hope you understood uh how are we actually going to translate the string back to the matrix to get the coordinates and then get the neighbors and then again translate it back to this string coordinate system and then flip that value to zero right so let's try to dry in one thing and then it will be easily understood so i flipped this uh bit so it became one and its coordinates are zero comma zero that i calculated with this formula so now i have to find it neighbors so um finding its neighbors as i said the formula will be this formula so let's say i have to find its top neighbor right so i'll find the top neighbor so the it will be j is 0 here right so j is 0 here plus then the top neighbor i minus 1 uh if you have to find the top neighbor so i is also 0 so 0 minus 1 will be minus 1 and n here is 2 right so you got minus 2 but you also need to check that the index ranges should be between 0 to uh like it should be between 0 like it should not go out of bounds so you need to check it should be greater than 0 and at the same time it should also meet the requirements of its row and column constraints so make sure that it is a positive index not a negative index so you if this happens you have to ignore it so we have to ignore it that means we don't have a left neighbor right so now you check for a right neighbor so applying the same formula j it will be 0 and then we need to make i plus 1 here because we are checking for the right neighbor so i plus 1 here will be 1 0 plus 1 is 1 and then you have 2 right so you get 2 over here uh so i actually uh said things wrong way that if you have to look for left and right neighbors then you need to do plus and minus in j in by coordinate and if you have to look for on top and uh down neighbors then you have to do plus and minus one in the x coordinate right so i hope that's that was just a mistake while speaking but i hope that sounds good to you now so um you know uh by this we are trying to find the right neighbor uh sorry we actually incremented i plus one so we are finding the down neighbor so you saw the down neighbor by incrementing i by one so you found the down neighbor now so down neighbor is at index 2 right so that is what index 2 is present here so index 2 is this so you are going to flip it to 1 right so you flipped one neighbor now you have to see to the right neighbor let's see to the right neighbor so for seeing the right neighbor i need to increment j by 11 right so my new index will be j has to be incremented by 1 so 0 plus 1 is going to be 1 then you plus do a plus and then i has to i was 0 originally because the coordinates of this element is 0 so 0 into n so it is going to be 1 right so you find found the right neighbor at index 1 in the string so you are going to flip it to you flipped it and similarly you can check for the left neighbor it is going to be a negative number the index going to is going to be negative number and so it is not between 0 and m cross n so that means that it is not a valid index so uh there is no left neighbor so we are done seeing all the four neighbors so we can uh you know copy rest of the elements as the same oh sorry it won't be a zero here it will be a one here because the last element will be copied right so you see this state of the matrix has been translated to the string so it's a similar thing that we got so this is going to be the approach that we are going to do and you can do the bfs till you uh not find a string which has all the contents as 0 if you find that then you can return the count variable that you were keeping to count the number of uh you know number of uh steps that it is uh taking to transit into a zero string so i hope that's clear now so now let's look at the code so it will be more clear with the code so uh there here's the code and let's start from uh the top so we are given this function in which we are given a matrix right so you find the uh m and n of the matrix that is the number of rows and columns so uh now you start and as i told you that convert the initial given matrix into a string so for that i looped over all the elements and then i use two string to convert it to a string and then i just concatenated all the elements to form a string so in this variable another mean while uh since the length of the string is going to be m cross n so i also created a zero string which contains all the zeros uh of length uh m cross n only so that we know this is our final state so this is the zero string is going to be a final state that we have to match it with in the pfs right so if this string that we formed is already a zero string that means the input was already a zero matrix given to us then we can return zero because we won't require any steps because it's already a zero matrix right so uh then if it's not the case then you start the actual bfs you create a visited that we normally have in bfs right so it is going to be a string bool map and then you create a queue of string you push the initial string of the matrix that you made right now into the queue and you mark it as visited and you keep a variable i have named it flips air to just count that how many uh transitions do we have to go through to reach the uh final stage that we have that of c having a zero matrix so this is just like any other bfs problem that you would have dealt with right it's just the way how you handle the matrix uh so now since we need to traverse level by level so that we can find the minimum number of steps that we are going to need so i initially take the size that was size of the queue and then i am going to loop it into that loop up to that much uh size so that i complete uh levels by level i don't mix all the levels in one right so before starting a level you can't increment the flips by one and then when you come to the main part there you pop the element and store it into a variable current right and then as i said that you are going to oh you are going you have to make all possible states that you can make by flipping each and every bit of uh this string that we have made right so you have your i take i have taken a variable k and that is going to loop over all the elements so i am going to flip every one of it and i am going to create a new state out of it so that i can find that in which pause in which way i can reach the zero matrix first so as i told you this is the way how we are going to get the coordinates of that uh that element that was actually the real coordinates of it in the matrix that was given to us so i showed you how this works so this is calculating the x and y coordinates of that element by using this formula this i have showed you by an example i hope you are able to recall it and once you calculate it so yeah i have to flip it so for flipping the ith bit the bit on which you currently are you also need to flip that so for flipping that bit uh i have xored with that particular uh like positions content with one because whenever you xor any number with one like it's like you're going uh if you x or zero with one then you are going to get one and if you xor one with one you are going to get zero so in this way you are splitting the bits right so this is this fulfills our need so i have xor it with one so this is going to be flipped right so you flip the ith bit now if you need to flip its neighbors so as i told you that we for seeing the bottom neighbor we are going to use that formula that i mentioned and we just have to uh do i plus 1 because we are looking at the down like the bottom neighbor by standing at the ith position we are seeing at the bottom neighbor so you do i plus 1 over here and then you check that it is between 0 and m star n so that it doesn't go out of bounds of the indexes of string because the string length can be has to be of m star n so then when you get it you flip that bit and similarly you do it for top right and left and as i explained you with the help of an example so you have to do this so once you have flipped right so now you need to check that after flipping so my is my string equal to zero string so if it's true all the contents of the string have become zero then you return the number of flips till now and if it's not and if that particular state is not visited uh we need to keep visiting this to make track that we don't uh keep on looping into duplicate states that we have already visited because that can lead us to uh into an infinite loop right so you uh have visitor if this state is not visited you push it into the queue and you make it make its visit as true so this is just like any other bfs and you have to just handle it uh with more care so that you know it doesn't uh you are able to handle proper matrix in the form of a string while doing bfs one more thing that i would like to make notice of that while we are dealing with right and left we need to keep off keep a check of two different conditions as i mentioned here and you can see that uh when we created the new index here i have said that j is not equal to n minus 1 and here i've written j is not equal to 0 but i have not written any such condition in the bottom and top cases this is because uh let me show you how i'm saying suppose you are on this bit right and you are saying that you need to find its left neighbor so how do you find its left neighbor as i mentioned the formula so if you are going to the left you need to uh look at j minus 1 right because you are going to the left so the formula here will be so the j here is 0 so 0 minus 1 is minus 1 plus i of this position is 1 right and the n value is n values 2 so what you get as a result you can see that 2 minus 1 is 1 so you get its left neighbor as this but that is actually wrong you know this happens because we are converting it into a string in this fashion right you go from here and then you go from here so this actually has got linked so we need to break that link so that in actual matrix we don't see its left neighbor as this element right this is wrong it's left neighbor is not possible and we are getting its left neighbor as this so we have to check for that condition so if j equals to if you are looking for a left neighbor and the j is equal to zero then you know in that case we have to avoid looking at its left neighbor because you will get a wrong answer so avoid looking at it left neighbor because you can't have a left neighbor right and similarly if you're standing here and you're looking for a right neighbor you'll get its right number as this element you can calculate the same you'll get the right as its neighbor because we have converted into a string in this fashion right so it has got link so that is why you need to avoid seeing its right neighbors so that is why i have mentioned a condition where when you are looking to write you need to make sure that j is not equal to n minus 1 so just to avoid the wrong calculation of the right and f number that will only happen in the case when you know when you're on the first column and you're looking for a left neighbor and when you're in last column and you're looking for a right neighbor so i hope uh this is understandable and with this we i'll try submitting the code and then you can see that this code is working and i hope this could make you understand how we made use of bfs with the help of converting a graph into a string and handling the possible states right so thank you guys for watching the video
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
four-divisors
Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge. Return the _minimum number of steps_ required to convert `mat` to a zero matrix or `-1` if you cannot. A **binary matrix** is a matrix with all cells equal to `0` or `1` only. A **zero matrix** is a matrix with all cells equal to `0`. **Example 1:** **Input:** mat = \[\[0,0\],\[0,1\]\] **Output:** 3 **Explanation:** One possible solution is to flip (1, 0) then (0, 1) and finally (1, 1) as shown. **Example 2:** **Input:** mat = \[\[0\]\] **Output:** 0 **Explanation:** Given matrix is a zero matrix. We do not need to change it. **Example 3:** **Input:** mat = \[\[1,0,0\],\[1,0,0\]\] **Output:** -1 **Explanation:** Given matrix cannot be a zero matrix. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 3` * `mat[i][j]` is either `0` or `1`.
Find the divisors of each element in the array. You only need to loop to the square root of a number to find its divisors.
Array,Math
Medium
null
228
hello and welcome to another Elite code problem we're going to be doing the problem of the day for June 12th and it's pretty straightforward in summary ranges so you're giving it uh assorted unique integer array nums and then it's telling you a range is a set of integers from all the A to B inclusive return the smallest sorted list of Rangers that cover all the numbers in the array exactly and so pretty much what they're trying to say how this problem is broken down is looking at these numbers split them into ranges where if the numbers are more than one apart then split those into ranges so for example if we have numbers 0 1 2 4 5 7. take every single place where the numbers differ by more than one and split that into ranges so where's that so right here these are different one more than one and right here and so if you look that's the output so zero to two four five and seven and for the second problem it's zero two three four six eight nine so let's do the same thing so we have cut here and cut here okay and you have zero two three four six eight nine so now the only other part we have left to do is for all these ranges how do we represent them as a range right so how do we represent zero instead of zero one two how do we do this so if we can do that then we're pretty much done with the problem once we know that these need to be more than one apart it's pretty straightforward but we can actually maintain is we can maintain a start range and an end range number for each of these and once we get to a break then we just ask ourselves is the start range and the end range the same if they are just output the one number and if not then output the whole range and let's see what that actually looks like so we're going to go through these two examples and we are going to go through them and show you like so let's say we have this output array okay and then so initially we're going to declare so let's just say S and E we're going to declare start and end to be the first number in the array so they're going to be zero and then all we're going to be doing is going index by index and asking is the current and is the current index more than one greater than the index before and actually sorry instead of the next before we're going to say is the current index more than one greater than this end so we're going to go to one remember we initialized them to the first element so we don't do that so we go to one and we say okay is it more than one greater than the next before no it's not it's only one greater so let's update our n to one now we're going to go so we're at one now we're going to go to two and we're going to ask ourselves again is it one greater or more than one greater than that no it's not so let's update that to two now we get to this four the four is more than one greater than the N so now what we need to do is we need to check and start in the end if they're the same we need to print one number and if they're not we can simply print the range because we have the star and the end so we're gonna do start to end now we are going to update our values so we have a new Range we're going to once again make both the start and the end the same value so 4. now we go to Five is it more than one greater than the end no it's not so we're gonna update this to be a five go over here is it more than one greater than the end yes it is so now we look at our start in their end they are different so we're going to have a four to a five and then finally once we actually finish the loop so when we're at the seven we're gonna have the seven once we actually finish the loop we do have to check one more time for this case because we're still going to have a start and an end so once we're done with a seven then we look is our start and our end different no they're not so we'll just put in one of them and so that's the answer for that one now let's look at example two and this should be pretty straightforward so we have start and end we initialize them to be the first element in the array here we go over here is two more than one greater than n yes it is so now we check is our starting end different no they're not so we're just going to put in the one number we're going to update both of these to be the two go to the three is only one greater so we're going to update this to be a three go to the four only one greater update go to the six it is two greater so now we're gonna check start and then they're different so we need the range and we also need to update our numbers to both be six now go to the eight it is two graders so they're the same so we're just going to put in six update both of these to being eight go to the nine it's only one greater so we're going to update our result and once we're out of the array remember we have to do one more check so they are not the same so we do eight nine okay let's take a look at uh yeah so that's correct okay so that's pretty much the whole code where we're just going to be looping through this thing and we're just going to be checking and so let's actually code that up okay so first of all what we're gonna need is there is a case where the array is empty and if there is empty we just need to return nothing so it's not this we do need to have a result and we need to have a start and stop like I said before so or start and end now we need to Loop or we need to actually make them equal to the first number of nums so num zero nums zero now we need to Loop through nums but we don't we need to skip the first value so if nums I is greater than n plus one remember if we have more than one difference that's what we do here and then also if the start and end aren't the same then we need the range so if start does not equals n then rest your start plus b Arrow plus Str and else res dot pen TR and they're both the same you can pick either one and now we also need to update our new values right so start I and so if that's not the case then we need to update our end value and that's just going to be nums I okay now finally once we break out of the loop we also need to do this code again because remember we're still going to have a starting and end value once we break out so I'll be there okay hopefully that's it okay nice okay perfect so that's going to be all the code for this let's go over the time and space here and so for the time we are looping through this nums array once so that's O then we're not doing anything special like in the loop or anything we're just looping through at one time base so if you do count our res we can have like uh we can have n total outputs but if we don't kind of res which most solutions don't then it's Big O one because we just have a start and an animator constant values so yeah so I think this is the time space and that's going to be all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel thanks for watching I'll see you next one 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
122
hi guys welcome to channel this is vaga we're going to do another leash good question and the question in question is going to be number one to two best time to buy and sell stock parts two right so you're given an array of prices you're supposed to buy and sell as many times as possible with the aim of making as much money as possible right so how we would do this is in this case we would buy on the low days and sell on the high days like if um if we since we know the price of tomorrow we buy at one and we sell at five make a profit of four then we buy at three and we sell at six we make a profit of three and four plus three seven right so how you would do this is um we check if first you check off if there is actually if the array is long enough for us to consider it right so we say if not prices or the length of the array is one right uh we just want to return zero in this case um because we can't do this in such a situation we could create profit and um profit is going to be zero start off at zero and afterwards we could loop through all the numbers and we say for i in range and the range is going to start at one because we need a previous number to consider right so we just say land prices like so we need a previous number to consider so it starts from the second element and goes till the end and um we check if prices at i is greater than the price before it right prices at i minus one if this is greater than that we just we sell and for that we just increase our profit right we say profit plus equals and this is going to be prices i and afterwards we're going to subtract the price today minus the price the previous price right oh yesterday so we say prices i minus one like so and after all this we just need to return whatever our profit is going to be right return our profit like so if we run our code this is of course going to it's accepted and if we submit it accept it pretty much accept it right so this is going to be constant time um so it's going to be oven because we uh the time we go through our entire array we don't create any structures so the space complexity is going to be over one pretty straightforward thank you for watching subscribe to the channel to our channel subscribe to the channel if you're new and i'll see you in the next video
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**. Find and return _the **maximum** profit you can achieve_. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 7 **Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. **Constraints:** * `1 <= prices.length <= 3 * 104` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming,Greedy
Medium
121,123,188,309,714
1,192
hey what's up guys uh this is jung here so today uh today's daily challenge problem right number 1192 critical connections in a network so this one is a very classic you know a graph problem you know okay so let's take a look at this description here so your direct n servers numbered from n to zero to n minus one right connected by undirected server to server connections right basically you're given like a connected graph a connected un direct undirected graph right and you we need to find all the critical connections in this graph so what does a critical connection means right so a critical connection is a connection that if it if removed will make some servers unreachable right which means that you know there are some uh address right in the graph if you remove some of the address you know basically this server but basically this graph will become uh unconnected right for some parts so for example right we have uh this one you know so the answer is one three and why is that because you know for this one two zero one two right we can remove any of those graphs right and after doing so you know this one zero one two they're still connected but if we remove this one and the three right if this one is gone basically there's no way we can reach 3 from 0 1 2 or the other way same thing there's no way we can reach 0 1 2 from 3 right basically this is something like a bridge right between two components and there's the constraint is pretty standard right 10 to the power of 5. okay so after reading the descriptions you know some of you might have some uh already have some thoughts right so it's kind of obvious in that you know is that we just need to find like a graph right uh find a edge in the graph that's a serves like bridge but how can we do that right so let me try to give you some examples here you know the uh so what is a graph what is the bridge in the graph you know let's see if we have some like address here you know right this isn't another one maybe this one okay right so if you if i give you this example here right so what are the bridges or what are the critical connections here in this graph so we have this one and two right because only these two edges are a bridge because all the others you know we can always remove one of them but after doing that you know this the connect the connectivity of this graph of these components that doesn't change right so now the problem becomes what becomes to oh and before doing that you know so but how can we uh how did we find these bridges right if you look at each of the components right we can clearly see that you know a bridge work a critical connection work is it's not does not belong to a circle right because all these kind of components they're all part of the circle right even for this one so which means that you know if it's not part of a circle then it is a connection it's a critical connection and for this kind of uh components you know for each of the components it's this one is not like a strongly connected com component right so it's a little bit different as strongly connected components in this case you know so strongly connected components means that you know any pair and each pair of these components have uh will have like an edge right but this one is not this one is extremely com con scc this one is not either base so this in our case all we need to all we need all we care is that you know if this edge or if this node is part of if this add is part of the uh a graph oh sorry a circle so now the problem is that how can we find address right uh belongs to part of a circle no you know we all know that you know to detect if a circle exists in a graph we can simply use a dfs right i mean so let's say for example i have this kind of node here you know now this node right and then like this one right let's say we have this kind of uh zero nevermind so we can simply use dfs right to check if a circle exists in the graph right we simply uh start anywhere right we can start from any anywhere and then we do a dfs and every time when we see a node you know that has not been visited right we mark that node to be visited you know so when we see the moment we see a node the moment we see a neighbor which has been visited before then we know that okay we have seen like a circle right basically you know if we have if we mark so if we see this one it's not visited and then not visited not and not right but when we reach at this note here you know uh we have seen okay one of the neighbors you know they have already been visited right i mean of course you know we will not consider the parents right so when we find the neighbors you know we'll uh simply ignore parents so basically when we reach this one you know this note here you know we're not looking at parents so we see okay the neighbor is this one but this one has already been visited which means we have find like a circle right that means that you know okay so this one this node this edge is part of the circle we can simply remove that right so let's say we have a b c d e and f right so which means that you know the add c and f we know okay so certainly it's apparently it's like part of the circle we can simply re we know that we can simply remove it from the uh from the add set so what i'm trying to do here is that you know if we can remove all the edges that belongs uh belongs to a circle you know so what's left in that set will be our answer right so this is clear right but you know the question is that how can we remove the address you know the c and f is already removed but how can we remove the address for uh for all the other address like cd de and ef right so how cd the an ef this one we already we know because we've we detect a circle here right that's how that's when we do that's when we remove this or this uh this edge but how about this three because when we are traversing this kind of three notes here you know we don't know if there's a circle at this time so how can we do it right so in order to do it you know there's we have to use something like a labels where you can call it a rank you know basically instead of like i said you know to detect a circle we mark this node to be visited so we can mark it instead of market uh simply market we can simply give like a label or a rank to e to each of the node basically the sequence we visited this node for example you know if we re visited this node so i would give this one a label zero right and then the next one will be one and this one will be two right and so on and so forth and the next one will be three four and five right so oh by the way so this algorithm is called a target algorithm because you know this algorithm was developed was created by a guy called i think robert tarjan in 1970s if i'm not mistaken but okay regardless you know so basically we have like a label here you know since we have already visited two here you know now you know when we add when we are at three or four or even two right because two we also need to know if this two is like part of the uh the circle you know if we if in the dfs right so we always use dfs so if in the dfs if we return the minimum labels for each of the uh for each of the node here so which means that you know when we add three here you know we call df as of four right and then in four we call dfs of five and in five we call dfs of two right but you know since two has already been visited we simply return that label right and in each of the node we always return the minimum label that we can get from five so which means that you know when we're at three four and five we always get two right and then we can simply use that returned like minimum label to check basically you know as you guys can see if the current label value is either greater if the current level is either equal greater than the return one right we can call the recursive right recursively a label here you know then we know okay so this note right or this where this edge is part of the circle right see it makes sense right because you know if you had like one here you know so we are at one right so what's going to be the recursive of one here because at one will we will recurse uh with two right so the two returns one so the two returns three four five and then back to two right so the two will return two that's why you know for one two is not a part of the circle but if we have like another add let's say from five to one okay so now one is part of the circle and why is that because you know so let's uh go over this logic one more time so from zero to one from zero we recurse to one right from one now we recurs to two same thing right same thing for two three four and five okay so keep in mind that so now five uh besides the uh the parents it has two neighbors right it has one and two and where both of them have already been visited before so when we return at five we return the minimum between those two which is one right that's why you know when we are at a one here no so when this is like the recursive finish this one got return to here now one is also part of the well basically now one equals to one so that's why you know we can tell so now this one is part of the also part of the cursor right yep so that's the basic idea so it's basically three steps a few steps so we start from a dfs traverse traversal and then and the second you know when we mark the visited node uh we simply we add like a label for each reach of the unvisited label and then in the end right and uh and then we will also compare right we also compare if the car if the current one is greater than the re then recursive label if it is and then we know okay we can remove the current wouldn't we know the part the current node or where the current edge between the na the child and the parent node is part of the circle we can safely remove it right and then in the end we return the at the minimum likelihood label among all those kind of recursive labels yep so let's then start coding uh let me see so first uh first thing first we want to create like a graph right so the graph is going to be a default half dictionary default dictionary of list right and this is all standard we have for u and v right in connections we have graph dot u dot append v right and then we have graph v dot append open u right and then like i said i'm going to need like a label right for each of the node so at the beginning uh i was starting the label to minus one i guess you know or you can use zero it doesn't really matter i think for me i use zero because maybe the first one i use will be zero one but anyway i use i initiate everything with minus one and yeah and for the answer you know since this list is kind of like uh it's a list you know when we remove from it will be of n time complexity that's why you know to make it to make the remove faster i would create a stat i'll convert this connection to a set right so that's why you know i would use like i put everything into an answer set right and when i'll just use the same photo here let's add this one to the answer but you know since you know the sequence so since this connections could be either zero one or one zero because when we visit this uh we do the dfs later on you know the sequence is not guaranteed right so one so two could be the parent or one could be the parent so either one is possible that's why you know when we initiate the answers you know we can define like a criterion which means that you know we always put the smaller note before the greater one right so we can simply do a minimum of u and v and then the max of u and v so just a little bit little trick right to remove some sum of hassle here okay and then the uh the dfs right so for dfs first one is the current card node and sec i use like the parent i also pass in the parent just to help us to determine uh if the neighbor is the parent right or you can use the modern ones but i just say uh prefer to also pass another like the additional parameter for the parent and then this the last one is the pre-label one is the pre-label one is the pre-label so basically it's pre-labeled means that so basically it's pre-labeled means that so basically it's pre-labeled means that you know it's the uh it's the biggest label we have been assigned so far right um cool so the axis condition which means you know if the label if the current one has already been assigned to label we simply return that label right which means that you know if the labels dot u right is equal greater than zero right then we return it we simply return that label because it means that we have already visited that node labels okay otherwise we assign the label for the current node right it's going to be a pre-label be a pre-label be a pre-label plus one right car node okay so now the next one is that we loop through all the neighbors right so for v in the graph right graph u here and oh we also gonna uh maintain like a label right the minimum label of the car node which means that you know what is the minimum label we can see from the cart node right which is the system at the beginning it's system.max beginning it's system.max beginning it's system.max right so for here you know uh first we check if the v is equal to the parent right we simply continue it means that you know if the neighbor is the parent we simply ignore it right because we don't want to revisit the part or go back to the parents otherwise i have this kind of recursive label right i mean from the dfs of what so now the current one becomes to v and the parents become to the current one becomes to the neighbor and the parent becomes the current one right and then we also pass in the labels right of u that's going to be the last label we have assigned and like i said so if the labels dot u if the current one right is either equal greater then the recursive labels right that means that you know it means that you know both u and v is part of the it's part of the circle right which means that we can remove which means the add u and v is also part of the circle and we can remove it also remove from we can just copy and paste this part since you know we're going to use the same logic here right so this one means that i know u and v right are both part of a circle and then keep in mind that you know every time we have like a recursive we're gonna update this minimum label right the minimum of minimum label of the uh of the recursive right and then in the end we return the minimum label right so this one is like necessary because remember so the uh if you remember this one you know the uh so we have a we have zero one two three four and five right so if five has another like add to one here you know when we are at five right so five have two neighbors have two v's right one is one the other one is two but here you know we want to return this one we want to return one instead of two right that's why you know when we i at one here you know when we add one here you know one recursion to two and all the way to five and then in the end it will return one right and when we are at one here if we go back right so one we're pointing to two in this case right because you know we're using dfs you know even uh so even though one has two neighbors which one's two the other one is five but since we're using dfs you know basically it will always follow one path to the end which means that it's gonna kind of follow two so two also have five to three but you know assuming we will always go to three first and then four and five right and when we are reaching five here you know so five will get uh we'll see okay one is already visited right and two is already visited that's why you know five will return one and then it backs to one here you know so here you know u is one right and then this label is one so the recursive label for the two for the recursive this one is also one that's why we're gonna use the uh the label uh equal greater than one so that you know we can remove this edge one and two from the answer set right that's why that's how we can remove one uh to add one and two yeah and when we uh when we reach at five one five you know i think that will just simply be ignored you know because you know so when you use one right so we have one we have two and five so two has already been uh set right has been re uh processed and then for five you know when we are reaching five but the five has already been uh visited right so which means that you know for the branch of five when we're at a one note here you know it will simply be it will simply return label a five in that case right and yeah but this one will not be uh affected because you know so in that case the income in that case the recursive label will be five but the five is greater than it's greater than one right that's why the minimum label for the node one is still one okay um yeah i think that's it and if there's no circle at all right so in that case you know it's just a one uh one single like line here you know in that case you know if you start from here you know the starting point is max size you know so for the neighbors so this minimum level will be what would be the they'll always be like the uh i guess the system max right which is fine i think because you know in that case we simply don't um let me see here yeah because you know in that case you know the minimum labels you if in this case they're all like um system max because it will never uh because this recursive label right i mean it will always be uh be what be the system max in this case and but since you know we're comparing this label the current label with this recursive label you know the current one we start from zero right will never be greater than this system max right that's why you know uh we can either use if the system max size is fine okay sorry so sorry about the side track here so let's finish this uh code here you know so after implementing dfs uh the last thing is just simply do a dfs uh we start from zero right and the parent from node zero minus one and then zero so this one you know we can start from any node from zero to n minus one will work i'm just uh happened to pick the first one and yeah and the label that's starting from zero actually i start from one because you know uh because the first one will be uh will be the pre-label plus one so that's will be the pre-label plus one so that's will be the pre-label plus one so that's why you know the label starts from one but it doesn't really matter right and now i simply return the answer so that's it right so if i run the code accept it right and submit all right cool i mean yeah so that's it right i mean the time complexity right and so this is like standard a dfs uh search on the graph right so which means which makes it a time complexity is the v plus e right where v is the number of the nodes and the e is the number of edges right and the space complexity is o of e right because we are creating um actually we have a graph here you know so the graph is like the uh it's total number of the edges right that's going to be the total time complexity and yeah because in this case you know address is either equal or greater than v not necessarily because in this case you know h is equal to v minus one if it's a tree if it's a spinning tree right but if it's like a completely uh if it's like strongly connected graph you know so this add is greater than v but you know v and e and v e will be uh i will have this greater like scale right of v that's why you know i use e to represent the space complexity right and yeah and so just to recap real quick right so this problem actually it's essentially asking you to find the edges right or to find the add if this add it belongs to a circle right so the way we're checking that is that we uh we mark each visited we assign each visited node label right and then at each of the recursive call here you know we are we're getting the recursive label right from the recursive call and we compare that if the current label is either equal or greater than the recursive label if it is then we know it's part of the uh the circle and then we can simply remove the edge yep so that's the core concept here uh yeah uh i'll just uh stop here thank you for watching this video guys stay tuned see you guys soon bye-bye
Critical Connections in a Network
divide-chocolate
There are `n` servers numbered from `0` to `n - 1` connected by undirected server-to-server `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between servers `ai` and `bi`. Any server can reach other servers directly or indirectly through the network. A _critical connection_ is a connection that, if removed, will make some servers unable to reach some other server. Return all critical connections in the network in any order. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[1,2\],\[2,0\],\[1,3\]\] **Output:** \[\[1,3\]\] **Explanation:** \[\[3,1\]\] is also accepted. **Example 2:** **Input:** n = 2, connections = \[\[0,1\]\] **Output:** \[\[0,1\]\] **Constraints:** * `2 <= n <= 105` * `n - 1 <= connections.length <= 105` * `0 <= ai, bi <= n - 1` * `ai != bi` * There are no repeated connections.
After dividing the array into K+1 sub-arrays, you will pick the sub-array with the minimum sum. Divide the sub-array into K+1 sub-arrays such that the minimum sub-array sum is as maximum as possible. Use binary search with greedy check.
Array,Binary Search
Hard
410,1056
168
hello and welcome to another video in this video we're going to be going over Excel sheet column title so in this problem you're given an integer and you want to return its corresponding column title as it appears on the Excel sheet for example a should be 1 B2 C3 z26 a2728 so the difference between this and a base 26 implementation essentially is what you're trying to achieve is in the base 26 A is zero B is 1 C is 2 and so on so we have like a base 27 but not quite because a is one Z is 26 and there's nothing a zero so we need to basically kind of like a pseudo base 26 implementation what or sorry base 27 implementation but not exactly and so the only trick we really need to know is how to convert numbers from the base 27 to this like Excel or from the Excel base 27 to a base 26 implementation essential and so it's pretty straightforward when you have a number you will first subtract one and then you will add A's ASCII value so another thing you're going to want to know is there are two python operators that are good to know so there's Ord where you if you give it a character like let's say a it will give you the ASCII value so I think a is like 64. and then there is CHR which is the reverse of that where you give it 64 and it will give you a and so those are going to be important to know so our algorithm is going to be pretty straightforward it's going to be we have some number let's call this column number let's say it's one here and we are going to subtract one and then we're going to say this is going to be in a while loop like while our number exists so while our number exists tricky like honestly the harder the hard part about this problem is like kind of understanding what to use in your conditions because it's a little tricky with the minus one I'm like do I mod do I divide the actual algorithm itself like once you see it's like almost no code but it's just kind of tricky to figure out like where exactly do I need my numbers you know how exactly do I get everything to match up but yeah so for one you would say like okay we have zero and then we're gonna have some wrap put called like res which is going to be an array and so we have zero so that's then what we're going to actually do is we're going to take whatever our number is we're going to mod it by 26. zero mod 26 is going to be zero and then we are simply going to add the ASCII value for a to it and then we'll change that vacuum to your character so we'll just say like 64 plus 0 change that back into a character we will get a here and then we're going to put that into the result and then our result array is essentially going to be backwards so let's go through the second example let's do the same thing so we have 28. okay and then we'll go through this last one as well okay so for 28 we are going to subtract 1 we're going to get 27. we're going to have a result as well and we're going to keep doing this until our result is zero like we're gonna get here's until our result is zero so now let's uh let's think about like what do we need to do so we have 27 now we are going to mod it by 26 we're going to get one and this is why we needed that uh this is why we needed that conversion from b equals so in Excel b equals two three a b c so a equals two but we want B to equal 1 for Arbor implementation to do this I have to do this is a modding so we're going to get one then we're going to say okay what's the ASCII value for a 64 plus 1 65. then we're going to take that and make that go back into a letter so character 65 is going to be B we're going to add B to our result in backwards order so we're gonna keep appending our new letters we're gonna have a b here so we're actually appending it normally but then we are going to be uh reversing later but I'll show you what that means so okay so we have 27 we got the B now we have to do 27 now what do we do next we have to divide by 26. so we divide by 26 we get one and now we do this again right so we have one we subtract one we get zero and then we do this mod 26 and we get the letter A when we do that so our letter A will be over here and now our number is zero so then we're done and now we get our output and we're just going to return that in reverse order and we can use this for z y as well for this last example let's actually delete some of this and then I'm going to write down just like the overall steps to make it a little bit easier so let's do this last example for z y so we have z y we have 701 and we will subtract one and we're gonna get 700. now we need to mod it by 26. so let's mod it by 26. we have 700 mod 26 equals I wrote the mod packets or whatever and we're gonna actually pull up the calculator here uh can we do this oh we could do it like this we can do 700 divided by 26 is 26 so we'll do 726 times 26. okay 676. so 700 mod 26 is going to be 24. okay now we are going to take a and add 24. so that means if a is 0 24 will actually be the 25th character so a plus 24 will actually give us y right it'll be the 25th character which will give us y okay now that we did that we're going to put Y into our result so let's put make a result here and we're going to put in y okay now we take our 700 and we divide by 26 so we do a lower divide and that is as I showed you earlier it was 26. okay so now that we have 26 we do this again we subtract 1 we get 25. and then what's a plus 25 so that is going to give you the character for Z right so that will give you the character for Z because Z will give you like 25 will be z a will be zero right because it's zero index now so Z is in the 26 is the 25th because a is the zeroth character so we get Z now we put the Z in here and then finally we do 25 divided by 26 and we get zero so now we're done and notice our result is once again been backwards so let's write down our generic steps so for the generic steps it's going to be Loop while number is greater than zero and then in the loop we're going to have subtract one from the number to account add to account uh for Excel one column start right instead of a zero index a one zero index one indexing okay now we mod number by 26 and add to order of a then get character from that and like if our number was Zero order of a plus zero would give us a if our number was one or div plus one would give us B and so on it's just how far away you are from a so you don't need to know the ASCII value for eight percent and then we floor divide the number by 26. and then finally we return result array backwards joined because we're gonna have a we're gonna have an array of characters you don't wanna just keep adding to a string in Python right you're making a new string so we're just gonna uh it's called we are going to reverse the array and then we're going to join the array uh and then we're going to return that okay so let's code that up okay so we're gonna say results people's an array and we're going to say well column number okay and then we have to do column number minus equals one right do I count for the zero indexing okay and then we have to do a result dot append and this is going to be character of Ord a Plus and this is going to be uh column number one okay so we're essentially taking a we're adding this mod and then that'll be like the new character that we're adding to our result array now we have to change our column number so column number lower divide by a 26 and now finally we need to return uh so we're going to join this array but first we need to make it go backwards all right so we're going to join this array but we need to make it go backwards in Python you just simply do this okay let's test it out so this is the reverse and so that did work and you can see that it's reasonably efficient it's kind of weird like I think it's all over the place I think most people also use like an O of n solution so if you just like submit it's all over the place because I think everyone has roughly the same solution or at least close to it so okay so let's think of the time and space here so for the time if you think about it we have our number right we have a number and we're just dividing by 26 each time so this is kind of like a log base 26. but in a log you don't really differentiate like what log base like a normal binary search and all those are log base 2 but as long as you have a logarithmic function it's just logarithmic so the time is going to be a log of n to get down to like that number right but we do also have to join this result and so what's that going to be well that's also going to be actually like if you think about it the number of characters there's every K there's a character for each one of these so it'll be log n characters as well if you think about it so to do this join this result it would also be login so this would just be login like this array would be login length essentially and then we're just you know reversing it which would be log n and then we are joining which Vlog they would be n but and like the value of that length of the array is log n so it would just be like something like three log n or something for our time now for the space if we're not including our result array we are actually not using any other variables we're just doing this column number in place and we are just using this result array so this actually be o1 space um but yeah I think the hard thing about this problem is just learn like figuring out I do think it's a little bit tougher than easy problem it's like an easy problem with a trick is like to figure out like how exactly do I get my indexing to work or my numbers match up like the so I really don't like this problem to be honest but you know um I mean I guess maybe if you use Excel you've seen like these formulas so it's a little bit more intuitive but it's not super intuitive to figure out that like you need to subtract one because like you can't understand that they're not exactly correctly indexed so I think if you did get a problem where a was zero and Z was 25 and so on right indexing that should be like really straightforward and that would be like an easy problem for sure because then all your stuff matches up but this little one little change is a little tricky like where do I need to subtract what do I need to divide by and there are like alternates of this problem like I think I've seen a problem like this on code forces that had like a go back and forth and honestly I don't think it's super easy because they're all like a decent amount of edge cases you have to look for but I guess that this one's not as hard as that one but yeah um I will say not a huge fan of this one but this is how you do it so if you did like the video please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Excel Sheet Column Title
excel-sheet-column-title
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnNumber = 1 **Output:** "A " **Example 2:** **Input:** columnNumber = 28 **Output:** "AB " **Example 3:** **Input:** columnNumber = 701 **Output:** "ZY " **Constraints:** * `1 <= columnNumber <= 231 - 1`
null
Math,String
Easy
171,2304
229
Hello, this will be discussing question number 229 of majority element 1000. Before this, what was asked in the discussion that we have about the element which is majority element, there is nothing in it and this notation is given in it, floor notation, it is called rotation. So there is nothing in this that which was its closest interior, give less and equal, it is a simple thing, 1 point, something will remain, okay, so we have to come out that ny3 times more love happens and that flow rotation is happening. And what is the total length that we have, its nine is okay because of the possible majority element inside. Now our first thought of mind, what should come in our mind that brother, the first possible number of possible majority element is okay, how many can be there? Use it a little, think, pause the video, then resume and see what happens, then the answer is this, how are you majority element, what is upper Morgans, upper karna means days, first of all, I have one, I divide it in ₹ 300, divide it in ₹ 300, divide it in ₹ 300, okay, so if Any element is more than 1/3 off, it means any element has to occupy more space than one third, so suppose I call it here and I call it e2 and let's see what we did now off D. Hole, there is majority element, yes, now so much space is left, hence this space is less, hence max can be you and it could also be like this, no one can do it. Do you understand, you have to try to understand from the diagram that N brother has said three. They have asked to divide into N/300 and they have asked to divide into N/300 and they have asked to divide into N/300 and they have asked to list all the elements which are occupying more than 13 and are occupying third place on it, so I think it must have been understood that you should come with maximum elements and make majority. Element 2 Elements Can See Majority Element Okay, this thing is clear, now we will approach the question, this was very important, I will explain this question very well, don't worry about it and now I am just following it, if you do n't understand. If you come here then see again what is happening because it is very important to understand small things, you are the build and the engine is the word, difficult question. If you think like this, then if you think like this then it will help a lot, so I question you in thinking to deal with this, right? Now what we did was that Max Van can be the majority element and there cannot be any other element and here you are but there can be only one. Okay, now what we did here is that I had made two people of Retailment First fight and I explained why they were canceling each other. We know that there is only one winner in it. What does one winner mean? One minute means a majority element will come out. Well, in this we can say what will we do, how many people will fight here, three people will fight, why right, because there can be elements here, two people, there will be two winners because all three will fight, that means two have been said and not two majority elements. Therefore, if there are two people here, there can be two majority candidates, there can be two majority elements, then sometimes they will fight, sometimes they will not fight, they will not cancel out, I had explained the whole example, it was understood only on the basis of canceling out. But the D moment is here, three people go to A, then there will be a fight because only two of them can fight, two people can live, so this fight will be an answer platform, there will be a fight of three people, this is very important. To understand the point, let me show you how it is going on in real life and 12 3456789 10 11 Okay, so first of all we will not make a fight between two people, so I will write the rules, fair fight is not yours. Triplet fight delay means if we get a different candidate then we will not fight now but if we get a third new candidate then we will fight then we will cancel it, we will make the fight between all three because we have only one of them. Here, two out of three can win, so three people will fight, three will kill each other, only two of them will survive, only two of the three will survive, okay, so we have taken everything, that is C1 and wick I write down the people and life count, I write down C2 and I write down the C2 count, so here is a van, its account is also a man, okay, I came here too, I got C1 here, it's good brother, so be my life. Gone, there is still van and Situ became mine because I got two, then I came here, then I got C van, then I will learn here, I will increase the count and three, then I came here, then I got C1. Now here I am, my account is done, now I have got a new band here, now I have not made anything, right now I do n't have anything, otherwise I will give it to you, brother, you go, now you have got this for me. Don't fight, nothing is getting canceled right now. Look, these two darlings are still in retail. They will not fight in cn2 because two people will not fight right now, even three people will fight. Two people are happy, brother, you both are winners now. So both of them keep fighting, there is a count here, C2 again met C2, now we have a new candidate, this new element, now there will be a fight, now it will be fun and if you fight with four, if these three boys are finished then it is finished. It is done, the count should also be reduced, it should not have been okay, now I have come here friend, again a new candidate has been found, then there will be a fight, now this one will fight, do you understand then what did he do, he killed C2 by zeroing this account. Killed C1, accounted for all of them, now a new C2 will be formed which will be a van, now I have come here, what will I do, here I am again, I have found you, now leave the account with me, I have information of candidates. Is it possible to see the majority elements, it is still randomized and neither is there in the majority element nor I nor the tax, so we will have to pass the second pass, what was there in the second pass, we have to check once, how is the frequency of the van, what is its frequency and then the election took place. So vote gaining is not the whole battle van and six are d majority element always exists so we did not need to check but here it is possible that there is zero majority element so in this we must have understood that tree so quality yourself is very easy. The first one has to be expanded a bit, otherwise if you don't understand then no one will do the court. If we are together then it's okay then let's do the court. I have written a little bit in advance, this is just the initialization part, this is first of all our result. In which we will run our look, in this we will check Han, here first of all our I, is it equal to C1 or is it equal to C2, first of all we check that whoever takes out life, we will increase his account, first of all I check. That brother, we have come to any element, the same van is there C2, what is the hit, do it plus, do it okay That That That brother, only one element with one element is eliminated, only one party is eliminated, one of the C2 accounts is eliminated. There is a C1 account, if it ends then what will we do? We will sign the one who has killed us, or we will sign the one who has killed us, there will be a new candidate for this, for the seats, we have done it for CITU, update the CITU counter. Update the two CITUs, what are you doing? You are creating a fight among the three, which means you are killing the elements of both the parties. You are killing all three. The two candidates on the number reduce the accounts of both and that of the third one. We don't have the count. Okay, now here we have to check. So first of all, what can we do to reduce the votes? End non stop sign = C1, we have it from the previous algorithm, so what can we do with C1 under score count. Plus plus do this is also for C2, now what will we do give the result of back should be BC van, if it is so then do it bag situ and this we will see by running it, okay submit and see time It's a great video, you will understand, thank you
Majority Element II
majority-element-ii
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** \[3\] **Example 2:** **Input:** nums = \[1\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1,2\] **Output:** \[1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow up:** Could you solve the problem in linear time and in `O(1)` space?
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
Array,Hash Table,Sorting,Counting
Medium
169,1102
128
128 longest consecutive sequence now the question is a medium level question and it is saying that given an unsorted array of integers so the example we have here is a hundred four two hundred one three 132 return the longest length of the consecutive elements and we have a constraint here saying that we have to write this in linear time so just by looking at the example here we can see with our eyes that the longest consecutive sequence is one two three four but um how do we do this programmatically um since it's an array we know we have to iterate um so you know starting at a hundred how do i know where this hundred is in the sequence is it the beginning is it the end is the middle um are there other numbers that contribute to an increasing sequence so for example if we had a hundred one 101 102 103 and we started at 100 we know that this is the beginning of a sequence because there's nothing less than a hundred if there was 99 it would be not the least or not the start of the sequence but because 99 is not in the array there's no number that is less than 100 we know that 100 is the beginning of the sequence now say for example if 99 was in the sequence then we would start at 100 and here we'll say we'll ask ourselves is there a number that is one less than 100 here well there is so then we would start we would go to 99 and is there a number that is one less than 99 and here um there's nothing that's one less there are numbers that are less but nothing one less so 99 would be the start of the sequence and you can see how i need to look up the values in this array right which means we probably need a map so using the example here i will give you a set here with a hundred ninety nine four two hundred one three and two um that's the set that we need to create from our nums array um and starting from the first index for the zeroth index we have our current number is 100 and our max sequence initiated as one so if there is a number that is below 100 we know that 100 is not the start of the sequence so we'll ask ourselves is there a number that's below 100 well there is 99 so we don't do anything and we move on to the next index now the current number is 99. is there a number that has one below 99 there isn't so what we do is then we ask ourselves okay we've reached the beginning of the sequence is there a number that is one above 99 and there is it's a hundred so let's set the current number to 100 and we'll increase our max sequence by one and then we move on because at a hundred right here we're seeing is there a number that is greater than 100 by one there isn't and we've ended our loop here so we are iterating through the values here and when we find a starting point of the sequence we need to ask ourselves what contributes to increasing the sequence is there a number above 99 is there a number above 100 and once we get to that limit we'll move on so starting at four is there a number that is less than four and there is so we keep moving on to the next index at 200 is there a number that is less than 200 well there isn't and this is the only sequence that there is um so we move on and now here we are at one so is there a number that is one less than one we check our set and we know that there isn't so we know that this is the beginning of a sequence and now we ask ourselves is there a number that is greater than one and in fact there is which is two so we set our current number to two and now we ask ourselves okay is there a number that is one greater than two and it's three and we increase our max sequence we're increasing our max sequence as we go along now we ask ourselves is there a number greater than three by one and there is and it's four and finally we ask ourselves is there a number greater than four no there isn't so we end this loop and we move on to the next index and so on so let me show you how the code looks like the first thing that we can do is just say that if the variable that we've given is null or has a length of zero right there's nothing in this array um what we want to do is just return it return zero now the next thing is we want to create that set that we were talking about where it records the occurrences of the numbers that are in this nums array and we do it with our javascript set function and then we'll have a max which is setting to zero and this would be the return value because we want to know what the max consecutive uh sequence would be so as we said earlier um you know let me just make a little comment right so if there was a five four three two one and we want to iterate through each of these so let's just say let num of nums or actually no sorry let num of the set that we've created because we can iterate through this now we're saying that if that number has so if there's a number that's less than the current number that we're at right so that means it is not the start of the sequence what we want to do is just continue through it we're going to skip that all together now otherwise we're going to say okay the current number that we're at is going to be num and our current max is now equal to one we've started it and now that we know that we are in the beginning of the sequence because there's no other number that is less than it we want to look up upwards or incrementing so let's say if the set has a current number that is greater than itself by one we're going to increment here and our current max is also going to be incrementing so we're going to keep looking up and if there's a number that is higher and higher right so let's say we start at let's say at five right um we're saying okay does the set have a number that is less than five by one yes it's four right so we continue and now we're at four we're at three we're at two we're at one at this point there is no number that is less than itself by one and we start looking upwards is there a number that is greater than itself by one right does the set have it yes so we'll increment and increment the current max and then finally what we want to do is just say okay let's get the max value here and the current max just like that and finally we'll return our result and let's run that all right and this is the solution to our problem longest consecutive sequence so if you have any questions anything that's unclear please leave it in the comments it helps me a lot thank you
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
86
Jhaal Loot Hello Hi Gaye Is Letter To A Question Limitless Questions Politics Media Question Awadhi Hello Friends Politicians Not Lose subscribe our Channel Ko sabsakraib a hai to Interest Rates Vihar-3 Hospital Interest Rates Vihar-3 Hospital Interest Rates Vihar-3 Hospital Admit Want to and to write what will give one to two Bank to and behave note switch off gray 22803 and divine vaccine that a this very not only tools you need to join this oil and post-partition also oil and post-partition also oil and post-partition also health tips 22122 friends and friends subscribe similarly for votes 205 I office let that look At example for the scene write suicide note and will make you points one's which will give me the worst position one's which went use and we ride point minto this what is the value of x square minus point in wave the great 2.24 great 2.24 great 2.24 torch light a head was Foiled by one neck tree again sirvi one ball is most point to this screen sumo powered by one neck less than this is the value sustain its last point to the nation from units go to right select less keep on are also held balamu power by Buy O Hai Next President Solid Liquid 2X Ignorance Front Point 10 Notes I Anil Pump Share Hayden Mode Welcome Hee Wa Ki End Plastic Wa Lean Proceeded To Sources Value Member This Obscene Point Two Aspects Garlic Two-Fold Shyness Plus Two Aspects Garlic Two-Fold Shyness Plus Two Aspects Garlic Two-Fold Shyness Plus App Good Listen End Classification Head Will Move Forward By When He Backem Not Right Suicide National Bank Automation Condition So Guys Alarm In The Morning Sacrifice Will Give The Connecting This Point To All So Much For Partition And Tools To Connect With Kapil That Now Last Point Up To The Head Of The Point At which this poem describes in a beautiful decoration Koi Dooba Ko My Favorite Song Aapke Knowledge and Port Louis Amazing Posted in and tagged with One Hand and Mangal Basically Crib Screen 2.1 A Crib Screen 2.1 A Crib Screen 2.1 A Ki Sudhir Vitamin Pointers Right and Dear Ones Mot A Place Will Be Used To matter in the morning at that time and post-partition morbi in that second and post-partition morbi in that second and post-partition morbi in that second partition night sweet dreams always notes which will expand your love you to make a list of all the states which country in the values ​​of great think what they this period values ​​of great think what they this period values ​​of great think what they this period third you subscribe Take Health Tips Love You To That Previous Select In That Case Will Be Curved Tools Raghu * Points Next Tools Raghu * Points Next Tools Raghu * Points Next A Pointer Of Place Today As He Did Not Tied Wait For Next To Un Similarly Against Second Place At This Point Tools And Note Phool Wali Laung Railway Recruitments In That Case 120 Points Collect Mode Of Mode To Head I Want Any Month For Boys And Don't Forget To Move Ahead For Beginners And Valid Till I Tried So What Is This Is What Will Observe This Fact This 20 Seconds Partition to last not actually plaster of recent times points reminded shravan jhal improved time when skin problem and it * jhal improved time when skin problem and it * jhal improved time when skin problem and it * within last modified result morning point to all student komal ut already connection all fonts right and second vihar to connect to last not tell of to the Head of then second partition rights how to that member fennel next elections and connected to the head of then second partition witch month and spoon head of next flight se zinc dros next point vikram and versus the meaning of tomorrow morning neetu point west side and suck Return Gift Not For Lust Tube School Result Will Return Of The Day God Bless You All To Tight Friend Code Ok Distribution The States With Some Wasted On The Price Of Mustard In Almost Every Person First Vinod Yadav C Plus Always Right Jhal A Clue Sunrise Time Pass Complexities of First Time Complexity Skin on This Trek Singh During Last Point This is a Point Tight Service Time Complexity Shroff and the Taste of the Number of Units and Installations Peace Complexity Award Winners Were Making for Electronics Tried Not to Man Point 2 and Space Between Complexities of these and healthy weeks - Gautam Wright in terms of symptoms of space complexity and healthy weeks - Gautam Wright in terms of symptoms of space complexity and healthy weeks - Gautam Wright in terms of symptoms of space complexity and right choice at that time Complexity Times Complexity Padak HC 210 Which of this video and welcome back or thank you Jhaal
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
32
hello everybody and welcome to another episode of your favorite algorithm channel my name is Ryan powers and today I'm gonna be taking you through longest valid parentheses so this is the third parentheses problem that we've done valid parentheses we've done generate parentheses and now we're going to do longest valid parentheses so this is a permutation of the original problem of Bal currencies but this time we're looking for the longest valid sub-string right the longest valid sub-string right the longest valid sub-string right the longest valid substring of Bal currencies within the whole string of parenthesis so let's introduce the problem given a string containing just the characters opening print and closing prayer find the length of the longest valid well-formed of the longest valid well-formed of the longest valid well-formed parentheses substring so we have some examples here so given this input of two closes and one open the output should be two right because the longest substring is this one pair of two parentheses and then here in example two we have another string of prints and the output should be four because this group of two well-formed parentheses sandwiched in well-formed parentheses sandwiched in well-formed parentheses sandwiched in the middle here is our answer anyways I will say we could use valid parentheses we could take our function valid print sees and we could use it and modify it in a way to where it would just return to us the longest valid string of characters at every single iteration through every index of the string right we could start at the first index you know modifier Val parentheses function to just go through that and give us the longest one we can find and then do that at every index but we don't want to do that right because that's not the most efficient way to solve this problem we want to do this in one pass right so that's the goal today is to solve this funk or solve this algorithm in a Big O of n time so that's what we're going to be doing as always I suggest that you try to solve the problem first on your own and if you get stuck or if you just want to see how I solved it then go ahead and check out the video so if you're ready to get started come with me to the whiteboard on the screen here I've drawn a string of friends and also their corresponding index numbers so this over here all the way to the right this is an 11 it's not a stray set of perturb quotation marks so how are we going to solve this problem well when we did ballad parenthesis we use a stack to solve the problem when we use generate parentheses we also use a stack to solve the problem we used the call stack in a recursive manner but we use a stack nonetheless so what do you think we're going to use to solve this problem well that's right you guessed it we're going to use a stack again but this time unlike in bad parentheses where we're just tracking what the matching pairs of prints are we need access to two different pieces of information and let's identify with those pieces of information are so if we look at our string here we can identify where our longest sub strings are so let's go ahead and do that so our first one is going to be right here and what's going to block this off right it's going to be this kind of straight closing print so that's going to end that substring and then we'll look and we'll see okay seven and eight it's going to be our next longest one or our next substring not necessary oh the longest one it's going to get closed off by this nine here and then we'll look down the line and we'll see our last one is here and our lengths are six two and two so how could we use the information we have in front of us to solve this problem well we need to know what types of prints we have to be able to decide whether or not we're going to push or pop right but we also want to know what the index values are and the important ones are right here right so 6 and 9 so when we get done pushing and popping everything onto the stack the parens that are going to be left onto our stack is going to look like this in the end right so we're going to be pushing in the index values instead of the friends themselves so then we can index into our string and figure out at whether or not what type of friend it is but when we push everything onto the stack our stack is going to end up looking like this and what is that going to tell us well we know if these are the prints we have left over then we know that everything between the bottom of our stack and six was our first string value and everything between six and nine was our next string value and then everything between nine and the end of our string was our last string value so using the index values on our stack we can get the information of how long each substring was and that's the strategy gonna use to solve this problem so let's go through a round of using this concept this idea to solve this problem in the next video on the screen I have our stack at the top represented as an array and we have our string with our index values above each of our prints and here at the bottom let's quickly go over the strap well we've kind of gone over the strategy but let's go over the implementation of the strategy that we're going to use so if you see we're going to be tracking a max here so our max is going to be equal to the max of whatever are the difference between that looks like a 1 but the difference between I our current index and whatever is on the top of our stack so that is going to be the substring that we're going to be measuring and we're going to take the max of that calculated value and our max our current Max and we'll be tracking that here at the bottom so what about this negative 1 business that we have going on up here well why do we have a negative 1 there well if our stack is empty then we need to basically add one to our substring links and an easy way to think about this is if you look at this right here well the difference between one and the bottom of our stack is going to result in a value of undefined right because there's nothing in our stack when it's empty so the difference we can't call it zero right because we have a zero index so if zero indexes is hanging out here on our stack then we would want the different and we were on two here then the difference between two and zero would be the two prints if they were valid and that would be correct it would be a length of two but if we don't have anything on the stack and we say that it's zero then we're going to get a wrong value we basically need to we need to count the zero as being part of our substring if our stack is empty so we need to subtract one to account for adding this zero index to our substring so negative one is basically going to be our undefined or our representation of an empty stack once we get there so let's go through a round of solving this problem and updating our max along the way and see how this problem is going to work before we go ahead and code it out so we're going to start our first index here and we're going to push a zero onto our staff and we're going to look and we haven't popped anything yet so we can't really measure a string right we don't have a valid stringing it because we haven't popped anything we're going to move on to one here and so one is going to pop this off the stack right so our I've al U is one our new top is negative one so our new Mac which is going to be a value of two current max is zero right so that's going to be two and we're going to take that value and we got to pop this stuff off the stack so we'll pop this off the stack and we'll move on to our next value so our next value is going to be two which we will push on to the stack and then we'll move on to three and we'll push that onto the stack three and we still haven't we still can't pop anything off the stack yet because we've pushed to open prints so we'll move on to four and four is going to pop three and four off the stack so our current value is going to be the difference between four - our new top after we pop between four - our new top after we pop between four - our new top after we pop this stuff off the stack which is going to be 2 so 4 minus 2 is going to be 2 and our current max is 2 so we won't update our max because it's not any bigger so we'll move on to our next index so our next index is going to be 5 and that is going to pop two off the stack so our new max is going to be the difference between five - we are now at the bottom here we're - we are now at the bottom here we're - we are now at the bottom here we're now have an empty stack so minus negative one which is going to be six and our current max is two so we're going to update to six you and we'll move on to the next index in our string so now we've come to the six and we're going to push six onto the stack and we can't do anything with it and so we're going to move on to seven so seven we also can't do anything with it so we're going to push it onto the stack and then we get to eight and eight is going to pop seven off the stack so hpop seven off the stack so we can calculate a new substring so that's going to be 8 minus 6 which is 2 and our current max is 6 so we won't do anything with that because it doesn't increase our max value and we'll move on to the next value so we'll move on to 9 and 9 we'll check the top of our stack 6 is a closing Parenti 9 is also closing front so it won't do anything so we're going to push that onto the stack and we'll move on to our next value is an open paren so we'll push that onto the stack and we'll move on to 11 eleven is a closing / in so that's going eleven is a closing / in so that's going eleven is a closing / in so that's going to pop 10 off the stack because 10 is an opening print so 11 was closing print 10 was opening prints who you pop that off the stack so our current value is I 11 and the new top that we just generated the new value that's on top of our stack is this nine here so 11 minus 9 is to our max was 6 and it doesn't update our max right so the answer to our problem was 6 so you can see that this is actually a pretty simple variation of valid parenthesis right we're just adding another wrinkle to this problem so what is the time complexity of this problem well the time complexity of this problem is a Big O of n right we are going through the entire stream so the size of the string is going to be what determines the run time of this algorithm and so we're just gonna have to go through one time so that's Big O and what about the space complexity well you can imagine that if we didn't pop anything off our stack we push every single item into our stack so that's also going to be a big o of n for space so now that we have a good idea of the strategy for solving this problem let's go ahead and implement it in code so let's initialize the stack and in our stack we're going to store at negative 1 and like we said before the reason why we're storing negative 1 is it represents our empty stack if 0 is part of our sub string we want to include it as part of the sub string right so we need negative 1 to represent our empty stack and we'll initialize max to be 0 and then we just need to loop over our string hello let I be 0 and while I is less than the length of our string then we're going to keep looping so we want to grab the top of our string and we'll store it as a we'll do it as a Const so well we'll get we'll grab the top of our stack which is just going to be the index the last index of our stack so that's going to be stack length minus one and now we need to check this index in our string we need to check to see is the top of our stack and opening paren if it's an opening friend and our current index is a closing print well then we can pop that item off the stack so we want to check to see if our top is equal to an opening paren and our current index which is just going to be the string at I is equal to a closing friend well then we can pop an item off the stack so we're on stack pop and now we need to grab our new top so our new top is just going to be equal to the same thing so it's going to be the last index in our stack so that's stacked dot length minus one and now we need to update our max so our max is going to be equal to the max of I minus our new top of our stack and our current max so if this isn't the case if our current value does not pop something off the stack well then we just need to push it onto the stack so we run stack that push and we'll push on I and then we just need to return our max at the end so just to do a little bit of recap we initialize our staff with the value of negative 1 to be sure that we're including zero as part of our answer if our stack is empty we initialized a Max variable to be 0 and we're going to loop over our string at each iteration we're going to grab the top index of our stack and we're going to check to see is that index if it's an open paren and the current index that we're iterating over is a closing print well then that's going to pop an item off the stack so we want to run stack that pop and we want to grab the new top index our staff we're going to subtract our current index or we're going to subtract from our current index that new top index because the distance between those two things is going to be our substring and we're going to take the max of the current substring and what is currently our max so if that's not the case then we just want to push that index on onto our stack and then here at the end we're just going to return the max so let's see if we have any bugs okay great well let's run that again okay so Lee coats not gonna let me do that let's run it one more time okay great so 80 milliseconds so that doesn't look great but as I stated before leak code is really trying to make me you look better right now so we're just going to grab the best solution and we're going to run it against our code like I've done for the past few videos okay so let's grab the best solution so we'll grab this one percenter here this one looks pretty good says it runs in 56 milliseconds cool let's go back to our solution you and we'll paste that in here all right see how they did okay great we're tied so our solution is just good again it's the best solution Alico if you guys care about that it makes me feel good when I see that but anyway as always I think this is a really good example now that we've done these three parenthesis Pro it's just kind of like a pattern recognition right so these print problems are really indicative of stack problems right like we had two items that have to come together to two to create a value that were that we're tracking right and we always need to evaluate the last thing that we did so any time you see a parens for all it's very likely that you're going to need you to stack I mean we used to stack all three times for all three print problems so if you see a pram problem in the future that I think is where our minds should go is hey maybe we should be using a stack to solve this problem so anyway I hope you learned something today I hope you enjoyed the video and I hope to see you in the next one
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". **Example 2:** **Input:** s = ")()()) " **Output:** 4 **Explanation:** The longest valid parentheses substring is "()() ". **Example 3:** **Input:** s = " " **Output:** 0 **Constraints:** * `0 <= s.length <= 3 * 104` * `s[i]` is `'('`, or `')'`.
null
String,Dynamic Programming,Stack
Hard
20
174
hey hello there today's liquor in challenge cousins comment on Jenga the description about the problem is pretty long let me try to give a summarization we have a 2d grid that's all the positions we can be in this game we have a princess alone on the bottom right and we're starting out as a knight on the top left our task is basically try to fire rescue the princess by fighting through the dungeon since that we are a good player we have to maintain a positive health values throughout in our journey know that there are some values on the locations that's the house we will lose or the house we can if we go through that so now the task is basically finding the optimal strat that the initial required house value is minimized so that's pretty much the problem of no moveset is that we can move to right or luta that's the only two possible directions we can go so that's pretty much that question so let's think about this question in a more top-down kind of fashion because we more top-down kind of fashion because we more top-down kind of fashion because we really are solving a special case in this game because we have the initial location what if we randomly dropping a jump in the game we want to solve this in more generic way is that let's define this function to be f IJ which is the minimum fells required to save princess if we spawn at IJ let's just look at the few values here to solve this question is basically return f 0 let's look at the board here so well-well really quick Molly we can so well-well really quick Molly we can so well-well really quick Molly we can look out there is a to do that's it for me directly spoiling the boss fighter room so the house we required is six because after the boss fight we'll lose five points of health so now we want to make sure that nobody neutral hell's if we spawn up to two as well larger than the deduction will get so yeah it's easy to figure out the f-22 is 6 then easy to figure out the f-22 is 6 then easy to figure out the f-22 is 6 then let's just look around and to figure out that the other numbers the other number that's quite easy to figure out is f12 so we'll get one house in that position the next step all the positions we can do is just go to the boss fight so we will get so this initial volume plus one substract fi has to be larger than 1 so this subtractor fires go into the boss fight the 1 is the spawn location give us one house for free so figure out this calculation here we need at least a fight to survive if we spawn at a 1/5 so fight to survive if we spawn at a 1/5 so fight to survive if we spawn at a 1/5 so that's a that's basically what does f2 to subtract the great value at 1 Toyota if you look at F 2 1 we'll get almost like a cheating amount of house by entering there so that's we want this to happen so basically we want this to be larger than or equal to the right hand side which is f-22 so this X can be some which is f-22 so this X can be some which is f-22 so this X can be some negative number which doesn't make sense so we just take the maximum between 1 &amp; so we just take the maximum between 1 &amp; so we just take the maximum between 1 &amp; 2 this required X so it's gonna be maximum between 1 and this so we can see that we need a 1 here so let me actually just try to populate this as well so this is the dungeon and the lower f IJ value look like so into 2 requirement is 6 the requirement here is 5 I mean let me try to make this a little bit better don't for me like from follow the same pattern I have seen here it's the maximum between 1 and Phi where this Phi is from X plus 1 is larger than or equal to F to do which is 6 if we solve for the X gear you will be five so it's taking the maximum between one and five that does that's the five here so that's the F 1 2 and F 2 1 it's easier it's easy to figure this thing out because they immediately next step is the replica to the boss fight so that's why they're they are easier to figure out the easiest is definitely have to do because we have to survive the boss fight so let's put the number here then we're just going to look at one more example we can figure out that the generic formula let's look at the 1 so the if we're at 1 here what's the value here we can look at the right-hand value here we can look at the right-hand value here we can look at the right-hand side and look down to see which path required the minimum amount of house so that's 2 1 here because we only need a one house when we reach to 1 in order to be able to successfully rescue the princess that's what to 1 this meaning here the minima House required to say princess if we was starting at 2 1 IJ so we won't go to the minimum among the two possible choices we want to go down here if we got the wrong one and we just need to get there with the minimum amount house that's required for that position so what we want is to take the maximum between 1 and X from X plus 1 plus 30 X sub factor 10 is larger than or equal to the minimum between F 1 2 and F 2 1 so that's pretty much our recursive relationship we just would degenerate this a little bit with the IJ here plug I J packing here there would be i J plus 1 this will be I plus 1 LJ and here the cell value basically is the we are adding the value from dungeon i LJ yeah so that's the recursive relationship if we go for the top-down relationship if we go for the top-down relationship if we go for the top-down kind of approach or we can go from the button up basically stop populating this F IJ value starting from F 2 and populating everything out so that would be the button up population approach and once we reach 0 we can just return that value so it's a 2d DP but notice that the relationship here to calculate every cell all we need is to look up that the right hand side look down so we can potentially do space compression to reduce the space required to be a single row or single corner for the DP solution upon an autonomously so yeah so that's pretty much the summarization about how we approach this from the top-down we approach this from the top-down we approach this from the top-down recursive relationship to the transition back to the Balan approach Barnabas is basically from 2 to and populating all the values to zero one trick we can do here is do because notice that there if we're dealing if we really want to do baden-baden Appa we might need to do baden-baden Appa we might need to do baden-baden Appa we might need to populate the last arrow and the last column because we don't have to take the minimum the quick kind of fixes to basically pad one extra calling and one extra row there and just have those value to be really large so if the tickling the minimum between the you know the next one and at the bottom you want out it will always choose the powers so that's just a little implementation detail so today I'm just gonna try to cut through the 2d version because I'm really tired right now so let's cut this thing up gonna grab the number of rooms and then the columns for the dungeon oh I have a missus valve here and then we're populating this 2d table instead of calling that f IJ I'm just going to call this HP is more intuitive rectifying a maximum integer so we had this 2d grid by one calling and one go so that we can just use one single formula to fill out the full thing it's going to be for long extra column one extra row yeah then with basically just using this formula to front to two from number Froude number : front to two from number Froude number : front to two from number Froude number : all the way back to there oh yeah one thing we need to do here is that we need to pad one more thing we have to part one here and one here so that just says we need at least the one house one after we finish the boss fight so we can do we need this no we don't need this we don't need a populate this we can directly fill out the value here right yes let's just try to do that instead you will look nice and nicer so HP at the boss fight after the boss fight will be maximum between one and the whatever-the-hell scan we will have whatever-the-hell scan we will have whatever-the-hell scan we will have after that so you will be if this is a free fire house up that means we only need one if it's a negative that means we have to have six so how do we fix this so it's a it's one I had subtracted the value of their same value it's one self tractor by five so it's done engine negative one so this is the initial case base case here the rare last cell it's not aligned anymore I'm just going to call in this a Space Case so the then is the looping to populate everything else oh it has to be subtracted by one sorry it's repetitive one and if we put an arrow it's actually the last arrow so we were looking at the last the one for the one prior to the last isn't since it's this and yeah that's it this is the rare loss the cell body that's true but this one we have to go one beyond that so it's this so we are looking at the very last arrow the rope prior to that and all the way back to the top and for the column we're looking at the right monster color and all the way towards the left we're populating this in this way because every time we do this update we have to look right or look down so we have to populate the stuff on the next on the arrow in the bottom or on the clownin towards the right we have to pop you let those first so that's why we generating over the indices in this way know is equal to number bro subtract by one we're basically gonna skip this one over if we or we can populate this fear too otherwise we were just gonna use the formula which is this so to solve this X it's basically the minimum between this two as substracted the dungeon IJ so that's a minimum between HP from the same row next to : same row next to : same row next to : from the next arrow Sampada and subtracted the dungeon value in the end we just returned the top left a value yeah so that seems to be the Co not defined yeah so that's the code we could do some compressing because if we look at the recursive relationship all it depends on is the next the rule not on next column so we can save some space and convert this to a one DDP if we really want I have to go I need to make breakfast to come back here so that's it for today
Dungeon Game
dungeon-game
The demons had captured the princess and imprisoned her in **the bottom-right corner** of a `dungeon`. The `dungeon` consists of `m x n` rooms laid out in a 2D grid. Our valiant knight was initially positioned in **the top-left room** and must fight his way through `dungeon` to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to `0` or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only **rightward** or **downward** in each step. Return _the knight's minimum initial health so that he can rescue the princess_. **Note** that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned. **Example 1:** **Input:** dungeon = \[\[-2,-3,3\],\[-5,-10,1\],\[10,30,-5\]\] **Output:** 7 **Explanation:** The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN. **Example 2:** **Input:** dungeon = \[\[0\]\] **Output:** 1 **Constraints:** * `m == dungeon.length` * `n == dungeon[i].length` * `1 <= m, n <= 200` * `-1000 <= dungeon[i][j] <= 1000`
null
Array,Dynamic Programming,Matrix
Hard
62,64,741,2354
101
Were and ₹ 1000 National Knowledge Commission are Were and ₹ 1000 National Knowledge Commission are Were and ₹ 1000 National Knowledge Commission are connecting the Africa series well, it must be understood that it is a very good conference of Bakyan Maximum, now according to me there are 12 more concepts left, so in total there will be 45 video factories, you will find that trick. You can bring my accords on Play Store again and further but in 45 rupees and the maximum should be tight, today we will give questions in this, tricky questions, very famous questions and a good welcome to you, if I send you that this time we have not If you have already done it somewhere, then let's start the video, see what the question is and before that, there is a big challenge for those who are looking for a job after leaving Job Seeker, if they do not have a good degree in film, then their connections. There is no butter left in your hair, then there is not much selection in your hair and you always want to do it and in these higher oil companies, after applying a lot and after supplying for fifty-sixty hours, you do supplying for fifty-sixty hours, you do supplying for fifty-sixty hours, you do not pass an interview. But travel which is India's first taste Harry platform by Unacademy but you can get job on this unique platform just on the basis of pimples and talent. Those who do not know about railway platform and tell a little that through this platform more than 50 Top Stars Companies Like Tadap Razor, all this company does everything, it is available from thousands of Yadav positions in the field of business development and development sector is online with the biggest benefits and you can get this test here for free from the best readers. Can give 168 tests with the qualifying score You will be able to create and edit profile Indelible platform relation Candidates who are eligible can now give 30 days test If they do not get a cricket match then the subscribe is killed and the folder According to test and subscription, you have to select your test match live business of development, now book a plot and then give slots to Afridi for the test, you will message me now fans are possible to book soon, Begusarai is quite limited, not TAKEN AFTER THAT YOU CAN CREATE UP AND CLICK ON SUBMIT AND CONFIRM IN MORE REMAIN TO KO LING LIKE EVERY TIME I WILL RECOMMEND YOU TO WATCH MY VIDEO PLEASE AAP MY VIDEO YOU WILL BE ATTACKED WITH MANY QUESTIONS NOW DARE The first thing is how simple it is, we have one in the middle of this route, which you treat like a, this is as much distance as it is two, this is two as much as this for slide specific resistance, but this is as much as three. Descend on Distance P3 Basically what we're doing is mirroring each tip is the symmetry that admins that if we if I say this line this is if I grab this line C line which and according to this if I this Fold it, okay, if I fold it, then this thing should match perfectly, it should go overlapped, the stage show of the semester is that David is doing this line quartz, we have to point this, so I then do both the soldiers read a lot of contacts, right then? The questions that come next are two-three concepts mixed, the next are two-three concepts mixed, the next are two-three concepts mixed, the concepts of the datasheet will be applied or the concept of your drivers or the matching concept of 292 tree will be applied, then many a times 263 are mixed and the question becomes why do people go online for development? I don't even have a date wise playlist. You must be watching this with couples. They are clear about all the basics to a great extent. Now they have understood how to solve the religious shop problem. Right, watch this video. Before watching, I will definitely tell you that this video is about vegetables, this entry video, if you are in the middle of the diet, you will still understand it, no problem, but I will recommend it to you. In this great video, the emphasis will be on exactly two videos, so you will watch it. So this video will be understood by those who are watching this video, it is sitting in the playlist a lot for them, but further I will give you this comment, if you are watching it for free, follow the playlist from my channel Rishi, that is, whatever you want. The fear of entry in Tubelight will also end, this is why these questions will arise Light, so I hope you have understood the question till now, what the question is saying, you just have to find out whether this thing is symmetric or not, just like returning bullion. If you have matriculation then you will return it otherwise you will return the pass Datesheet C If you have seen this video then I am assuming that you know what I have told in the video, so in this video I have created a function, torch light is matching. One is taking the root and the other is taking the form. This explains the function. Listen, this difference tells whether this omelette is this one which is the note structure and this one which is the note structural reconstruction. Both similes are found in the similarity or not. How are we finding out, what did we say that 242 danced, yes, it matched the left leg, three layer pendant, three, side effects for the right leg, four matched, if there was one here, it would have been seven, then it would not have matched, big here. If there was a forest from here, then it became green chillies. For example, the entire note structure is Chunari structure for the same. If you are telling this, how are you telling this, I have discussed this thing, there is no need to tell it, I am assuming that. Now what is there in this video is that wicket work is saying that you three and four right to three and four is the problem with us. What is the problem with us? Basically what we have to do is that we have to find a route and at that time we have to find a route. We mixed this route, we mixed it, we matched it, we came to the left, it is also left, both of them come together, only we are the left leg of the route, then sorry, they seem to be the route, collect the route and match it, ride and route of the boolean route Right of this lottery and basically the right of Fruit Karachi Eight and the right of this route both matched, tell me, now you have taken that too, this is Veeru and its value and that tweet is gone, so what do we do? Let us tell you what is the overall result of this. The conditions keep matching, the complete tree is found on the site below, what is the question saying in this case the demand of the question is care, so is the demand, listen, in the first time I got 21, in the second time also I got two here, both are very good. The value of should match, there was no problem, we came to its left and due to this, we will not go left, we will go to its right, then we will not put mirror, then this distance will be the distance, if subscribe is required near the subscribe, this one will be a trap for the other one. The one on the left will be the one on this website. Overall, we have to match each one. In this, the left side of the route is matching with whom, the right side of the route, let it become a railway route as per your wish, the route two is matching with its right side. Agri positive, let me explain it to you in an example, what are the examples and it is easy, why did you match, very good check match, this thing, now we left on this, but yes brother, now the skin will have to become tight, I danced, it Right left is in its night and in its left and right for this and four matches have been made. In this case, five left may come in the side of this Christmas. Trichay will have to come in the right. You must have read from development districts chilli that now. The distance between the ends of the jet is equal to the distance between the sides. If we make it a my computer, then the distance is the same. If this is one, it will be the same album. The trick for that is that if the position of the one from this is left her studies. Question: There is no chance in the left, studies. Question: There is no chance in the left, studies. Question: There is no chance in the left, shifting it to the light. The common people have to check for soaked money, its percentage is in the right or not? Yes brother, fiber letter is possible here, what is there in the left before this, bursting into discus and being consumed in the right. Only then will you be able to add more things, you must have understood why I am saying this again and again that brother, it is simpler than our old video, that is why the one below is also just what was there in the old video, like This is two, this is three, this is the phone, this is two, this is three, this is for attack, what we were doing was to superimpose two, not mirroring it, superimpose means if we pick up the edit and put it on top of it. This thing should be super imposed, for that its left and its left should match. I should ride it and its right should match. If we put it in the middle like this then it will not work. The chicken designer with Pecos Super Impossible is matching one on top of the other. So this left and that left and front correct sunlight every few activities should match - when mirroring then this should match - when mirroring then this should match - when mirroring then this left and that should be tight. Here you understand that I am trying to explain the truth, not so much time. If it comes then please comment. If you don't understand then please do comment and tell me what I did n't understand. Look with one, I want to see one Aishwarya. As if we have only one route, the stop has been changed and nothing else has been given that we have. If it is not given then in this case is it yes, everything is fine, you tell me how simple it is, we have kept it in the middle, so now you will say it or no brother, and it has been cut, so this time it is like this and this time it is like this, it is mine. If it is not there, then do not comment as if we are single after seeing the note. Set this note in between and remind us of a single road. It will make a difference only from the middle, it is equal, it is okay, we will get the stick, Edison, okay, someone can talk to me in English. I don't know if there is a tap or not, then this tap made of clay means something, so for that, you could have done it for a while, if not then it is still okay, it is not that simple, friend. What we are doing in every case, we say in every case that like this is the tube, its who is its four, its three is two, very soon, what we meant in this case is that its left leg should be old, in this case its root is Its behavior is to loot and rally, it should be from both its right and its right, but I don't want unless its left and it should be from ride, then its left, sorry its left, one more will go with its right. Whatever is his right, whatever is left of him will definitely go with his right and the benefits of both should match. As I told, I have to run 3424 three leg race on this route. If there is partition, then of course it is the responsibility of both of them. Shouldn't there be a Nobel Prize for the route, should be Agri and Vacation? You know that this match will return like a title match and both have become colonels so that they can fight this is also a tap and this is a tap. I told you then, what if the opponents do it? There will be more screw cooked, till now it is clear, there is no doubt, let's code it now, please don't say it, brother, I was very scared, Vikas, if this place was felt, then you should say oats, yes, top is felt, no, I did not understand, minute, it is not that much. It is more tough, turn it on, that I keep asking, let's assume that the root is closed and the root two is right. Now what did I say that if only the root lineage is not equal to null and the root two add 9 tbsp oil, then they will say that let's check, say one. Drop test match route, the left routes will be fixed to the right and then these will be done so that in the middle of making this, the second one will go for the right one, then what he said was that only the route is fixed, the value should be equal, the value of route two came and It should be from Brahmins, if it is ok then we will return it, now it is a proof, we will return it, now it is a false, now let us assume that this condition is not there that there is an addition that both the channels are equal, this contract used to withdraw cash, what is true and last. That return for neither of the two has happened that a this is not a message album clear next messenger is not clear then please watch this video and 10 minutes will be spent if you think there will be a stay of 10 minutes but what in 10 minutes Learn a lot, this route was not found evenly, if that route was not found evenly then what did we think now that whatever the route is, it is fine, if we do not know that then we will just button it, then there is another single route. So what we said is that if the goods are in that route then the sure symmetric volume of its left part has been put to the matching surprise of the right part. Joint Auditor Match A has become the left recruit of the form of route one and the right of the route which is route two. Ban banya let's run, which class is this? I hope you must have understood this, I was asking this question just to change here and our rider is there, so if you like the video then please do subscribe and many people are about to finish subscribing. Stay Connected For A Long Time Thank You Main India Thru Loot
Symmetric Tree
symmetric-tree
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). **Example 1:** **Input:** root = \[1,2,2,3,4,4,3\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,null,3,null,3\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-100 <= Node.val <= 100` **Follow up:** Could you solve it both recursively and iteratively?
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
129
a holiday after Daisley coding challenge question is called some root to leaf numbers we have a binary tree containing digits for non zero tonight so each node inside this binary tree will have a value to be a single digit from 0 to 9 and each root to leave pass inside the spidery free represents a number and the question is asking us to sum all the leaf to a root to leave numbers looking at it at the example we have 4495 491 so that we receive we add those three numbers together and return the cell that's the question so how it go about solve this we're just gonna traverse the tree in the DFS search fashion so we're trying to reach try to complete a route to leave pass before we explore other paths once we reach the leaf node we can return the we can add the number that's represented by the past or some kind of accumulator and once we done all the DFS search the accumulator will be the sum we wanted so yeah that's pretty much it just gonna do a DFS search and after that we'll be done so it's a it's gonna be linear Italian linear space pretty simple question really so because we do DFS search we won't use a stack so that we can pop fall on the back and the element on the stack is gonna be a topple which is going to be the node we're currently looking at that during the DFS search and also the partial pass some so initially it's zero so we're just going to do DFS search until we run out of stuff to look at so each iteration we're gonna pop the know and the partial sum out and then we're gonna check if this current node is a leaf node before that we update this partial and then we check for if an odious leaf node the node will be a leaf node if the node does not contain any children if we reach the leaf node that means the partial will be the number that are represented by this pass so in the beginning it will be after we moved to after we pop the root out the partial will be updated from 0 to 4 and when we move to 9 it will be updated to okay I'm sorry I think the calculation is wrong I have to multiply 10 to the partial so that I shift a wrong position so in the root here the partial it's a 10 multiplies er plus for size 4 when we move to 9 you will be 40 multiply the prior partial by tendons are the nodes father so we all become 49 and when we reach the leave we will be 490 plus 5 so the partial sum here will be the number that's represented by the past once we do if we do this kind of update all the way so if it's a leaf node then we put this onto the total and otherwise we would just extend the stack to explore its children's since that we might be pushed pushing a null pointer onto the stack we just going to do a really quick check here if the node is no pointer we just ignore it yeah so that's the iterative approach the FSH to solve this problem all right so yeah that's pretty much it in the worst case when the tree is a degraded singly linked list the time and space here pose order of n so if it's about as the tree the space is the space would be just the space will be log off and so by the time is it still order n so in the worst case it suppose linear in terms of time or space yeah that's it the prettiest simple question for Friday
Sum Root to Leaf Numbers
sum-root-to-leaf-numbers
You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. A **leaf** node is a node with no children. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 25 **Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. **Example 2:** **Input:** root = \[4,9,0,5,1\] **Output:** 1026 **Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 9` * The depth of the tree will not exceed `10`.
null
Tree,Depth-First Search,Binary Tree
Medium
112,124,1030