id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,769 |
hey what's up it is wednesday may 4th 2022. uh we are powering into may still in the beginning and yeah we are uh here at coding with chef or chef the algo man i still haven't decided the name of this channel and uh we're trying to um yeah solve some algo questions and uh so if you like my content just a reminder before i get into it please like subscribe and comment below let me know how i'm doing let me know what you want to see and yeah um let's get into it um it's a gloomy day so kind of perfect for algorithms and um yeah i'm ready to do mediums now well not totally like uh but you know a bit right like i want to try to explain these as i go through them i've been doing a ton of mediums as they are but uh explaining them sometimes gets a little tricky once you get into the cs of it um but yeah in this case i think we should be good to go so let's see the name of the problem is max number of k sum pairs okay 1 6 7 9 it's the daily challenge all right and i have a discussion thread on it which i'll share and the link tweet whatever um uh so you can follow me on twitter follow me on uh this channel and you'll get to see all the discussions and whatnot uh for each of the problems okay all right and the discussions are elite code so here we go it's a medium problem it's a very well liked problem okay and the problem states you are given an integer number nums and an integer k in one operation you can pick two numbers from the array whose sum equals k and remove them from the array return the maximum number of operations you can perform on the array okay and then the example one they give you is one two three four and k equals five so we basically you have to find the maximum number of operations uh such that if you take two of these elements out uh they sum to the target so if i take one and four out they sum to five and then if i take two and three out they sum to five okay so um that's two operations and that's the maximum okay that kind of and this is kind of intuitive i think some elements of it are but um the question is how do we know that we're doing the maximum number of operations okay so um the next example is three one three four three so if we take and notice that there can be duplicates in this array right so if we take two threes and sum up the six now so sum at the six we get one operation then we can't use these threes again so we can take one and four uh that will sum the five one and three that'll sum to five four and three are four one four and three will sum to seven so none of the remainder of pairs of numbers uh that we can use can sum to um can sum to the target six okay so um yeah so how do we go about writing an algorithm for this so the thing you want to intuitively understand you look at the array and you kind of i think the first example really gives a good solution it gives a hint to a good solution because you see what's true about this array it's sorted right and it being sorted lets us pick elements from the larger and smaller sides of the array right and sum them together and that also simultaneously lets us you know as we move along the array squeezing in inwards right we can also use the fact that the elements are sorted to start to look at which sums don't fit into the criteria okay so let's see here okay let's here's an example if i have one i'll start at the end of the array and four right the pointers are zero and three let's say we have two pointers right one for sums to five so then we go to the array we can move both numbers ahead uh we can move the left pointer left plus and the right point to right minus and then two inner numbers also simplify okay and so that's a pretty straightforward example okay then you don't yet see the efficacy of sorting here right but you'll see in a second so if i take um nums and i'm going to sort the list three four okay and uh that's this list sorted if i sort this list i get um now let's go through the same operation remember i have a left pointer left equals zero right equals four okay that's the index of each of these elements so if i increase left plus and for now first before i do any increasing let's check the left and the right elements so 1 plus 4 is equal to 6 okay so 1 plus 4 is equal to 6 i know that or e one plus four is equal to five um so that's less than the array right that's less than the k is equal to six uh nums of left plus numbers of right equal to five so what can i do well in that case since this is less than the target what i can do is i can move left ahead because all the numbers ahead of left or to the right of left are going to be increasing so my best chance of finding uh a sum that equals the target is moving to the left moving to i can't move to the right because i'm at the very end of the array but also because i can't use elements that have that are past the element i've already used on the right so i the only thing i can do is move to the left so if i move to the left again nums numbers of 1 plus nums of 4 equals 7. so now i'm above the size of the target right because the target is 6 right k equals 6. so in that case what do i do well in that case since the only thing i can do really is i can decrease the sum the next attempted sum right and the only way to decrease the next attempted sum will still take in account the numbers that i haven't used yet is to subtract right okay and then uh so i'm squeezing the right side again numbers of 1 plus nums of 3 equals six great uh and therefore i'm going to say my total operations opposite plus one and then what else is there left to do so i have to move both pointers now like left plus right minus because i can no longer use uh this pointer and this pointer this number and this number right because uh you have to remove them according to the original statement from the array so with that being said and we have only one number left three and so how do i know that uh this is the maximum number of operations that one is the maximum number of operations right uh max equals one well because there's no other way to um some elements in the array such that we can get to the target and uh this is the optimal addition right of all the elements so with that being roughly understood let's attempt an algorithm so i'm going to call my number ops this is what i'm going to be churning and right equals nums dot length minus 1 and left equals zero okay these are my two pointers and remember what did i say i was going to do i was going to sort the array so sorting slows down the progress of this array but it prevents us from having to do like anything like a depth first search or something even more crazy because you could do a crazy depth first search type thing to reverse every element in this array and find every sum and that would just not be efficient if you could imagine right so and some equals so now i'm going to uh go iterate to my array and i'm going to iterate until left is well left is less than right if they're equal then they've obviously come on to the same element if they've crossed each other then you're in an even sized array and there's no longer anything you can sum because all elements have been used so um uh so we're gonna get the sum of the left and the right we're summing everything regardless so if some equals k remember what i said if sum equals k then we have to squeeze both sides of the array okay um so we squeeze both pointers towards the middle right minus okay else if some greater than k right greater than zero right minus okay so remember this counts for if uh we've overshot with this sum then we need to reduce the next sum by moving the right index over to the left right we shrink the right index and final condition right is if left is less than nums.length minus if left is less than nums.length minus if left is less than nums.length minus one right left minus one we want to make sure we don't want to go to that get past the end of the array we probably don't even need to do this check um but i'm just doing it anyway uh i will confirm if i need to do this check anyway um but it's just good boundary condition checking so let's go on there you go and uh let's see what we did here uh f plus ah we have to do plus yeah oops in that test case with me okay there you go now let's see if we even have to check the boundaries i mean i think it's a good practice but does it speed up the algorithm did not do this extra ah if oh wow it actually did by a lot but you know you never can really trust lead codes thing in mobile here so um yeah that's the answer uh it worked runtime o n log n space constant right because we're not doing any other storing of any other uh elements based on the amount of the nums that we get back so yeah that's it so if you like this video like subscribe comment let me know how i'm doing and until tomorrow i'll see you around oh and the discussion thread is available remember check it out i'll link it in the video the discussion thread i wrote it's my code i do the code problem i learned how to do it and then i put the discussion thread my discussion thread okay thanks see
|
Minimum Number of Operations to Move All Balls to Each Box
|
get-maximum-in-generated-array
|
You have `n` boxes. You are given a binary string `boxes` of length `n`, where `boxes[i]` is `'0'` if the `ith` box is **empty**, and `'1'` if it contains **one** ball.
In one operation, you can move **one** ball from a box to an adjacent box. Box `i` is adjacent to box `j` if `abs(i - j) == 1`. Note that after doing so, there may be more than one ball in some boxes.
Return an array `answer` of size `n`, where `answer[i]` is the **minimum** number of operations needed to move all the balls to the `ith` box.
Each `answer[i]` is calculated considering the **initial** state of the boxes.
**Example 1:**
**Input:** boxes = "110 "
**Output:** \[1,1,3\]
**Explanation:** The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
**Example 2:**
**Input:** boxes = "001011 "
**Output:** \[11,8,5,4,3,4\]
**Constraints:**
* `n == boxes.length`
* `1 <= n <= 2000`
* `boxes[i]` is either `'0'` or `'1'`.
|
Try generating the array. Make sure not to fall in the base case of 0.
|
Array,Dynamic Programming,Simulation
|
Easy
| null |
12 |
A height competition song in reality problem-solving serious problem it problem-solving serious problem it problem-solving serious problem it well and research institute romantic words updated with scientific expert video those problems absolutely solid to problem measurement electronic media problem statement pass roman rains representation practice witch i actually CD and with specific Living Under Your Voice IS One Five to Zubaan One OK Yourself Sample Positive I Can Beat Officer Drops Subscription OK Thank You All Must Be Aware About How Do 135 What I Will Strive to Preserve and Tried to Solve Them Using Normal Top Ten More Which Will Contain Liquid value starting from is haldi is writing from what ever have any condition plus some specific values for the talking plus specific values for the talking plus specific values for the talking plus specific values will take time to problems yes I am values will take time to problems yes I am values will take time to problems yes I am creating gayre vidyalaya us din tha ushe zor vighn top electronic your New updates Please subscribe and shyam mein Vriddhi Subtraction For Rice Intensification Qualification Note You How To Get Some Thing For Certain Distance From Dixit Every Kind Of Time 528 Is Pay Point Per Kab Cd Tense Peeth 110 Ayush Vs 500 Vs Stringbuilder A That Death Will Start With You Starting From Equal Us Sure Hai The Planet And Drew A Blank Space For Migrating To Work At Which Are In The Middle Of The Night Fall Aka Bunty Number To Fati Duty Removed And Motivational Used Oil Little Difficult - - So 1008 Is I Will Little Difficult - - So 1008 Is I Will Little Difficult - - So 1008 Is I Will Attend Divya Melta Animals And Places Of Tourist And Subscribe To Carry Out Record To Ninth Chapter Feature Hai Ko Hataye Shudra Varg Gaj Ka Tiffin S T Literature Created In Roman Language White Subscribe Skin Final More Minutes SUBSCRIBE TO A SOUL POSSESSION 150 ADVERTISING ACTUALLY IT WILL BE SO FIGHT SUBSCRIBE BUTTON AND ALSO LIKE SHARE THE VIDEO CONFERENCE ON SOCIAL MEDIA THANKS FOR WATCHING A
|
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
|
412 |
welcome to joystick this is joey and in this video we are going to solve a problem that i have taken from lead code the problem is fizzbuzz which we are going to solve using java without further ado let's take a look at its problem statement but before that if you are new to my channel and haven't subscribed it yet then do hit the subscribe button and the bell icon because that way you won't miss out on these programming tutorial videos i create for you are given an integer n for this question we are going to assume that n is 5 you need to return a string array like below yes there are certain conditions involved as a result of which this array has been generated let's take a look at them so the first condition is if any index i of the array is divisible by both 3 and 5 then we assign the cell at index i the string fizzbuzz the second condition is if any index i of the array is divisible only by 3 then we assign the cell at index i the string fizz now similarly the third condition is if any index i of the array is divisible only by 5 then we assign the cell at index i the string buzz and finally if any index i of the array doesn't meet any of the above three conditions then we simply assign the value of i to the cell at index i and you have to remember that i here starts from 1 which means the first index of the array is going to be 1 and not 0. take a look over here the index of this cell is one is neither divisible by three and five nor by three only one is also not divisible by five which is why one goes straight into this first cell as a string okay now we jump to the next cell the index here is two now two doesn't meet any of these three conditions which is why two as a string goes straight into the cell then we come to this set the index over here is 3 is not divisible by both 3 and 5 but 3 is divisible by 3 which is why we insert the string fizz over here in this cell that's the logic this is how this array has been formed okay let's now move to write the program to solve the fizzbuzz problem in java i'm already in my project in my intellij ide so i'm going to create a class now i'm going to name this class face buzz only as you can see the class has been created let me create the main function as well so i'll type psvm and there you go main function created the first thing that we are going to do is declare a variable n and initialize it to 5 as we have seen in the question so it will be int it's going to be an integer variable n equals to 5 okay now we will declare a list of strings rather than an array of strings because it will be more convenient for us to use when we know that the indexing has to start from 1 all right so it will be list string we'll call it li equals to new arraylist and it will be of type string there you go and i'm going to import the java.util package the java.util package the java.util package so that these red marks get sorted out the list interface and the class array list are available in java.util package hence we need to java.util package hence we need to java.util package hence we need to import this package first since we have to fill the elements of this list li with the respective values specified by the conditions involved thus we'll have to use a for loop so it will be 4 and it's going to start from 1 because the indexing starts from 1 and it is going to run all the way to the value specified in n which is 5 and it's going to increment in steps of 1 okay now the core logic involves writing an if else construct all right so we will write if and within brackets we will write the code to check the first condition is to check if i is divisible by both three and five so how we are going to check that it's simple we'll check if i when divided by the lcm of 3 and 5 which is 15 gives the remainder as 0 if it does then we add the string fizzbuzz as an item to our list li hence we are going to write i modulo operator 15 comparison operator 0 okay lcm of 5 and 3 is 15. so if this condition is satisfied then we are going to add to the list the string fizz buzz okay the second condition will be to check if i is divisible by only 3. so we will write elsif within brackets we will write if i when divided by 3 gives the remainder as 0. if it does then we add the string fizz as an item to the list okay the third condition will be to check if i is divisible by only five so we will write else if within brackets we'll write i modulo operator 5 comparison operator 0 okay so if i when divided by 5 gives the remainder as 0 then we add the string buzz as an item to the list li and lastly we'll write else and beneath it we'll simply add i to the list so it will be li dot at i okay now since i is an integer variable hence we'll have to first type cast it into a string and then add it to the list we will thus use tostring method of the integer class to do the type casting so it will be integer dot to string and we put i within the brackets of two string method okay there is one final bracket missing over here let me put it the final thing that we are going to do is print this list li so it will be system dot out print ln and simply i'll write a live within its brackets okay that's it the program is complete now we run it and test the output and there you go this is the output and this is exactly the same as we saw in the slide before and when i submitted this program on lead code it ran in just one millisecond and you can see that it is faster than 100 percent of the java submissions made for this particular problem so with this we have come to the end of this video i hope you enjoyed learning this program from joystick and i hope you coded this program along with me i look so much forward to helping you with programming and algorithms do let me know in the comment section if you got any doubts and only for this video goodbye and take very good care of yourself
|
Fizz Buzz
|
fizz-buzz
|
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_:
* `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`.
* `answer[i] == "Fizz "` if `i` is divisible by `3`.
* `answer[i] == "Buzz "` if `i` is divisible by `5`.
* `answer[i] == i` (as a string) if none of the above conditions are true.
**Example 1:**
**Input:** n = 3
**Output:** \["1","2","Fizz"\]
**Example 2:**
**Input:** n = 5
**Output:** \["1","2","Fizz","4","Buzz"\]
**Example 3:**
**Input:** n = 15
**Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\]
**Constraints:**
* `1 <= n <= 104`
| null |
Math,String,Simulation
|
Easy
|
1316
|
1,189 |
hello everyone so today we're going to solve a random v code problem and to make it random i'm going to generate a random number from 1 to 1 5 6 9 is the one five six nine is the number of lead code problems that exist as of today we got the result one nine three so let's see what uh problem number one nine three is um one nine three does not exist one eight nine exists so maximum number of balloons so that's what we will be solving today let's see what kind of problem this is 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 the text at most once return the maximum number of instances that can be formed so you'll be given as sorry it will be given as input text string text and you want to make sure um you want to be able to return the maximum number of balloon instances that you can build from this particular text so in the example that you see here n l a e b o l k o um it becomes balloon like if we take the this character we have b this character we can take a we're going to delete this character because we can only use one character one we can use l um we will use another l we will use one o we will use another o we will use n so we are able to make one instance of balloon from the given input so the answer to that is one as you can see here and just like that if we get something like this loon balax bill ball you can have two instances of balloon and if you have something like beat code then you cannot have any right so what we want to make sure of is if we have um a text we want to count the number of characters there are right um so let's do one thing we'll create a hash map of the number of characters in this in balloon so map will look like b exists once a exists once l exists twice in balloon by l occurs twice and o occurs twice and occurs twice now when we're going through the text we want to make sure that it's a multiple of this and are you how many times this is happening right uh so we will go through the text as well and build a map like that now we will go through balloon and see how many of that exist and we take the minimum of minimum occurrences of that count so if we get like uh you know that balloon b occurs once a occurs once l occurs twice occurs um all cursed wise and occurs once right now we go through the text and we get something like b occurs four times a occurs three times l occurs six times o occurs eight times n occurs um four times so what's the answer here so when we get then what we need to do is that we have one map which is the balloon map and then we have the text map right so then we need to loop through balloon okay so each character in balloon and then we check what's the size which the current how many b's can you build you can actually build four b's right so right now our candidate answer is one is four because you can build four b's we are probably going to get more right and then we are going to see that a how many times can you build c build a you can actually build three of that three divided by one is three so the minimum of four and three becomes answer becomes three and six by two is also three eight by two is four but three is minimum so we'll keep three four by one is four we will keep the minimum and if at any point this does not exist looking up on the uh in text map does not exist looking up on balloon map it exists and it does not exist in text map then we have a problem so that's what we're going to do we're going to keep track of two counts so let's try and implement this so we have in counts this is always all going to be lowercase english characters so ball map that will be 26 and text map that will also be 26 now for each string ball equals balloon and we're going to parse that string and take count of all the uh um character occurrences in balloon so counts of ball dot character at i minus a plus so we have this and we are going to do the same in the case of text we have so much so we have kept the map right now we want to go through this again so this is ball map and this is text map and what we're going to do is we will take the occurrences in um both occ occurrences in ball map of well let's first take the character in index equals ball dot character at i minus this now ball map of index and in text occ equals ball text map of index now if at this point we find that um if text occurrences less than ball occurrence then we can return zero at this point else now inch min length equals integer dot max value let's see in current possibilities equals text occurrences divided by ball occurrences now min length becomes math.minimum min length becomes math.minimum min length becomes math.minimum of current possibilities i regret making huge variable names um min length ultimately we can just return mid length i think this will work let's see if i have any compilation errors oh that worked okay let's try to submit this now yeah so it works first time and this is a pretty straightforward problem so yeah there's that so thank you for watching i'll be back with another video pretty soon see ya
|
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
|
724 |
hello programmers uh this is a little good problem 724 the problem name is find pivot indexes I am reading the statement of the problem in Array of integer number calculate the pivot index of the array or here you can see the what is Pivot index okay the previous index is the index where the all the numbers is strictly to the left of the index is equal to sum of the all the number is equal to the index right uh in the index is actually I'm summarizing for the statement that by example test cases okay uh here we can see if I uh you are in indexes two zero one two and that's uh the time here am I okay we are making it great okay here in my okay c and cs7 1 8 6 5 6 12 and 5 17. left pivot indexes and right paper indexes are not matched I think if I uh if I like go another index three this is three and you can see seven one eight three eleven five six eleven actually uh the pivot indexes uh matched left and right and I would return the index indexes number zero one two three the answer is true I hope you guys understand the problem statement and in solving approach I would go with two approaches the first one is a root approach abridges approach and Bluetooth approach you can use a true Loop more you can use tool up or three Loop and it is also called n square and Loop in Loop within Loop okay and you just iterate the first in the first just as you can see in both Force you just iterate your first value and the last sum of the Library login some first two value and the sum and last below then with that and first value and last four Value First True Value and last three value and you can get them and so and I'm going to use a prefix sum instead of that and in prefix um here you can see I just uh prefix all the sum of all the value okay first firstly I just one two three four okay in the past four loop I just um prefix all the sum of the I just prefer this sum okay three and 536 and 64 10 okay and in prefix exam you need to sum it the current value is my previous all the values okay one three seats strength and I just um you know I just prefix some here and then afterwards in that statement uh you can see the statement uh any statement was said that in the fast index in the last index you just get a zero in the left in the right so I just Define two indexes if I is equal to n and this time I just need to zero and when indexes is I is equal to 0 that time I just need to all the elements 0 because the left one is zero okay I just I specified to condition and else uh if I am here this time I need to let you actually I got the previous old value uh so uh previously below if I uh minus I minus 1 I will get the all previous below here in that below if I want to get that time I need to just get n and here I go all below here n okay and n here I've got all below Eureka 10 I got all value on previous value I'm going to show the example okay uh here you can see okay I just one three six ten okay I just go to prefix sum of all element okay I'm just here and then uh if I um I got all the prayer in this value if I minus 1 okay then I got three in all previous by login and here I need to get all the right Barrel okay uh when I need to write below that time I just need n and n is equal to 10 if I remove all previous value from here then I will get the right Bell and this Edge actually in the ISP specified three condition and otherwise if no such is a condition here then I would reach on just minus one yeah that's all thank you guys for watching
|
Find Pivot Index
|
find-pivot-index
|
Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
|
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
|
Array,Prefix Sum
|
Easy
|
560,2102,2369
|
95 |
hey everybody this is 2nd of september leeco daily challenge hit the like button to subscribe and join me on discord let me know what you think i'm going to be doing this all month uh and probably a little bit longer um yeah let me know what you think um i usually solve it live so if it's a little bit slow just watch it on a faster speed or a slower speed whatever you need to do okay so given a unique binary search tree to return or structurally unique binding that there's from one to n you turn the antenna in order okay so i mean i think the first thing to kind of get a coin into two it is something called a catalan numbers um just google this i suppose um but it will let you describe the number of caravan trees um and i forget how it is actually i remember the first couple of sequence but let's see so basically for ng goes to eight it goes pretty fast but i yeah so if you look it up then here's the first numbers in the sequence and that is to say uh eight is like here right which is to say that it is small enough to be brute forceable as long as you do it in a smart way okay uh one two three uh it has to be a search tree hmm did i mess that up uh yeah but yeah so then the idea is that okay so why do we do this exercise the reason why we did this exercise just so that we can show that um brute force is going to be fast enough is the good idea and that's pretty much the idea because if the brute force is good enough then we can just move first okay and we start by uh yeah we start by just uh choosing the uh root number and then we kind of uh how do they want us to return this okay just like the root note or something hmm this is very awkward though maybe um it's a very awkward thing because you have to return the route and you have to create it multiple times and stuff like that um let me think would that make sense because if i'm gonna do it recursively then um if i do it recursively you know you have to make an instant of the tree from the root i guess that's okay right maybe yeah i guess so this is pretty awkward though but okay fine um but yeah the idea is that okay you have uh you know that's just called recursion i just call it go for now no for note and then maybe just like a min and a max right we have an answer thing that we keep track of and then it's just a for loop right if and if you go to mx then we just have one loop or one node so then we how do i hmm how do i know if all the numbers this is very awkward let me think about this for a second so i can brute force this in a way that makes sense it's just about taking a snapshot to take each of the root every time it's basically the idea of what i want to write let's just return nothing for now um what i want to write is something like for x is in range from is it one or yeah okay one to n plus one to be inclusive then we basically have a say a root node is equal to uh was a tree node of x and then would left is equal to uh go of i don't know and then it goes from one to x minus one on the left and then something like this right oops x plus 1 and then and so we have something like this is kind of how we want to do it and then i guess there's nothing to it's just we have to get all these possible trees and then just combine them in a good way okay fine i thought there may be something that clever that i can do but maybe not so yeah so left trees is equal to this we do white trees is equal to this and then ants and then now we have to do every combination of left trees and the right trees to combine them yeah i think that's right so yeah so then for left three and left trees with that left as you go to left tree with that and then we need to do another for loop so i'm writing this in a very poor way to be honest so i don't i hope that this is a interesting video um because i think i'm saying this in a really poor way not gonna lie okay so we don't actually do this we do it here okay that's what i'm doing wrong okay so with that leverage you go left tree with that right is equal to right tree and then answer that append root right so this is a top step thing um and now we have to implement the recursion so now what does this go mean just go returns or return all possible trees of m n to m x and you can actually make an optimization here to be honest um if you really know what you're doing because as we said these are counter numbers so it only actually the number of possible trees only matter between the number of delta so then here you can take this and then in theory like for example if there's five numbers in between it's always going to look the same um so then you can kind of like do an offset instead so that you add every number by that um but i'm not gonna you can play around that if you like um because that is just more uh complexity so then here for now i'm gonna write something like trees is equal to emptiness and then this is the same thing which is that four left tree in oh whoops let me think about this for a second what happens if you have an empty list because right now we don't have an empty list or like we don't handle that correctly um so we might have to do it um well this can only be empty if the number is empty right so we just put it in the trees okay i think that's fine um and you'll see what i mean in a second i guess um okay so m if the min is greater than max that means that there are no elements because so then we just return this i think that should be good otherwise uh this is the total trees left trees as you go to go of i don't know why we haven't known i guess we don't really need to know i was thinking that we did for some reason but i am well sorry i didn't really think about this ahead of time and i usually stop this live like i said um so and this is a problem that i haven't done in quite like this in a while at least not because usually i do recursion that's similar to this but then you don't really have to recreate the structure of the tree uh at least and make it a copy every time so this is something that i didn't really think about in quite these ways but so let's think about this so what does this mean so now we have to look at the middle element again right so this is for mn mx plus one because we want it to be inclusive then now in this case left trees is equal to m n to x minus one again uh right trees uh is equal to go of m uh x plus one to max plus oh no not plus one um actually and we don't even need this to be frank i think we can actually just uh return go of from one to n inclusive and then we don't need this anymore um and then now we go basically what we said before and i'll i'm gonna explain what i did in a second but for now um this is what i'm going to do notice you go to 3 node of x but basically it's just brute force but trying to do it in a clever way which i failed uh but i am rewriting it so hopefully this just at least makes some sense uh nothing left three note that right as we go to the right tree return oh no not yet return trees so three is a z uh dot append of node because this is the new root of the node so yeah so let's give it a spin i don't know if this is right well okay it is right if we literally get everything but it because it's only eight we're going to dry all of them i suppose both for correctness and also one time i guess this is good so yeah so this looks good so let's give it a submit uh yeah so this looks good uh yeah i mean we gotta accept it so i got a phone call real quick uh so i had to ignore it because it's only spam who gets a phone call nowadays anyway uh especially at the middle of the night um random number anyway so yeah so this is just the proof for us and i think i didn't really think about this in a good way to be honest um but yeah and basically once i uh able to kind of ask myself what i really want to answer and that is to return on a possible tree from one to uh some number then we can do this thing and then we can just literally it's just a brief force right because this is the trees dump all possible trees and on the left side these are all possible trees on the right side and then we literally you know and square them not really n square but just get all combination and then put them to the left to the right and then create a new tree um yeah uh so what is the complexity of this it's gonna be hot it's a little bit tough to say but to be honest it is roughly speaking it should be roughly speaking all of canada numbers which is a weird thing to say but this is uh you know uh yeah uh because for each possible because they're kind of numbers of them right and then for each of them we create a new space so this is going to be our fan um and of course we look at each so we look at each three ones because each tree is that even true maybe i'm lying about this i'm not quite sure i think and carrying the numbers is uh and cube i think so this is going to be probably end to the fourth is my guess um but this is a very awkward looking thing so i'm not quite sure uh in the worst case uh that i mean at least you get the honesty from me but it is very brute force my guess is i just end to the fourth for end to the fifth uh because of some weirdness here uh maybe you take a look but yeah um but yeah but basically the idea is just brute force implementation even though this is a very slow uh one but once i get the idea um it should be okay and like i said you can actually uh do some things where this you can only you only care about the min and offset and then you can uh or just the offset and then using the min you could cut you could do some math to kind of copy over the trees if you like but um but yeah that's all i really have for this one let me know what you think this is a really weird one because again because you have to generate the trees not just like something that takes care of the structure a more common problem that kind of use this structure or use this kind of recursion is um going to be more related to dynamic programming um or like parentheses and brackets and so forth uh let me know what you think that's all i have for this one uh it's a little bit tricky i don't think i explained it that well but anyway we're going to be here all month so come join me on discord or just on the youtube leave comments ask me questions let me know what you think anyway stay good stay healthy to good mental health i'll see you later take care bye
|
Unique Binary Search Trees II
|
unique-binary-search-trees-ii
|
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 8`
| null |
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
|
Medium
|
96,241
|
350 |
Yes, hello, there are 2 of these. The problem to be solved today is Leeteuk 3, number 150, l Section 5, Tour Race Turan, and the problem is as follows. Two arrays are given and the problem of writing a function that calculates their intersection is given. It's almost a child, and this is the array element of the number of number, and it's a stuy. I 'm looking for a million intersection. Okay, let me 'm looking for a million intersection. Okay, let me 'm looking for a million intersection. Okay, let me solve it. Uh, I used a lab to calculate the score. If this number is for each of these elements, I checked it when they are present and when they are not. If they are there, I definitely do it. For example, in the beginning, the first element since the number is one, but since there is no value with this as a key, it will be difficult, and this means that there is now one. And if 1 2 1 to 1 comes back in one minute, the key is already one. Since there is, we add one more number here. Then, for this first array, the elements of the elements become the keys. In particular, the value for is how many times that element appears. So, after calculating this, I guess I missed one. Umm, the answer is to send az Havre. This creates an l day pair and looks at the second array. Now, we need to check the elements that are set in the map. If there is a * value and it is greater than 5 velica consim 0, that is. There must be a value. If you find a while passing the number, you should add the value and subtract the number from the app. 4 If you turn like this, here is the set. Only the initial version will be included. Let 's submit it. 4 You can check that it has passed successfully. I 's submit it. 4 You can check that it has passed successfully. I 's submit it. 4 You can check that it has passed successfully. I solved it like this, but I would appreciate it if you could leave a comment on how you solved it. I will see you in the video for the three of you. Thank you.
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
746 |
foreign problem 746 being caused climbing stairs so we are giving an integer request as we can say this cost for 10 15 and 20 and where cost I is the cost of the ice step so this means if we step at this position it will take a cost of 10. and then we can jump here or we can jump to the next one it means we can jump to either one step or two steps so what are we going to return we're going to return the minimum cost reach the top of the floor so from the beginning if we are starting at 10 for the next step we if we Step At 20 it means our cost is asserted but from the beginning we can also Step at 15 so it means 15 is okay because our next step will jump two steps it will go out of the array so it means with already with the top of the floor so it means it is a 15. now let me go to the Whiteboard to explain my method and then go back to the code Editor to finish the coding yeah so for me because I can jump one step or two steps so by the from the beginning I can be either at the first index 0 or at the indexed one so this means from the beginning iot some I will start from the second from the index two from the third index from this prison because from the beginning I can be here or here it does matter but where can I go from go to this prison I can go from 15 or I can go from 10 yeah so there are only two places so this is my state so my DT is the cost of rain I can initialize a DP or I can use the cost agree directly because for this reason I am coming from this 10 or I can come from this 30 because this number is 15 of course it cannot be like that but what if this number is just like for example one so if I go from 10 plus 20 it is 30. if I go from this one if this number is 1 it means 21. so 21 is smaller yeah if I go like if this number is a 15 it means a 35 yeah so it means the 30 is smaller but what I gonna return I first need to return the minimum of those two values so of course 15 is the minimum so I gonna return 15. because I can jump out either from the 20 I can jump one step out or I can sample from the 15 I can sum two steps out yeah so according to this kind of you are analyze we can prepare our DT so DT is the minimum of so uh let me prepare the DP actually we can also use the cost array indirectly so it means the cost I so at this position it is a COS I will start from 2 index 2 so the cost I will be the minimum of the cost what cost I minus 1 let's let me use a say I minus 1 and yeah let me make it clear so yeah the transformation function we're going to use a c as cost so say I will be equal to the minimum of say I minus 1 and say I minus 2. and bring it also to plus this value we should also plus this say I yeah so this is a the result from the CI but what we're going to return as you can see the minimum of those two numbers is 10 plus 20 is 30. so after updating the array will be 10 15 and 30. what are we gonna return we just need to return those two minimum values that means the minimum of say minus two so we can use it this way to represent the minimum of last two numbers it is a 15. now let me go to the code Editor to finish the coding so we can just start from the second index from the index to the third index so for I in range 2 to the length of the cost and the COS to I so the plus equal to minimum of positive I minus 1 and cost I'm minus 2 and what we need to return is the minimum of cost from the last two values so here will be -2 yeah so in this case so if there are -2 yeah so in this case so if there are -2 yeah so in this case so if there are only two numbers for example the cost of less is two it means we're gonna not execute this line we have to return the minimum of the two numbers but if there are more numbers we have to use the DT to calculate until the last value but we're gonna return the minimum of the last two values inside the cluster ring now let me run it to make sure it really works as you can see it works now let me submit it to that if it can pass all the testing cases and by the way the time complexity is just on because we just use one Loop and this is a DP method as you can see it's pretty fast it's nearly 50 of all prices with submissions thank you for watching if you think this is helpful please like And subscribe I will upload the money called problems like this see you next time foreign
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
357 |
Hello everyone welcome back to my YouTube channel Dashrath will dip for next and account number will also be there like value means number 21 from 2010 to the earliest how many numbers were deleted in 1969 usage all three are under the control of Ravana means I am any one in this how many From number to video, today we look at this program as if I had to go for friendly suicide, you had to say something, changes from zero to five were found in the middle of this, so it is in the middle that I should stop doing this, it is like you. From the perspective of how many numbers are there in looted 9829, the mother digit on one side of it, from this experiment to 99, how many are there in it, I will braid it. Okay, this will have the advantage that if I get angry, then any such thing, all this. Things will break, just add Noor Jahan in it, I keep it from zero to nine like this, my problem is and how many are unique in the house, how many in this range, the problem of simple is fine that if they come out 2.1 sir, add ghee in it and that if they come out 2.1 sir, add ghee in it and that if they come out 2.1 sir, add ghee in it and powder them. It is okay to know the pipe and then I have to add it in the last, okay, I will make it a medium okay, so now whatever is the cash, friends, give me my unique, I will make the 2nd note, this lead take off but did. Not denote that it has kitne baje hai Okay okay now notice my duplicate in it is duplicate one digital all notifications 12345 6809 how many duplicates are there 0 Okay now let's come to the to-do list that a I have duplicate and Can click ok now how many is a two digit total number ok taking tension 9899 - 1090 ok taking tension 9899 - 1090 ok taking tension 9899 - 1090 a total two digit element 128 now it has duplicate sit and will get support from distic 1999 only and only meaning like chief in cd If there is any one of these, then it will be my duplicate, isn't it okay, if none of these are being repeated from all the duplicates, 500 ABCDs are different, now Ghee or whatever small digit we have added to that part, then that should also be this and this. Yo, if any of these happens, I will be duplicated, that is fine, so there is only one in this, how much is the digit, one is fine and that we become a digit, then my Aamir Khan option is one, so that is between all these. I will put one, so here you can put 1134 500 600 800 m. How did it become similar in MP3 DJ? How many 9th parties have I attended in life from Noida? Tenu way, 98100, so there are 9 elements in it, now see, there will be duplicates in it, they can also bring from this. Whatever element is there can also come in it, like I have one to three idiot means this is the two digit number from the number to my number from here you to the number like here I have converted the two digit number from 21 a, what will happen is that you can do this. My duplicate can be made deep duplicate Amazon can make tasty naan from rear * Okay plus this is a duplicate * Okay plus this is a duplicate * Okay plus this is a duplicate that now this is what the whole Delhi says I will post anything about it stay so it is a duplicate this one Those who clean the numbers here, put serial 12345 608 anything, it means that here it is every time Times Subscribe 602 that media tuk toh mere duplicate you and Vikas me kitne 90 - 2018 681 channel end Vikas me kitne 90 - 2018 681 channel end Vikas me kitne 90 - 2018 681 channel end subscribe one Two Three Four is 60 numbers along with that the digits in previous are ok Aplus phone number digits in New Delhi public how many preservatives how many digits in to-do list total how many digits in to-do list total how many digits in to-do list total how many numbers 90 and husband - meaning two how many numbers 90 and husband - meaning two is a message word juicer - NS word it's - I am ok, this is a message word juicer - NS word it's - I am ok, this is a message word juicer - NS word it's - I am ok, this is my total number - delete it ok so my total number - delete it ok so my total number - delete it ok so this is what I have subscribed to 100 2nd T20 - 09 2nd T20 - 09 2nd T20 - 09 loot ok, just try to calculate for this Gomez Heroine, then my point came for this So duplicate my dad will check number 10 in to-do list so this is done quick now see this in this that I am in law-2000 123 45678910 so this note's law-2000 123 45678910 so this note's law-2000 123 45678910 so this note's no zero is okay next 9 news room should be asked that I Just that it is handed over to 9039399912 Eminem's in Delhi For any query for means from zero to come or by hands but this picture has to be calculated okay so that I will return the notifications swear from zero to three okay So now you can also do this like this, if you store all these open tickets of gravity, then you can directly return the traffic jam said that I agree, then I will add it in this train. It has come then it will do 1031, it is done, it is okay if you install it in advance and keep it, then the better thing is that it is my time delivery, that is okay, then who asked you to get it for you, I will tell you that my 291 means the same. Meaning of things, either this was the account number and units, okay, you will know that this is okay, I will make Fabric Shankar famous again, or it will become easier, okay, so the solution has been opened, okay, the space will be there, then it will be butt. If you do this today, then that other school's time acid, if there is one more thing like this, I gave toe sacrifice 100 grams to the friends of WhatsApp castes, okay, then you can directly see the agree message and give the answer and it will be believed. All about this video, if you like the video, please like and subscribe to my channel, see you soon in the next video
|
Count Numbers with Unique Digits
|
count-numbers-with-unique-digits
|
Given an integer `n`, return the count of all numbers with unique digits, `x`, where `0 <= x < 10n`.
**Example 1:**
**Input:** n = 2
**Output:** 91
**Explanation:** The answer should be the total numbers in the range of 0 <= x < 100, excluding 11,22,33,44,55,66,77,88,99
**Example 2:**
**Input:** n = 0
**Output:** 1
**Constraints:**
* `0 <= n <= 8`
|
A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
|
Math,Dynamic Programming,Backtracking
|
Medium
| null |
129 |
hey everybody this is larry this is day three after october november whoops wow time just keeps flying by to the november league daily challenge hit the like button the subscribe button join me on discord especially if you like contest problems and the code problems and so forth and just you know hanging around with smart people or me anyway today's problem is some root to leave numbers you're given root okay you represent numbers when okay that makes sense under some okay um yeah that should be pretty straight forward-ish forward-ish forward-ish um yeah i mean i think this is so the way that i always think about these trees um or maybe not always but the way that i explain it in any case is thinking about it you know okay start you know the tree is a complicated subject or complicated data structure at least maybe until you get used to it a bit so the way that i think about it is think about linked lists right uh okay i know linked list isn't that much easier i don't or at least depending on the problem it's not always easier but for this form ring of a linked list and then when you think about linked lists think about in a way instead right and in this case um you just think about okay what happens if you have an array right so for example let's look at a tree let's say you have this tree right here right four nine zero five one right so then you go from four nine five and then you remove the last digit and you add one and so forth and then you kind of go back and then you put in the zero right so these are the ideas that i would think about um if you're having trouble with these kind of problems these are the ideas that i think about and then thinking about it how to do it for a linked list and then just you know pop it off one at a time or something like that either of the explicit stack or an implicit stack by recursion so okay uh i think that's all i need to do there are couple ways you can do this one with global variable and another one just by just returning the sum of the numbers um i'm going to use the sum version just because i think it's cleaner even though it is a little bit more confusing if you ask me possibly or when you're coding and or for this one it's pretty okay but when it gets more complicated it is a little bit trickier but if you practice enough it should come at least more of a um of a thing um and actually so yeah i mean i think you can actually just use this directly um so maybe we do that um okay right so total is equal to zero um so if root dot left is none and without write is none we return so this is the child right oh actually no we can't do it this way i forgot that never mind me so we have another one with um so far digit i think something like that or current something like that um and then here so we have a couple of uh cases right which is if this is a leaf node or maybe if node is none we return zero right um yeah because let's notice not n and this should only happen if the root is none to be honest but yeah otherwise if it is a leaf then if this is a leaf then we return current otherwise we return total of node.left total of node.left total of node.left current times 10 plus know that value plus total dot know that right current times 10 plus know that right of course this amount is just the next amount maybe i could put in a railroad as well um yeah shifted maybe you could call it that i don't know that makes sense but it's just basically the next number right um taking a kind of current digit um yeah is this right no i think this is wrong actually i muck it up somewhere huh because basically if this is leaf and we calculate beforehand and this should be wrong actually so i think actually this is how do we which way do we want to calculate before or after um we just have to be consistent i think both way doesn't really matter as long as you're consistent so here we just do first know that value and then here we can just return total root and then zero because now it doesn't take account that and that's pretty much it you can actually still use this thing if you really wanted to change the parameter by adding an optional parameter but hey i think that's a little bit sketchy also i'm really wrong apparently so uh where did i go wrong and i was just saying how easy it was and then i just messed up okay huh that is oh i'm just being dumb uh well i mean it still might be oh yeah i'm still just being done because i forgot to shift at all um so we definitely still need to shift yeah okay i don't know why i start um yeah we still need to shift but we also need to shift here i think is my point whoops here uh whoops huh there you go uh let's put in some test cases some edge cases was it none or no what is the thing that they prefer something like that a tree visualizer this yeah that looks okay so one two three right okay so that looks good let's give it a submit cool 582 nice um yeah so this is going to be linear time linear space linear time because we look at each node at least once and as a matter of fact the lower band is of n right so it's going to be in um because you have to look at your jump once so you at least look at your node once and you have to look at each node one so it's going to be linear time because you have all of n o of n uh notes and linear space or of h space where h degenerates to end with this if you're given a linked list essentially um where h is height maybe so that's just a stack space so yeah um that's pretty much all i have i think this is relatively okay as long as you don't make silly mistakes like i did let me know what you think um anyway i'll see you later stay good stay healthy to go mental health hit the like button and subscribe and join me on discord and i will see you later bye
|
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
|
402 |
hey everybody this is larry this is day 18 of the february leco daddy challenge hit the like button hit the subscribe button join me on discord let me know what you think about this problem double checking that this time i'm recording the screen okay we're good here uh yeah uh so i am actually today in katahina hopefully i'm saying that correctly so yeah um so i'm doing a bed uh a bed stream so hopefully that's okay uh because even though i requested a room with a table unfortunately sometimes things just don't work out and the internet's a little bit shaky so we'll see what happens but at least this should not require that much internet issues so yeah anyway hope everyone's doing all right i hope you know everyone's having a great week so far this is uh yeah friday or wherever you want to watch it today's problem is 402 we move k digits okay so given string numbers so far we will win k digits from num okay um so these numbers usually or these type of problems i don't know if it's a type but uh the way that i always think about it is greedy right and why is it greedy because if you have two numbers let's say or one three two four something like that right um almost it doesn't i mean so like the um the most significant digits and they call most significant for a reason um like that's all that matters right and only when it's tied early on that later digits matter so in that way we're trying to figure out how to um yeah and then we could figure out the rule in some way to figure out that how to be greedy in a consistent way and you many of the times there are some like um uh what you might call it like edge cases maybe um to kind of think about uh different things but uh but for this one probably is not as uh hopefully it's not as tricky so let's see um and the first thing i would do is just look at um the examples and just kind of play around with like um like thinking about in a new because these kind of greedy problems with the most significant digits um type thing a lot of the time is intuitive unless you miss a case or something like that but it's still mostly intuitive because you see the entry like oh yeah of course that's right so there's no like hidden cases almost but uh it's just about like experience and your limitation of imagination or just like practicing or whatever so yeah um the way that i look at is look at this number um what are we supposed to do the smallest okay the smallest so um there's also maybe an other way of doing it like okay maybe not ten to the fifth um another way of doing it um so one is doing what they tell you which is we move k digits so in this case you move to 4 3 and 2 as they say the opposite of course is to keep x digits right where x is equal to n minus k so for example in this case there's seven digits you have removed k is equal to three another way of saying is you could keep four digits to keep it the smallest way um and yeah and maybe that's the way to do it uh do i um kind of frank right um yeah and i um i'm just trying to think about which way is a little bit better uh also this one there is some strangeness to this one though right because look at example two even you will move one digit you already lose a lot which is pretty an awkward weird case so maybe i'm a little bit wrong on this one my earlier assessment yeah um it seems like it could be tricky to do the keeping one because of these zeros and stuff like that um let's see so how do we remove k digits right so um i think we could do in a greedy way actually so what we can do is process from right to left to keep track of the numbers to the right but then here we go for example four um it's four okay well let's go let's start with one obviously right okay let me put it here so that we can see a little bit better i mean i think i now have an idea which is that okay you start one and then you ask is there a smaller digit to the right to kind of uh keep it and if there is there one that would give us um enough digits right what i mean by that is that if you want to remove k digits um and for example let's say you have 0.5 and for example let's say you have 0.5 and for example let's say you have 0.5 uh i don't know how let's do it uh let's see what's an example in my mind but let's just say you have something like okay yeah so you have something like five and then one right so in theory you'll be like oh two but then you could go to this right one in the right but let's say k is equal to uh just one right um if you skip all the way from this two to this one then you already used up all your quota of case um so that's not possible so then now you know that you have to keep the two um do the same with three four and then when you set to five you say okay we only have to keep k is equal to one so then we can delete it right um so that's an idea it's not quite complete yet i don't think because the idea is because i think there is a trick in it or it's not that tricky but it's just about thinking through the cases is that so you have a similar thing where it's something like this but you ask yourself okay let's say you have maybe a similar thing right okay they just use the same thing but now you have two numbers right and then the question is let's say k is equal to maybe two um then the question here is okay let's for example the five do we go to the one or well or do we okay let's go start from the left right let's see the two uh if we go to the one then we skip four numbers so that's no bueno uh let's say we have the three then we go to the one then we skip three numbers right and then before we go we skip two numbers to go to the one i guess that's good um actually maybe a different one is something like this right maybe that's slightly different um i'm just thinking about the cases allow as well so um yeah so for example at the four you could remove the four and the five to get the two or does it make sense to me move to five and then two to get the one right in this case it actually is okay to get to two i guess the differentiation that i'm trying to think is whether it's okay to get the next smallest or the actual um i think you just keep going to see because then i think the idea that i'm trying to think is okay right like i don't know if i'm articulating the edge case that i'm uh struggling with in my eye a little bit um which is that okay um like you can add more digits to kind of make this like fluff it out a little bit or whatever but then the idea is like okay like let's say at this four let's move to five for now where uh here at the four do you remove maybe it doesn't come up because maybe in the earlier stages well in this case it's a little bit awkward but let's come let's just change this to a two and a three then in this case we force the four right and then the four you ask okay so is it better to remove one four to have a three or two digits and have a one right and i guess you have to answer that every time um and i think that's okay because i think you want what you want is you want to remove any number as long as it's in the budget and there's no decision because of the greedy thing that we talked about so that means that um we get the lowest number the no lowest next number that's within k and it's okay to use as much as we can because like we said about greedy the most significant digit is going to like the rest of the digit will be smaller or will make the whole number smaller because you're the most significant digit right so i think that's by basically the idea that i have and then the other thing of course is that you cannot do anything n squared because n can be 10 to the fifth so the idea that you would have here is just keep track of where all the digits are i think that should be okay um i think that's a good start i think this is a little bit awkward though i have to think about how to do this right because this is the only time where where mean this is the only time where uh i don't know maybe i just have to handle zero differently right because the idea is let me see if i could think up something right now because i think the thing that we have here with this removing thing right is that we always we replace one digit with another digit which is obviously you know good for our greediness but then this case kind of breaks it up right with the leading zeros because effectively for 1k cost you can um you can remove multiple digits right all the stats still hold let me try to think that for a second um so i'm moving the camera a little bit closer or whatever uh because maybe that still holds right because for if one goes to z like we look at one and then we look to the right and it goes to zero um yeah i mean i think that then we can go to it and replace it and then we just kind of chop it off or whatever um excuse me um okay let's see i mean i think this is where oh i hit my elbow in something um i think this is where sometimes we um let's just run it out and see what it feels like um and you know and this is where i always am a advocate of tdd to an extent um at least especially for uh lethal e-problems because well for uh lethal e-problems because well for uh lethal e-problems because well they're very self-contained right so they're very self-contained right so they're very self-contained right so it's very easy to kind of think about it so here let's think let's at least solve the other cases and then we can talk about um this is pretty awkward but uh yeah and then we can talk about um yeah and then we can think about the edge cases this is i mean i guess this is a medium but it's still kind of very tricky though but anyway okay so n is equal to length of nums um and then okay if n is equal to k we just return zero i don't know if this is necessary but i just feel like eh okay and then now we have we want to pre-process the digits so index pre-process the digits so index pre-process the digits so index x in number way num what we want to do is let's just say look up of x we append the index and look up we just have a collection start default deck of a list right um yeah okay and then now we go again for actually we want i want this to be a deck maybe uh do i want to do this actually what i mean by that is how do i want to keep track of what to remove and what to keep right so okay so here maybe we can do something like okay let's just say uh we move maybe is to go to force times n um yeah maybe that's fine and then now we start with the current index at zero say and then we do while index is less than n what do we do okay current indexes of this is the current number what we want to do is let's sequence you go to this student uh let's just say this is an end actually i need to fix this because this is a string so then now we just go we count backwards right we got for yeah for i is in range of from current minus one to zero and then you know recommending right so basically the idea is that we um the way that i don't think i explained it that well but so the way that we have it here the idea is that we can look um look up the next num next index that's in here right so then here we greedily um actually this is a little bit awkward i think what we should do is greedily look for with zero um from zero to i think i just became used to writing it but yeah from zero to current um yeah and exclusive of current because if it's the same digit keep it anyway i think that makes sense because you can always remove future maybe actually i don't know that is very awkward isn't it that is another case that i don't know if i considered for example like if you have i don't know let's see if you have like one two uh one two three two right and if you could remove two digits um you're at the two do you remove the three or do you like the two and the three or you just keep going i guess keep going it's fine because and the three you replace it with that next number anyway so okay so i think we're okay here actually um yeah okay so then here we go okay if do look up of current um so first we checked that this is um we've checked that this is uh greater than zero and lookup of current of the first um index if this so this is the index that is what um the next digit of it so then that's minus index um so what this is saying is that we're replacing this with that so if this is greater than or so if this is less than or equal to k um then we do let's see so this cannot be zero so this is always going to be at least one and if this is one then we will move one digit so okay i think this is yeah i mean this is right and we can use eco too that's what i'm trying to think um then we you know we subtract this delta um and we remove uh we set indexes to go to lookup of current of zero and this is where the deck comes from um but yeah and that's it i guess what i actually forgot it or not forget but i didn't do is that while lookup of current is greater than zero and um and look up what i have to fix the typo first lookup of current of zero is less than current then we pop right we pop left so basically it's just getting rid of the old ones um and you know and the reason why i don't worry about the complexity is that for each number in the input that each digit will only pop once right so this is going to be linear that looks really awkward right now in general um yeah and this is okay and then at the very end we have to figure how like okay so now we skip to it okay we want to do here is brick actually okay i'm trying to think so what i'm thinking right now is how to move to index if did all these fail um i guess i could do this and that should be fine note that we didn't use the remove yet so it's a little bit awkward but that's fine here we can do some a quick for loop of for x uh yeah okay for x in range from the current to look up of cour nope this is i think i'm mixed up somewhere that's my oh man just i have this for i and then i keep on using current so actually all this is wrong uh because and i only know this is now my four friends uh from okay so from current to uh this thing that i should probably cash it so because i keep on calling it and it's not free but it's wi-fi and it's not free but it's wi-fi and it's not free but it's wi-fi um and then now we go we move for x as you go to true and that should be good right um and then now we can do something let's just print this real quick i'm just trying to see whether this um make sure that i didn't have any infinite loop situations um today collections oh this one whoops that's what i'm trying to fix okay so here we don't remove anything which is obviously pretty bad but um that's weird actually so things go for this is the okay uh this index is right okay just as you go to this is i uh okay so what i'm struggling with is that i keep missing current and index this should be index so this pops uh this is a good the current is the number of digit um so that's not right we have to go from index to there which is actually same as here so this one's right um and here this is lookup of i now look up current uh a lot of silly mistakes on this one not gonna lie okay so this looks a little bit um it definitely looks a little bit better but uh but still wrong because this is now saying oh no this is the remove i forgot if i was doing remove for tip but then now you can do something like uh return to do that join um maybe something like uh zip of remove and nums uh let's see for r and or x in this if not all so if it's not removed then we keep the x yeah okay oh but i'd have to remove the leading zeros but that's okay yeah so i have to remove the leading zeros um i'm surprised this worked actually oh no that's because i had this but i could also do um i have to do another test case of just leading zeroes of okay so you know of one um is that the only one or this and also two maybe but we're mostly there actually so we should be pretty good having all we have to do left now is just remove the leading zeros um so i think there's a left strip of i think that's right oh but this now gives me the wrong answer for zero itself as you can see this is annoying okay fine okay so this just basically checks for leadings uh check to see if there's no digits then it's zero um what did i click on an ad i guess um am i good this is kind of yucky to be honest uh i'm okay with kind of submitting a yolo level let's give it a submit apparently i did it last time in the first try so oh no huh how did i miss this oh i forgot this one case is true so i'm already didn't bring last time i forgot that we have to force to do k or force to remove k um because here the one thing so every so yeah this is i don't know if this is the only case that will come up there'll be other cases but what i have forgotten is that this only removes digits if it tries to get to the um the next digit that is smaller but here then we possibly have k left over if you have k left over then in that case i'm trying to think so one thing i'm trying to think is whether it's it is possible to have okay i'm trying to think whether it's still possible to have k left over in a way and uh like my thought process is that right now we only have k left over if is if the result is an increasing sequence otherwise you could always get rid of it right so using that logic which i don't know if it's true right now that's what i'm thinking about and whether i can prove it at least to myself is that if that's the case then if you have k left over we can just remove from the end because it's an increasing sequence right so that's basically what i'm thinking about um i don't know if i could prove that though and i also wonder if like past larry is just like knows it a little bit better because he also did it much quicker i think maybe not much quicker but slightly quicker anyway um okay i um because if it's not increasing subsequence then you can always remove one digit in the middle from one of these things so i think it is true that if k is left over um yeah let's say if there is k left over it must be an increasing subsequence right we can actually as i'm also i'm curious whether i should have assert this but um yeah so then here oops how did it happen uh maybe we'll just use another wrong answer we can learn about it this is also where i would say this is the type of thing that if you practice a lot and these are the properties that you explore when you do the practicing and you learn for next time right so it's not um it's not always bad that you know you use something like this it's not always great i guess either but uh but in that case it just means that you um like the like what you spend on now to explore the properties of these greedy things um it'll come back to help you in the future because you'll be like oh i recognize that and i know that this is true you know maybe you don't know how to prove it per sec right so uh so yeah um okay well uh let's see uh yeah so then here then we want to say uh aiming signal length of i guess you just actually go to do it um yeah uh okay i mean that doesn't okay maybe i messed something up uh what is k i used up all the k on the other one but it would still match so that's a little bit awkward nope it's just zero so shouldn't it be to negative zero return zero is that why um maybe i mix that up so if k is one um does that go to the second to last one or something or am i messed up i always i'm really bad at these to be honest um no so if okay fine uh so if k is zero then it's actually the only case with this as well uh well at least for uh what i was talking about okay fine then if k is you go to zero return answer otherwise we turn this uh the substring of the first fringy okay so that looks good um but is it good enough let's see um i want to do something like one two three four five uh four um and then in this case you wanna remove say six right so in theory it should be one two three four we'll see if that actually happens okay yeah um i also want to see so the answer is that you should have well this five will return it with four so yeah so this should be let me print this k for a second just want to see because it should have like a four or five as a k um just to make sure your upper uh okay so maybe i am a little bit more confident after um you know running the code in my head if you will and then actually running the code uh and let's give it a submit again and hopefully i don't need another one oh no oh um okay fine uh i am sad i'm not gonna lie so i mean this is just me being silly at this point right because this is uh like we returned to zero but we stripped it out somewhere uh so the length was gonna do what how did i remove this stuff wouldn't this be oh because i have okay fine uh okay fine if uh i think i just have to wait the other way oops yeah and then i'm curious how larry passed larry did it uh so careful last time uh whoops also let's put in new case how does that i thought i have a test case that looks like this style maybe not i guess yikes all right this time i hope i'm okay a lot of silly mistakes on this one um but after the dirt go i do have a 689 day streak i'm happy about that less happy is you know me making mixing this up but that said this is going to be linear time and linear space even though this looks very complicated there's a lot of while loops and for loops and while loops you can think about it at that it's linear time well depending how you want to say linear it's linear time because each digit only gets pushed once and also gets popped once um that said because of this loop um it can be you can look up 10 digits right so it's going to be linear times 10 because every time in the worst case you can say that um that for example if the thing is like nine eight or something uh like nine eight seven or nine eight dot um this would go through ten per digit which is linear times alpha if you will which is n times alpha where alpha is the size of the alphabet right um here this is just linear and i hope you understand why for linear and space but yeah uh now let's take a quick look to see what past larry did uh huh past larry used to stack huh i guess that's the same idea um man pass larry maybe is smarter um but it's just basically keeping track of the digit um yeah past that is smarter on this one for sure um and then that um forever and then when you get the digit later that is bigger or smaller than the digit previous then you know basically this is only looking at one digit previous to that um and then just keep on popping it while you can that's basically the idea um uh that is actually much smarter wow past larry well done uh current larry not so much but that said past larry was not in katahina and the current larry is in katana so i'm maybe having a little bit more fun than past larry but uh all right friends uh hopefully this is educational we did it another different way than we did previously but the same idea though which is greedy on the most significant digits so and i know that a lot of you struggle with greedy problems uh and maybe that is just me speaking to myself that's not supposed to be a brag as you can see even though i knew all these things uh it's very easy to miss cases and so forth and that's why you know that's where you practice uh anyway that's all i have for today um stay good stay healthy take good mental health and i'll see you soon bye
|
Remove K Digits
|
remove-k-digits
|
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`.
**Example 1:**
**Input:** num = "1432219 ", k = 3
**Output:** "1219 "
**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
**Example 2:**
**Input:** num = "10200 ", k = 1
**Output:** "200 "
**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
**Example 3:**
**Input:** num = "10 ", k = 2
**Output:** "0 "
**Explanation:** Remove all the digits from the number and it is left with nothing which is 0.
**Constraints:**
* `1 <= k <= num.length <= 105`
* `num` consists of only digits.
* `num` does not have any leading zeros except for the zero itself.
| null |
String,Stack,Greedy,Monotonic Stack
|
Medium
|
321,738,1792,2305
|
1,870 |
Today we will do the question of 26th July which is a very good question, you will get to learn from it, now just stay till the end of the video and try to understand that this is a very good best question which Above we can solve many different types of questions. Okay, let's read the question. The question is Minimum Speed of read the question. The question is Minimum Speed of read the question. The question is Minimum Speed of Minimum Speed, Arrival Time. Look, there is a lot written inside it, you have to read it properly and you can do it yourself. Try to understand, I am just trying to understand you directly, see what is written in it, one us is written in the lowercase, it means whatever destination we have to reach in 6 hours, like Maa Lo's office, we have to reach the office in 6 hours, okay, 132 is written. This means that we have three trains and you can control the speed of these trains, so what you have to do is that you have to deliver within 6 hours and by keeping the speed of the train as minimum as possible, if you want to deliver Valentine then For this, what you will have to do is that you will have to find a speed which is minimum to minimum and will also allow you to reach on time, but if you look at the example in this one, if we move at a speed of one, then first the car will take us one kilometer. How much power will the train take first We will decide that the speed of every train will not be there and the speed of the train should be that of waiting. Look, it is written here that there should be positive waiting speed of the train. We have to find out the minimum positive waiting speed of the train. If we go to the speed of one ISP then we will calculate. What will we do if we go at the speed of one, will we be able to reach on time? So see, if we go at the speed of one, how much time will it take to go one kilometer? One means one kilometer, then how much time will it take to travel one kilometer at the speed of one? Here it is calculated one by one i.e. one calculated one by one i.e. one calculated one by one i.e. one hour and then at one speed the next train will go 3 kilometers, then at 21 speed if it also has to go 3 kilometers then how much will it cost 3/1 i.e. it will go for 3 hours means it will go 2 kilometers. How much time will this also take? 2 hours, then how much time will it take in total? 1 hour plus 3 hours plus 2 hours, then how much time will it take in total, 6 hours and we had to reach within 6 hours only. Okay, you cannot do this that you limit the speed to 10. I have done it in kilometers and the first train is the train. Brother, it is normal that the first train is which is 10. If I do it then it will take very less time to spend 1 kilometer. Like mother, it took me 5 minutes. If it took 5 minutes then you You cannot do this that in the next minute you board this train, its search is also written here, it is okay if you reach here in half an hour, then you will have to wait for the remaining half hour and board another train. Okay, this is also a condition. Okay, this condition also has to be kept in mind. But let me try to understand you better by taking the example to notepad. Okay, let's say 132 and we have 2 kilometers here. Okay, and we will have to travel on every train, just like this mother, first you will go 1 kilometer on this train, then you will board this train, it will be 3 kilometers, then on this train, go further 2 kilometers to the direct office. When you reach there, you will have to control the minimum speed, whatever speed it is, you can control it like, take mother, you take mother, if you make the train run at a speed of 50, then how much time will it take to travel 1 kilometer, one hour 50, now take mother. It will come to 0.2 something one hour 50, now take mother. It will come to 0.2 something one hour 50, now take mother. It will come to 0.2 something but like if your mother reaches in 5 minutes then what will you have to do then I will have to stand for the remaining 55 minutes because any train that starts will start after an hour. If you have the power to start after any hour, then no matter what speed you go in the first train, it will take an hour because you will have to wait, okay one hour, if you go at a speed of 50, then it will also take 3/50 of the time, so that Also mother, it will take 3/50 of the time, so that Also mother, it will take 3/50 of the time, so that Also mother, it will come in a few minutes but still you will have to wait, so you will have to add plus one to this one too, okay and in this one, two bets, 50, so in this one too, so I will come in this one, zero point, anything will come because in this one, you You will reach there, just like mother, take zero point, if something has come then the answer will be 2.7 something, if you answer will be 2.7 something, if you answer will be 2.7 something, if you drive at a speed of 50 then it will take you 2.73 time to reach. First you have understood this much, 2.73 time to reach. First you have understood this much, 2.73 time to reach. First you have understood this much, imagine that if you go at a speed of 50. So you will reach before 6 hours and what did you do, you drove the car at a very high speed. We have to ask the questions which are the problems in real life. Just like mother, I go to my office dear, I think 30 minutes on foot is fine. What will I do? He will leave the house exactly 30 minutes in advance because I know that I will walk comfortably and reach there in 30 minutes. Well, I can also do this, leave 5 minutes earlier and go running, but that happens to him, so here is the question. Will also make it in a similar way which matches a little with real life, okay what we have to do is to minimize our speed, we can control our speed and we know at what time we have to go, it is given to us, so time it. For example, we could have gone in 30 minutes, now we have 20 minutes, but 20 minutes does not mean that we run very fast, we reached in 2 minutes, so if we have 20 minutes, what will we try to do so much? Walk at such a speed that the exact question should be reached within 20 minutes. That condition has been designed here. Okay, so now look, I have explained what is happening in the question. See, unless you understand the question, it will be very difficult to answer it. Okay, so now what do we have, look at the number of vehicles, it is fixed as per the size of the area, the number of vehicles is the number of kilometers each vehicle will take you to travel, that is also its value, like if it is one kilometer then it will take three kilometers or What will be the total distance of 2 km? He knows that this will be the total distance. Okay, so what is in your control? Speed is what is in your control? Speed is what is in your control? Speed is in our control. Speed is in our control. We can control the Speed is in our control. We can control the Speed is in our control. We can control the speed. So, okay, let's control the speed. Let's try to control the speed, as if I try to understand, look, now look, I have come very close to the answer, okay, now look, the answer is about to come, so what will we do, mother, if your distance How much is the total, see, it is 6 hours, you take the maximum to the maximum, so I try to follow the same system, like we take the maximum, if we run it at the speed of 10, I will also tell you how much exact amount is to be taken. Like mother, if you first try to walk at a speed of 10, then let's see how much time is passing. Understand this, I am late from inside, mother, if I go at a speed of 10, then I am late and see how much time passes, if mother, take this. I walked at a speed of 10 and the time was around 6 hours, so that means I can walk at a speed of 10, okay and then I will try to reduce it further like mother lo, I walked at a speed of 10 and the time is 7 hours. What will I have to do, the speed will not be much and if I go at a speed of 10, I mean the time is like 5 hours, then what will I do, I will reduce the speed a little more so that my time seems accurate, then go at a speed of 10. Me, how much time will it take for me, this much time will be taken, exactly one bet 10 plus 3/10, 3/10, 3/10, but the answer of the last one will come in whatever fraction it will be in, the answer will come, okay mother, if x comes, we will not do anything about it. But think about the answer of 1/10, if your think about the answer of 1/10, if your think about the answer of 1/10, if your fraction is A, then it is okay, you do not want to hit 0.0, you will have to wait for it to be not want to hit 0.0, you will have to wait for it to be not want to hit 0.0, you will have to wait for it to be delivered, because as you take it is the same thing, like 30 minutes are going, that is, 0.5. If you are going, that is, 0.5. If you are going, that is, 0.5. If you are going, then the rest of the time you will have to stand here, that is, for every train, the entire time should be spent in waiting. Okay, if the time is not spent in waiting, then I alone will have to take him to the interior. So, what will you do with whatever answer is there, you will have to count it from the cell value, that is, whatever it is, if you reach the next interior of it, then whatever will be 0, it will be something, but you will have to consider its answer as one because the rest of the time I am You have to stand still, you will have to consider it as one and whatever fraction will be the answer, then what will happen is that it will be 2.x, whatever it is, the answer will be 2.x, whatever it is, the answer will be 2.x, whatever it is, the answer will be 2x, so what did you see that if we walk at a speed of 10 If you are walking at a speed of 10, then the answer is 2.73, then answer is 2.73, then answer is 2.73, then you have said that our time is going very less, so we have to minimize the time and we have to minimize the speed, so we saw that if we walk at a speed less than this because we have to Time is decreasing and we have more time, so what will we do, if we reduce the speed a little more, what will we do, now what do you do with the speed, like the speed is now 10, now let it go linearly, what do you do? Do it like mother lo ki minimum speed can be one and now we have thought 10 so next time try no pe na because of search we do it in binary search then do one like this make it 11/2 i.e. 1 + 10 / 2 do one like this make it 11/2 i.e. 1 + 10 / 2 do one like this make it 11/2 i.e. 1 + 10 / 2 means approximately you can search on five, then next you search on five. Now if you search on five, what will happen? 1 / 5 / 5 / 5 3 / 5 plus 2 tell me, if it comes, what should you do if you band it, then see this also. One will have to be added, its band will also have to be added, its mother, if something comes, it is still singing the same, so what can you do now and can you reduce it, how much will one and five be, now you go to three, brother, net search Like 1 / 3/3+2/3, what will be the answer to this also, see, 3/3+2/3, what will be the answer to this also, see, 3/3+2/3, what will be the answer to this also, see, you will have to take one, it will definitely come to one and it still means something of 2.x, come to one and it still means something of 2.x, come to one and it still means something of 2.x, so still you will take one more. Do it between three. If you go at 2 speed then you will see how much time will it take. 1/2 how much time will it take. 1/2 how much time will it take. 1/2 plus something. If you want to go at less speed then one and you are fine. Now whatever is there, walk at the speed of one and see. One by one plus. Three, one plus, three plus, now you have seen that you will keep matching every time, you will check this, whether it is <= 6 or not, check this also, whether it is <= 6 or not, check this also, whether it is <= 6 or not, check this also, where ever my license will be 6, so I will add whatever is there in the answer. With the help of this, you will have to track what is there. Okay, now we have gas here that we will try for 10 first. Okay, what will we do, see what we have taken out, take this in a separate function, we will find out the total. If we walk at this speed, how much time will it take, I have made a separate function, mother, take that function will give us just one time, we will have to walk at speed and what is the maximum speed at which we can walk, now see, I will tell you about the maximum, see here. It is written in the answer bill note what will come in the accept but the example must be telling you why to do 10^7 but the example must be telling you why to do 10^7 but the example must be telling you why to do 10^7 then look at an example if I think mentally like take one comma 1 lakh mother take it becomes one lakh 0.06 sorry understand this Take it, understand this, now tell me at what speed can you take me, if you know that you have to take me in 2.0 one time, take me mother, you have to take me in 2.0 one time, take me mother, you have to take me in 2.0 one time, take me mother, you have to take me to you in 2.0 one time, then what will you take me to you in 2.0 one time, then what will you take me to you in 2.0 one time, then what will you do, see at what speed you go, at whatever speed you can go For this 1 km you will have to pay one hour just like mother takes So for this you will have to give only one consent, in the next one too you will have to give a big 50 rupees, for this also you will have to give one consent, then look at the next one then it will be ₹ 150. See this, 5 times 10 will be divided by zero, so 2000 hours, so two, approximately 2002 hours are being spent in this, it is okay, two hours have been given, so what do you do, here one will be taken, so I am fixed, no matter how much you look at one, you The speed will not increase, now the bigger number you give, 0.1 will keep getting smaller but 0.1 will keep getting smaller but 0.1 will keep getting smaller but 0. Whatever it is, you will have to consider one hour, here also you will have to consider one hour. So you have to try that it takes 0.1 time to travel at this speed. If it 0.1 time to travel at this speed. If it 0.1 time to travel at this speed. If it takes 0.0 one time, it will take 0.0 one time. takes 0.0 one time, it will take 0.0 one time. takes 0.0 one time, it will take 0.0 one time. How will you know? So, if you see two, three, five or six people traveling together, then see if it will travel at this speed, then 1 / 2. 4 1 air maa lo one sher, this 1 / 2. 4 1 air maa lo one sher, this 1 / 2. 4 1 air maa lo one sher, this 0.1 will come very small but still 0.1 will come very small but still 0.1 will come very small but still it will have to be considered for one hour because for the rest of the time I have to stand, the next one should be considered as one but look at the last one, two three five bet two. CAT given 2.0 one, that's why I was saying that 2.0 one, that's why I was saying that 2.0 one, that's why I was saying that start from maximum, that means if 6 hours are given then start trying from 7 hours or start trying from 6 hours, but if any such situation comes then we We will think that we start from one lakh whereas the answer is one crore. Do you understand that this means that we should try the binary search from the maximum given to us because it is like this? 6 etc. are coming and it is given to you like this one comma 1 com like this take 6 commas and here take mother that five lakh is given like this then its answer which is very big will come its answer will be very big okay you You will think that you will try from 1 to 6 lakhs, but it is not possible, the answer is very big, that is, you cannot consider the maximum number or the one who has given you an inferior one, he said that it is 3 hours. If you want to reach the place then you cannot try the number of hours from 1 to 10 because your answer has nothing to do with the number given, here it is a coincidence that 6 hours were given and we were reaching within that time but This six has no connection with what speed we will consider here, hence we will consider the maximum that can be from there, that is, what will be the minimum speed of our binary search, we will take one and the maximum. Okay, so far. Look at how much we have reduced, think about it, we have to reduce only two, what we have to do is to apply binary search on the given speed i.e. one and speed i.e. one and speed i.e. one and find a middle of 20/7, calculate how much time will be taken at the best made speed find a middle of 20/7, calculate how much time will be taken at the best made speed find a middle of 20/7, calculate how much time will be taken at the best made speed and We will create a separate function to calculate the time. What has to be done in it is that Aroma travels and every time divide it by whatever speed you have and add all the answers. If it is 0. Meaning, whatever it is, you have to take its cell. Whatever you want. The answer will come in that cell. Whatever answer will come, Shilpa, don't take the last one's answer in the cell, because you will reach outside, okay, you won't have to wait there, like mother, take the last one, it took you one hour, this one took 1 hour, and in this mother, It took 30 minutes, so you reached there in 2.5 hours, so you reached there in 2.5 hours, so you reached there in 2.5 hours, so you will leave 3 hours here, go and sit in the office, do some work, you have reached the office, so you don't have to take the last cell, this much is understood, now look now. You have to create two functions, one is sugarcane and once you apply it, from one to 10, you give the power of 7. For every minute, for every minute, ask the time function, how much time will it take, if that time. Look at the time, if the time is less than the time given by us, it is okay, we know that the time given was 6 hours and we have to reach it in 6 hours, but we are running out of time. If we are running out of time, what does it mean that our speed is very low? If it is more then we will have to reduce our speed and if the speed has to be reduced then look here, if there is no speed then the right one was here and the left one was here, so if the speed has to be reduced then what should the right one have to do? Mid Mines If you want to do one, then if A is true then you have to do it right. One of the means is this. I understood this and if it is not so then it means that if the time is increasing then what does it mean? What is the meaning of increasing the time? Our speed is less, that is why the time is going more, so if it is so, if the speed is less, then the speed is not big, okay, so then what will we do to the left, what will we do to the middle, because the rest of the left one is The part is not less than that because it is a very low speed, we have to increase the speed, so we will bring the speed which is on the left, which is in the middle, it ends up, you know the answer, wherever it is, where is the answer. Incidentally, we will store the answer every time in an answer variable. Now I have to write the exact code and try to understand it by relating it to other things. Okay, keep seeing what I am writing in the court. Okay, see. The code for this is easy. If you have understood all the things I have said, then see first of all what we have to write here. Look, first of all, whatever is on our left, what will happen to our left? I had said that what is on the left, where does it start? It will start from one, so this much is understood, what will be the left and where will the right start, after that what we had to do is see the answer which will be minimum equal, you see if nothing happened until then, what is the left, give us our list. And you will remain equal to whose right what do we have to do till then Sorry ji HD What do we have to do till then what do we have to do inside the look First of all extract the meat as it happens otherwise it is wrong We will create a function which will return whatever it is If its value is given, if its value is taken as Lee and equal tu is given, what is the meaning of being equal that the time we are taking is less time. If less time is being taken then the speed is more. It is okay if we take it. Whose time was given by us i.e. the time taken is time was given by us i.e. the time taken is time was given by us i.e. the time taken is much less than the time given by us, I am taking less time than that, it is equal then what should happen, see if it is less or equal then it is possible. If this is our one value answer then first of all store it in the mean speed, maybe we have an answer, okay if this is the answer then it will be stored here, if not then what do we have to do, okay guess what? If it has to be taken, then one possibility is that our answer is not there, our answer can be like ours on the left, why see, because the time is short, it means our speed is high, so if we reduce the speed. Reducing the speed means that we have to move from right to left, so what should we do with the right which is ours? If we have to move to the right, then the answer can be this, and after that, when your mobile runs out. After the mobile is finished, whatever is in your mother's speed will be your answer and that will be your return. Now we are short of the time function that has been written so that we can write the function to calculate the time. Ok, let's write it. What will the function which calculates time return? Will it return time? Okay, what is the function which calculates time returns? Now look, this is time as it can be expressed in points too, so double the time because time is Whatever is 2.0 time equals, what do you do? First of all, it is okay because if you wait then it will get messed up. We need everything in double and whatever has been disturbed, you should also double it and keep it in a double variable like double train. I mean, how much time is going in the train, he came to the team, and look like what am I doing, look here, if you look carefully here, like what are we doing. We were doing 1 / 5, we doing. We were doing 1 / 5, we doing. We were doing 1 / 5, we took it in T, then after taking it in the team, when we will add it in time, then we will add its cell function. If we want to add all the ones, then if we do not add the last one, then we will try to write it in the code. Size is -1, that is. It is the last one, if I is -1, that is. It is the last one, if I is -1, that is. It is the last one, if I is the last one then we don't have to do anything for it. Look, for that we are setting the condition that if it is true or not, it means it is the last one, then whatever is the value of T, add it directly. And if it is not so, then what do we do? Its cell function is to make its cell, then its cell has to be taken away. See, what am I doing? Like, mother, take this one, I was making the point, take its mother, whatever will happen. 1/5 As I is zero, happen. 1/5 As I is zero, happen. 1/5 As I is zero, so we have first checked that I is n - 1, if not I, then I is n - 1, if it is not, n - 1, if not I, then I is n - 1, if it is not, n - 1, if not I, then I is n - 1, if it is not, see if I, if n - 1 is not, see if I, if n - 1 is not, see if I, if n - 1 is not, this is not n - 1, no. If yes then what this is not n - 1, no. If yes then what this is not n - 1, no. If yes then what should be its value and if yes then whatever is the value of t brother it should come in time so in this way one by five will also be equal to 2/5 will way one by five will also be equal to 2/5 will way one by five will also be equal to 2/5 will also be equal to and if the last one will also be equal then all three will be equal to By adding all three, whatever time is there will be returned in the time. Okay, and the same time which is given to us will be returned blank. It will be returned here at this place. Then what will we do with that time, we will compare that with the time that we are getting. So what is the time that we are passing, that we have this much speed, we are having this much time, then we will check whether the time that is passing is smaller or bigger than the time given by us, if the time is small, what does it mean that it is It is possible that it may be equal to ours, if so, then why has the speed been updated because our time is getting less, it means that the speed is more, so the speed has to be reduced and the speed is increasing day by day. If there are rights, then the speed is more on the right side, so if we have to reduce the speed, then we have made right minus one, okay, in this way the entire code will run and when you go here, when the time comes, when people finish, then you have whatever If you have to return the time then return the time. It's ok if you understand then many of your questions will be solved. Let's see after submitting. If we talk then look at the space, we have not taken any time. If you are wasting your time on the story then look. Wherever the time is going, it is going the same, as if you can understand that 10^7 time is the loop [ that 10^7 time is the loop [ that 10^7 time is the loop then it will be there, people 10 tu di power 7 i.e. if you take it, then lock it. Whatever it is you guys are running here, it is running every time and it is running for many times, so if there is a support lock of N* people then is running for many times, so if there is a support lock of N* people then is running for many times, so if there is a support lock of N* people then it will work.
|
Minimum Speed to Arrive on Time
|
minimum-speed-to-arrive-on-time
|
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
* For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark.
Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_.
Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**.
**Example 1:**
**Input:** dist = \[1,3,2\], hour = 6
**Output:** 1
**Explanation:** At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
**Example 2:**
**Input:** dist = \[1,3,2\], hour = 2.7
**Output:** 3
**Explanation:** At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
**Example 3:**
**Input:** dist = \[1,3,2\], hour = 1.9
**Output:** -1
**Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark.
**Constraints:**
* `n == dist.length`
* `1 <= n <= 105`
* `1 <= dist[i] <= 105`
* `1 <= hour <= 109`
* There will be at most two digits after the decimal point in `hour`.
| null | null |
Medium
| null |
901 |
Show More MP3 Video Song Hi Guys Saunf Ban Do List Question So what is the name of this question? The name of this question is Online Stocks Gain OK and in this we have one classes in that class the input will come price input will come to us this is its price Spain If there is a pan in Spain, then what do we do? Let us copy this question. I copied the example of the question from here. All in one note. Okay, there is a pan. Let me tell you first. What is this pan? Spain is great. So in this different is less than different prices so I am okay this info time we will create our class we will come in this different prices in food so the first one or 120 is ok then after directive comes sixty after that after ability Came 6575, then 8, so this is the different size of any A price. At this time, by instituting this day of Spain's over, that is, by commenting on this particular day, if we go back from this, then this price is how many prices is bigger than this one? Talking about hot soil, it's going out, if I grind it, then take one of the biggest because before Harold this big reality time that this integer is the tip of the king of Spain will be water. Okay, in this case, if I come to six. 6 And the consumption of the first element will always be plus and because there are no elements before that, well then if I give you six here then you will get six, that will give that the element before this is activated, it is bigger than this, that means this also has to be increased by something. So that means the scrub will be done then it will come from eight okay so now this center is this seven okay this is six big that if it increased from 2016 then it would have had the youth of one pan of all this OnePlus this big will be subscribed so good okay Then I will find this one sixty. If we find this one, then we will see that seventh is not bigger than any other. So this pen will be bigger than this. Then we will come to 7575. Interest you 275 is that when we are standing, one is on 75th and the remaining six are bigger. And then this one is 16th bigger, so how much bigger was the stake in it? Make your romance a festival bigger than 3rd, Tariq himself is 111 older, Fragnet 30, Amaze 676, Bigger-Bigger, this will increase it 12345, if you subscribe, then this is ours, why, what happened PAN What is a pipe chapter that is from Spain so what do we have to do now let us see a way to take out the pan so it's like you have the input first we have dry fruits done 1670 will come again it will get cooked then one more Make it, okay, make one deep inside your class and break it was dark under the stars, we put eggs in it, history, we put it, when I came sixty, we gave idlis, then we have to prepare it so that it makes us stand proud, or go back and see how many elements are there in this. It is big, okay, so basically it is six big and this small one of ATP has increased by one element, so whatever elements it has increased by plus one, send it, okay, now like here it was six, what is there after that, here seven five okay. It is bigger than Amazon, it is bigger than this, so it is increased by three elements and one yourself, you will answer it, 4 returns are one way, but what will happen in it, for each element, you may have to do N work in it for N years and N * and can may have to do N work in it for N years and N * and can may have to do N work in it for N years and N * and can mean. I have to work on every element, that is, Hina Khan, because whatever is complete, I may have to travel, just in case, and the element will go to its complexity and the square is fine, the complexity will be its length and if here then its If you look at the customs then the price of one call is ₹ 10. 5a is price of one call is ₹ 10. 5a is price of one call is ₹ 10. 5a is fine. ₹ 10 importance for 5th is fine. ₹ 10 importance for 5th is fine. ₹ 10 importance for 5th is ₹ 10 button. So this inch of our qawwali ₹ 10 button. So this inch of our qawwali ₹ 10 button. So this inch of our qawwali presentation will not work. It is ok, so now what approach should we use in it. So what should we do now? Will do basically you what do I need if I'm standing here 71st you I want that 727 next big element on which is the play list torch light latest trend Akshay 0 2345 6 sexual hatred so me that it means that which 727 next big element on there Place it, all the elements in between will be gone, when the seven key will come, this trick will be removed, like when the seven key will come, what will I have to do, pass job, my index is 70th, which is 3 - which is 3 - which is 3 - which means soil. The index of which is 7612, I will make it two to two, it will go to my 80 stocks, it is okay, if I talk about this discrimination, then it is more effective, it needs a big element acid, so if I come to know that it is Thursday - 01 I come to know that it is Thursday - 01 Wash face with Shiksha is 1234567 and on the other hand that is 6777 and myself together is three this is bigger than 306 youth ok so this is my way so now what do I have to do basically break the next crater element If I have to store the next greater element, then what will I do? I have to press one by one and take the input prasad. TV 6726 56001 Yes, then what will I do? Now as the elements come to me, I Let's create a class, its name is late, I am Answer Node A, ok, there are two things in this class, the first thing is pants data, whatever data, any price and index, what is its index, what will be these two things, so I will create a class in it. Okay, so now as soon as the hunter comes, my tab can take my ant, so I will create a new object, its answer is of no type and I will put it in that answer, I will put another answer mode is on, I will put the price which is and I would like to index at which number this element came, so now in the induction share index, I am here, this is my class, here I will make the index as my rate of pants and act and that will be my in a class tractor, so I will do indexes 0, ok, and I will show you by creating a class, why would A class go here, class laddu's name, answer note, it has these data and Intact Sir, ok, then I have created a constructor of the answer no type, these data and Induction stove, my country has become dot, data and strong start up has become my index, so this is one of my answer notes is ready, now what will I do, as my hand comes and I am the last example, then if I take it, I will make a new answer note. And then I will put in it with the index in which the answer has become Tamasha note insert type extend I will have to make a tag, okay this relationship has become one, so I have put it in the darkness and index it so that when the next element is So that on its own is the second ODI. Okay, now what will happen this time? This time there is no step in the soil, either it will activate the soil like acidity will come, we will see what is the topper of a tax, what is kept on the top of the tax, nurses are big i.e. Its on the top of the tax, nurses are big i.e. Its on the top of the tax, nurses are big i.e. Its pen is basically what is it? Its intestine sector-14 scan will get impatient, Its intestine sector-14 scan will get impatient, Its intestine sector-14 scan will get impatient, basically it will be made because it is kept on the tech top, Hunter's is fine, so now I will do something in it, if I get one fragrance 60 then it will be 100MB. Will give, have kept it like this, 31 big will not do anything, 6 Ma will push toe, ticket will come again in the step, 70% marks are interest, ticket will come again in the step, 70% marks are interest, ticket will come again in the step, 70% marks are interest, now as soon as you go, statement books will be churned on Sunday, that is a sure thing, but these six 70 is small, so now what will you have to do, you will have to take this situation out of the tax, okay, I have taken out the top till August after that, why ABT and mind, this 7080 is small, so further I will do it, so now My consumption of this will be answered for free minus one which is 270 what is our stock two as alleged the same is fine then it is 1667 smaller than the door so it will be asked like this after that 7575 will come interesting why are you at such hours Interest of 175 saw packet top 16 will be removed, 70% will come then if saw packet top 16 will be removed, 70% will come then if saw packet top 16 will be removed, 70% will come then if 180 can be removed then what will I do now joint access of 125 - tractor top 25 - will joint access of 125 - tractor top 25 - will joint access of 125 - tractor top 25 - will fly after becoming force so its spain is done our four fragnet inch is ok a diploma scan x6 So you will see that the smaller one will come and the youngest son will come and the bigger one will come then the answer to this will be 6 - 01 So I bigger one will come then the answer to this will be 6 - 01 So I bigger one will come then the answer to this will be 6 - 01 So I can find out with your help the next letter element Yes now he comes here from school Okay, now here If I come to Britain, then I take more than 100 in the track, the step is 100, why will it give the index, then now when this quarter inch comes, it will become active and this ne robot will come, okay, now the entry has been made in the tag, MTO gastric, so if my step is If you become MP, then how many stocks should you wear? There will be flame of gas, that means this hunter is the one who had increased the most in the city. Okay, if he had increased the most then how many elements will be there in it, till now there is consumption tax in it, so this meat will be of 7 Plus lineage i.e. talent which this meat will be of 7 Plus lineage i.e. talent which this meat will be of 7 Plus lineage i.e. talent which She will display including this, so whatever is the index in I plus one, my answer will go like this, it is okay, then this question explanation must be coded. If you do the court with 200 grams, then this note has become in the data index. He has fried them and become a constructor. Gone ok induction and in a cup here I make a tank what type of answer notification great saint and will do and the word tax make this make it editor make it clear a tax poetry is first people's name is bicycle then Are you cheating? Hey, why is it free? Well, okay, in school, as long as it's done, I will use the target here inside this constructor, now like the effect, I will see if there is a secret in Meghnagar, so I don't have to do anything, just in one take. I will do pushya what will I do new a answer node and its value is price and its inductance index plus app that if it is not so then how will I do wild tag dot size that is not equal to zero that and take dot pick developed sectors top But the thing is placed, if what is it smaller than what price, keep a text opportunities, if it is very small than price, then I will pop it, I will do this thing, we have to do something in the attack, which is our element, so What we will do here is that price comma and The exception is that my element and the biggest one have been removed from it and the entire stock has been emptied, then what will I do, my answer will go here. If we take the end answer here, then my answer will be. The thought index is plus one, okay. If my take is not anti then my answer will be my current index - the index - the index - the top index of the tag Stock. I will give my answer. If the torch light is on, then he sees that there is a compilation and there is a leg. He is saying that a tiger pick is coming into function due to the coming of good data. There is a function and there is nothing green after surrender. It is a mixing written statement. Abusing my brother was our anti, so we wrote bad stop that run code is there and wrong answer is coming, why is it that run cold is a pan, then there will be less Dainik World here, these two prices are ours, so now we have to crop. Okay, so let's submit it and see if it is complete, it is 98066 and it should be dry and you all have understood the solution and he must have also understood and it is not that I have deactivated it, so all of you. It is necessary to play it once and see that I am busy, at least it gets accepted, so I look ahead once, but this one is Ko Dobra Live, there is no left voice, so we will give you the solution of your choice. And both the codes and if you are not able to understand at any point then basically comment on the cover of Instagram and ask your first question from this, I answer everyone, till then take care bye by Nakul Patlu
|
Online Stock Span
|
advantage-shuffle
|
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`.
| null |
Array,Greedy,Sorting
|
Medium
| null |
1,367 |
hi today i'm talking about lead code problem 1367 linked list in a binary tree so what this problem asks you to do it says you're going to be given a binary tree called root and a linked list called the head and what they want you to do is return true if all of the elements in your linked list occur in a downward path of the binary tree so here you're given a linked list with the elements four two eight and you should return true because there is a downward path of your binary tree with those elements four two eight and so it doesn't need to be the first elements in your binary tree this sequence just needs to occur somewhere within a downward pass and the constraints it says i don't know the constraints don't seem that important that the value on the node is going to be between 1 and 100 you know who cares um and that there will be up to 2500 nodes i suppose that is a bit more important for testing scalability when i was working on this problem though i actually found it hard to just create the linked lists and binary trees you know it's a bit cumbersome to create those in order to get some test cases to work with so i wound up just taking the best effort and then submitting it to see if i solved it or not so the solution i wound up with is a recursive solution and it starts with this function here the is subpath and here i take this function to be essentially solving the problem given by the problem statement so it's saying from this tree node or from this binary tree are any of the descendants or this node itself the path described in list node and so here i have two kind of base cases one would be that there are no values left so our linked list has been entirely exhausted and so it's just an empty set in which case that were true um yeah this is a sub bath like there's an empty sub bath here or anything is an empty sub path and the other possibility is that node meaning the binary tree node that i'm currently at or the binary tree node is none and if that's the case if the binary tree know tree node is none and we still have values because we didn't hit this condition so we still have some values left we know for sure that we aren't going to complete our values list um in a downward path if we're already adding a none so those are the two base cases and then the recursive case basically has three branches so i'll talk about this first branch in a second but the other two branches are really just saying okay let's do the ibs is sub bath of my left child and my right child so i asked is the root a sub pass maybe it is maybe it isn't um and then either way is my left child the sub path is my right child sub path and so you can see how that logic will continue on you know it'll try the left it'll try left and right child of the root node so here it's trying the left child it's going to dry the left and right child here when it dries the left child it's going to hit this condition that my node is none and it's just going to return false and then here it's going to check if this is a sub path and so on i'll explain more about that when i talk about this primary recursive case which is a similar function sub path which is just going to say is the node i'm currently at does that map out this values list so just the difference between subpath this function and is subpath is saying does any descendant have the path whereas subpath is just saying do you have the path um so the entire thing here says um does the current node online does that have the path described by the values list or does my right hand child or does my left hand child i said that backwards or it is my left hand child or it is my right hand child and so to do this subpath function we again have the same two base cases um if the values list is none then true if the node is none then false and otherwise we say okay if the value if the top value in my linked list is not equal to the value in my node then i'm going to return out false and otherwise i'm going to recursively call or i'm going to return the recursive case which is the next value and the left-hand side of the linked list left-hand side of the linked list left-hand side of the linked list or the next value and the right-hand or the next value and the right-hand or the next value and the right-hand side of the linked list so let me um let me try to just illustrate that real quick so like here we have one for i guess they don't really need to be in circles seven and we'll just say two um and say we're looking for a linked list that is four and two so we start with our root here and we say okay this is not null and so we can check it for its value this is not null and the list we're checking for isn't null so okay we can check it for the value no these two don't match okay so we're going to return the or of sub path of your left child and sub path of your right child so right we won't explore but you know as a spoiler it doesn't work out so the or would be left path or false or right path when we explore the left hand child you know we pick up a node this isn't null so our sub path function would say okay did these two match they do okay so what we're going to return when these two match is the or of the sub-path is the or of the sub-path is the or of the sub-path of the left-hand side and the right-hand of the left-hand side and the right-hand of the left-hand side and the right-hand side with our linked list values dot so we'll just dot so we'll just dot so we'll just explore the sub path of the left hand side which will work out and succeed and return true up our recursive chain or the right hand side which would return false and so because all of these recursive calls are just ored together that's how it works that if any one of them succeeds then if any one of them hits a true condition then the entire statement will evaluate to true um and yeah that'll get us to our solution uh recursively uh it's not super fast actually when i looked at the other solutions it's highly similar to at least other solutions i saw in the discussion section i think most people solve this recursively there's just something about a binary tree that kind of calls out for a recursive solution it's at least easy to do that way but yep this is the solution to leak code problem let's see what is it one three six seven um yeah i'm gonna try to keep solving the leak good problem a day or something like that and when i do solve them i'll just record a quick video to discuss my solution so if you're interested in that subscribe click the like button thanks for your time
|
Linked List in Binary Tree
|
maximum-height-by-stacking-cuboids
|
Given a binary tree `root` and a linked list with `head` as the first node.
Return True if all the elements in the linked list starting from the `head` correspond to some _downward path_ connected in the binary tree otherwise return False.
In this context downward path means a path that starts at some node and goes downwards.
**Example 1:**
**Input:** head = \[4,2,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** true
**Explanation:** Nodes in blue form a subpath in the binary Tree.
**Example 2:**
**Input:** head = \[1,4,2,6\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** true
**Example 3:**
**Input:** head = \[1,4,2,6,8\], root = \[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3\]
**Output:** false
**Explanation:** There is no path in the binary tree that contains all the elements of the linked list from `head`.
**Constraints:**
* The number of nodes in the tree will be in the range `[1, 2500]`.
* The number of nodes in the list will be in the range `[1, 100]`.
* `1 <= Node.val <= 100` for each node in the linked list and binary tree.
|
Does the dynamic programming sound like the right algorithm after sorting? Let's say box1 can be placed on top of box2. No matter what orientation box2 is in, we can rotate box1 so that it can be placed on top. Why don't we orient everything such that height is the biggest?
|
Array,Dynamic Programming,Sorting
|
Hard
|
2123
|
1,437 |
Shocked by the longest Udayveer Gondi song this question of click and this depth all once and at least length ke debit the question thought it right to take it a little higher so here I click is ok and it has 90 ok now whatever must have gone in between the two Will happen or ca n't grow again then okay this is this see the Sangh has said that there should be butt minimum between these two okay then fast it so I have already got ready in the Raghavan function regarding basic education The Giver One name is okay, it means that this is a domestic rally, so now we have claimed that what will we do, not that we will keep the position of Vansh in any other place, then today you have various to keep the position. You can use this data structure, so we use Victor here, that Victor is different, we have to set one clock first, where is it, so for that, we do not need the name Joe or this Joe Victor. We will have to reverse it completely one butt and the name of the end Begusarai Jung is start size, it means it will last till its size and the oil space will keep increasing. There will be a condition inside, the training condition is that if the name is clear, it should be 2221. Okay, if Governing Agarwal is done, then we will ask him about it, but we have to pause him, his position has to be made happy, okay, we have made him happy by worshiping him, okay, so as it is beyond this point, then we have confirmed it to life. What position did you do? Okay, now we have to check between them. How to check the fate among them? Simple sir, this is that we will mix the entire personality once. Okay, but where were we to reverse? If we here you can do something. So if we write zero then there will be a slight mistake, this is the program, if we explain it because okay, it will continue till Veer and size, here it will increase, it will automatically increase and here how to calculate the difference, so it is basic, okay, it will be different. Business - Position The meaning of the previous one is - Business - Position The meaning of the previous one is - Business - Position The meaning of the previous one is - one and in between the two, SAARC needs minus one. Okay, so now look, if we had started Life is, it would have been here or Bigg Boss should have come to minus one, meaning it would have been here. Going minus one was different - one to here. Going minus one was different - one to here. Going minus one was different - one to tweet - if the bun is messed up then here the tweet - if the bun is messed up then here the tweet - if the bun is messed up then here the calculation is different in America, that is a little problem, then it is fine in the chord, then it is a basic one, we will put this statement, if it is less than k, then just return. The gift will be that, this is the recipe, the return gift will go, okay, and if it comes out of Kalyug, then it will return to end, okay, it would have been simple, we would have done the school quickly, I have already made a brush ladies so that in no time If the code is money, then G plus, I have to fold here, Hello don't say is also okay, I will make it medium, it is okay to fail completely, I am passing, Jhaal, check umpire Suhail, okay, now we will type this and then. Then it will automatically reverse. I will see it tomorrow. I will see it means it is done, it is okay, it means this is the first customer, okay, he picks up the phone, I just feel like it is done, let's copy the photo and pass it on, Aadhya. I turn it over to ISKCON, let's set it, okay, only sister, you had it so that Qawwali is two, okay and keep one verification at the bottom, it will take some time in these companies, now let's type one by one that we need the meaning at the head. Okay and this is our basic teacher and it is fine, there was not much add, it had to take a little time, which is the concept that whatever position of boys is called crystal, you will have to do it, okay, so you can copy and paste this code and run it. If you can, then it's okay to like and share the thank you video and subscribe to the channel.
|
Check If All 1's Are at Least Length K Places Away
|
minimum-insertion-steps-to-make-a-string-palindrome
|
Given an binary array `nums` and an integer `k`, return `true` _if all_ `1`_'s are at least_ `k` _places away from each other, otherwise return_ `false`.
**Example 1:**
**Input:** nums = \[1,0,0,0,1,0,0,1\], k = 2
**Output:** true
**Explanation:** Each of the 1s are at least 2 places away from each other.
**Example 2:**
**Input:** nums = \[1,0,0,1,0,1\], k = 2
**Output:** false
**Explanation:** The second 1 and third 1 are only one apart from each other.
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= k <= nums.length`
* `nums[i]` is `0` or `1`
|
Is dynamic programming suitable for this problem ? If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need n - x insertions to make the remaining characters also palindrome.
|
String,Dynamic Programming
|
Hard
|
1356
|
649 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem Dota 2 Senate which is an absolute essay of a problem I've never actually played this video game so let's go through this real quick because this is a really good question to use as an example for me to show you how you can take like a pretty complicated question like this one and really break it down because sometimes that is the point of an interview to see how your skills can take like high level requirements like this which I guess aren't really high level but these are like problem requirements and they're not exactly spelled out for you in like the easiest to understand way in my opinion like this sentence over here I had to read it like 10 times for me to understand if this Senator found the Senators who still have rights to vote are all from the same party he can announce the Victor and decide on the change in the game well I think the easiest thing to do is actually to start with the example so let's see what we're actually working with here we're only given a single input string here and what we're trying to do is return turn the party that is going to win I guess some kind of election or something like that who cares what exactly it is let's not distract ourselves with those details that are pretty irrelevant to our problem or at least our solution and in this problem we have some R's and Some D's I guess they stand for radiant and dire who cares I don't as far as I know we have some R's and D's and we have an input string that is going to be r d at least in this example but we could have some others maybe r d or DDR or you know something really long now it's not quite as easy as just counting the number of R's and D's that would probably happen in like a normal election where here we have 3DS and here we have two r's so D's would win unfortunately it's not quite that simple here so what are the rules well they are a bit complicated at least the way it's phrased here but basically we're going to iterate through this from left to right that's very important they mention that over here which they again they don't really tell you we're starting at the beginning of the string ring they tell you here the round based procedure starts from the first Senator to the last senator in the given order that's a fancy way of saying start at the beginning of the string and move to the right but to make it even more complicated actually we are actually going to not just iterate once necessarily we can actually loop around when we're talking about voting I'll talk about that in a second but these votes are not traditional votes so this is the senator that's first going to vote what do they do are they voting for their party no actually what they're doing here is saying that this person is allowed to remove one of these D's any of them since this guy gets to go first let's just remove this one this R gets to do the same thing remove ad well I'm just going to remove this one this D gets to do the same thing remove some R I guess I'll just remove this one so now we are left with an r and a d so here are we done does it end in a tie no actually the game keeps going here we were looping through this from left to right now we still have some character so here is the part where we loop around and go back to the beginning we're back to R this guy gets to make another move and guess what all they can do is remove a d where's the D it's right over here that's what she said uh but we can go ahead and remove that and at this point clearly there are not any choices left so for R we would just go ahead and return radiant that's kind of the only part of this problem where you actually need to know what the string is the r stands for radiant the d stands for dire so after that this seems really simple it seems pretty deterministic there's usually just going to be a single solution right we're just going to take every R and just remove a d or something or maybe skip like a future D and do the same thing for every other D well first of all it's not quite that simple there actually is a greedy approach I'll try to explain the intuition really quickly for that whenever we do happen to have a choice for example let's just make this string a little bit longer the idea is that if this R gets to choose a d that we can remove does it matter if we choose this one or if we choose this one and it kind of does we probably want to choose the one that's closest to this R intuitively we'd want to do that because we know we're going from left to right this guy is going to get a move before this guy so when we have a choice with this R to remove either this D or this D we should probably take this one because this one is going to be harder to remove remember to remove a character we need something to the left of it to actually remove those well technically we can loop around but who knows we might not get another chance there might not be another R over here to ever remove this D this guy was our only chance and now we don't have one and this D is going to still remain then and then this D is going to end up removing this R and what they end up telling us is that let's assume that each Senator is going to play this optimally so assuming that they play as best as possible which like this D is supposed to remove the one closest to it this guy is going to remove the one closest to it so that this guy actually will not get the chance to ever remove an R so that's kind of the intuition here of why we want to remove sort of the nearest neighbor uh by that I mean like the for R we want to remove the nearest D that comes next okay so that doesn't seem so bad how would we go ahead and code a solution like that up well going character by character if we find an R we want to remove the next D character and just continue this character by character now when we say remove how do we handle that removal because we probably don't want to have to actually remove it that's going to be an O of n operation we can probably lazy delete it basically we could just have like a variable counting the number of like previous R's or something like that then when we come up to a d maybe we could just skip that one at least at a high level you can kind of get a picture of how you could solve this by it like keeping counts of R's and D's and having an array instead of just using a string because string operations are almost always Big O of n converting this to an array will actually make the most of those operations o of one except for the removals so we will have to keep track of that the last thing is how do we kind of keep track of this D being able to loop around because that's going to be really painful and if we just keep going in circles and we don't really remove these values then you know if we have to keep going through the entire array so many times we might end up having like an exponential algorithm so can we do better than that and yes we can so how do we usually handle removals in O of one time from an array well usually when we remove from the end of it right using a stack so maybe we can get some intuition that a stack will help us and I know an even better data structure where you can actually also remove from the beginning in O of one so maybe a q as well here will help us so knowing that let's go ahead and try a cue just because it's more flexible than a stack but we want to handle the removals how do we remove from a queue either from the beginning or the end where we can handle the voting here like when we go from this R over here I guess we add it to the queue and do the same thing for the next R over here and now let's get to the D well this D we don't want to add it to the queue so what do we do at this point should we just skip it maybe we can just check the top of the queue or the end of the queue and if we see an R we can use that to remove the D well that wouldn't work because if there's a d over here and now we're trying to add another D we're going to see a d here and think that we don't need to remove this but if there were some previous R's over here yeah we actually do need to remove it so can't just look at the top of the queue and maybe mixing and matching these R's and D's isn't helpful for us because clearly the relative order of them matter a lot and this is where you might get the intuition for two cues or you might not and that's perfectly fine because you may have never seen this solution before it's pretty rare I think the two stacks variation is more common but here we have two cues you can guess one is going to be for the RS one is going to be for the D's clearly the relative order of the matter let's keep track of the indexes zero one two three so let's try this again here we're actually going to add zero to the cube we know that there was a r at index 0. next one let's add one to the Q next D two let's add two to the other Q we have another q now for D's and a different Q for R's now we have R let's add two to the Q here or not two actually three and lastly let's add four to the other Q over here so these are the D's these are the R's and now to actually do the simulation let's start at the beginning of both of these cues now that we've kind of separated the R's and the D's starting at the beginning of the R's and the beginning of the D's let's look at the first value and actually pop both of them we're going to pop the zero and the two and at this point we kind of know what we should do we kind of know the rules here since R is before the d r is at index 0 D is at index two so clearly the r is going to be able to remove this D this is the first D that shows up we know for sure because we're starting at the beginning of the DQ and that's exactly what we were trying to do now here is a tricky part well first of all we know that the D is going to be removed so here I'm just going to cross out the D and we actually also popped the zero so I'm going to remove that as well but are we going to take that zero and then push it again to the end or maybe the beginning what are we gonna do here well one thing I want to remind you is that this D can possibly remove the beginning right we can loop around but we haven't really accounted for that in our cues like when we look at these two values three and four we're definitely not going to say this can remove any possible R's because they're all to the left so that's where this kind of comes in where after we pop that we have visited it we know it's going to still remain in the queue but we want them a value to be modified and also the position so it makes sense to pop this and then just append it to the end and the new value that we're going to give it is going to be the original index plus n we're adding this offset of n because we want to add the length so that any value in the array can then loop around and actually not just loop around once but loop around multiple times so here if we added that four we might you know pop that for and then make it into an eight at some point because we're going to keep looping but that doesn't necessarily mean we're iterating through the array multiple times remember we're only visiting each of these values from the Queue at most once whether we're pushing or popping it's always going to be a constant time operation and we're going to do it roughly Big O of n times we haven't really gone through this entire example but I've pretty much touched on all the points that I wanted to I do encourage you to walk through the rest of this I'll go through a couple more we're gonna pop from the left both of these one and four which one is smaller one so that's the one we're gonna pop but also re-push we're gonna add that offset of n re-push we're gonna add that offset of n re-push we're gonna add that offset of n which is the length here which is five which makes me realize that this value here should have been a five so I'm really sorry about that but also this value that we just popped was one plus an offset of five that gives us a six over here but this four over here was actually removed and now we end up at the end of our solution how do you know when to stop well here one of the cues is empty that means there's only ours remaining that means the r's are going to win and from this example that does make sense I think what would happen is this R removes this and then we're done I will admit though this solution is definitely not easy to come up so don't beat yourself up about it if you weren't able to solve it yourself now let's go ahead and try to code it up so the first thing I'm going to do is actually convert the input string into a list usually operations on strings are expensive because strings are immutable but lists are immutable like we can change this in O of one I'm also going to create two cues that are going to be poorly named D and R for the DQ and the RQ which is going to be a bit funky to keep saying those because this is DQ and this is what I'm also going to reference has the DQ but going now to the Senate list we're going to iterate through it getting the index and the character we can do that using enumerate in Python and using that character all we need to check is whether it's an r or a d and then we can add the index of it to the respective queue for so for this one we add it to the RQ and this one we add it to the DQ so now we did the initialization where we set up our cues now to actually run the simulation we're going to continue knew while both cues are non-empty because as soon as one of are non-empty because as soon as one of are non-empty because as soon as one of the cues is empty we know we can stop and actually once we know that one of the cues is empty we can return either radiant or dire and we can return radiant if R is not empty we know one of these cues is going to be empty we have to figure out which one if R is empty or rather if it's non-empty then we return rather if it's non-empty then we return rather if it's non-empty then we return radiant if dire is or rather just really the else case then we return dire so whichever Q is non-empty that's the one whichever Q is non-empty that's the one whichever Q is non-empty that's the one we're going to return well the string we're going to return the string we're not returning the Q okay but now for the simulation we pop from both cues so D turn what was that well we'll get it from the Q D dot op left and R turn r dot hop left and our question is which one of these is smaller is D turn smaller if it is we don't have to pop from the cube because we already really did that what we have to do if R is smaller is ADD its value back to the queue but all the way to the right and make sure to add the offset which is the length of the Senate and then we can do a very similar thing in the else case where D has a smaller value so we'll append to the DQ and we will append our turn to the DQ with the offset and then I think we are pretty much done here not a lot of code but definitely not a simple solution to come up with even if you know you're supposed to use a queue this still isn't easy in my opinion but let's go ahead and run it to make sure that it works and as you can see yes it does it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io it has interviews check out neatcode.io it has interviews check out neatcode.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
|
Dota2 Senate
|
dota2-senate
|
In the world of Dota2, there are two parties: the Radiant and the Dire.
The Dota2 senate consists of senators coming from two parties. Now the Senate wants to decide on a change in the Dota2 game. The voting for this change is a round-based procedure. In each round, each senator can exercise **one** of the two rights:
* **Ban one senator's right:** A senator can make another senator lose all his rights in this and all the following rounds.
* **Announce the victory:** If this senator found the senators who still have rights to vote are all from the same party, he can announce the victory and decide on the change in the game.
Given a string `senate` representing each senator's party belonging. The character `'R'` and `'D'` represent the Radiant party and the Dire party. Then if there are `n` senators, the size of the given string will be `n`.
The round-based procedure starts from the first senator to the last senator in the given order. This procedure will last until the end of voting. All the senators who have lost their rights will be skipped during the procedure.
Suppose every senator is smart enough and will play the best strategy for his own party. Predict which party will finally announce the victory and change the Dota2 game. The output should be `"Radiant "` or `"Dire "`.
**Example 1:**
**Input:** senate = "RD "
**Output:** "Radiant "
**Explanation:**
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And in round 2, the first senator can just announce the victory since he is the only guy in the senate who can vote.
**Example 2:**
**Input:** senate = "RDD "
**Output:** "Dire "
**Explanation:**
The first senator comes from Radiant and he can just ban the next senator's right in round 1.
And the second senator can't exercise any rights anymore since his right has been banned.
And the third senator comes from Dire and he can ban the first senator's right in round 1.
And in round 2, the third senator can just announce the victory since he is the only guy in the senate who can vote.
**Constraints:**
* `n == senate.length`
* `1 <= n <= 104`
* `senate[i]` is either `'R'` or `'D'`.
| null |
String,Greedy,Queue
|
Medium
|
495
|
1,647 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem minimum deletions to make character frequencies unique so in this case the problem title is pretty self-explanatory we're given a is pretty self-explanatory we're given a is pretty self-explanatory we're given a string s it's considered good if no two characters in The String have the same frequency by frequency they mean count so in a string like a b the frequency of the character a is to the frequency of the character B is one and they keep it simple for us we're only allowed to delete characters so from this input string we're allowed to delete literally any of the characters now we don't care about like the resulting string after we delete some characters the problem is actually more simple than that we care about the counts so if we delete an a then the count of a is going to be one doesn't matter if we delete this one or if we delete this one so that's something important to notice it's not super complicated but that's kind of like the Crux of the problem a couple more observations we can make well I guess before that let's actually understand what we're trying to do and that is calculate the minimum number of deletions that we have to do so that none of the characters have the same count just like the problem title says now in this string neither A or B have the same count so actually it's already good what's the result in that case well zero we return zero there's zero deletions that were needed what about a string like this one suppose we have a b and c so problem here is that a has a count of three B has a count of three and C has a count of two now one hundred percent we will have to delete a character from this or from this like that's guaranteed there's no way we're going to be able to make one of these counts different unless we delete from here or we delete from here now my question is does it really matter which one we delete from it really doesn't because all we're trying to do is make the counts unique we don't care whether we delete an A or whether we delete a b so that's probably the most important observation in this problem it doesn't matter which character we delete as long as we're deleting from one of the piles of characters that we have to delete from like in this case we have to delete from one of these so I'm just going to pick a arbitrarily like we know for sure we had to do that we had to decrement the count of this down to two but did that really help because now this has a count of two and this also has a count of two so actually it did not help us so now what do we do well once again we know 100 certainty we have to delete a character from one of these two piles once again it really doesn't matter which one we delete from so I'm just going to choose the a again so now the count of a is one the count of this is three and the count of this is two it took us two deletions and that's also the result for this problem so actually this problem is not too bad what I've done I haven't told you the algorithm but just from kind of the visual explanation you might be able to guess what we're going to do when we code this up one we're going to count the frequency of every character they're not necessarily going to be adjacent like the B's are not necessarily going to be grouped together but counting the frequency of characters is not super difficult to do now after we do that we're going to do kind of what I was drawing out we're going to for every single character and I think we're limited to 26 lowercase A through Z characters but we're going to go through every character that we have a frequency for we're going to look at that character and check is there another character that we've already seen with the same frequency if there is then we better decrement this and not only decrement it a single time like we kind of showed earlier we might have to actually decrement this multiple times so we're going to keep decrementing it until the count is no longer unique and then we're going to record that we're going to say okay we took a lowercase a and mapped it to account of one now we could have taken another character and mapped it to one but it doesn't really matter so in this case C will be mapped to two B will be mapped to three now if we saw another character for example like D or something it has a count that conflicts with one of these three we're gonna keep decrementing this until it no longer conflicts with the others and there's one last Edge case if you're clever you might think of it I actually didn't so I failed my first submission but it's actually the third example that they show you let me show it to you so sometimes it is helpful to read the fine print in this example they actually deleted a character C until there were zero occurrences of that character and that's perfectly valid so you might think what if we get to a point where it's actually impossible to delete characters until there are unique frequencies for every single one like for example if we're given a string a b c d how do you make it so just by leading some of these that the frequency of each one is unique like are we allowed to set the frequency of a to zero and then also set the frequency of B to zero is that allowed does that not violate the initial condition well technically this is allowed I guess based on like the description here that's something we also have to account for if the frequency ever becomes zero then it doesn't really matter if there's a conflict okay with all that said now let's code it up I think it's pretty self-explanatory though that this self-explanatory though that this self-explanatory though that this algorithm is going to be Big O of n because we're just going to iterate through every character in the input string we might have to do it twice but still that is linear time and in terms of memory it's also going to be Big O of n because we're going to map every single character to its frequency I guess technically it's going to be o of one because I think we're guaranteed that there's only going to be up to 26 unique characters in the input so I guess that is worth mentioning but now let's code it up so the first thing I'm going to do is create a hash map and I'm actually gonna make it a default dictionary in Python which means the default value is going to be an integer and what that allows us to do is now we can go through every character in the input string and map the count or rather just increment the count by one now you might be thinking what if this character does not already exist in the hash map we'll get a key error like the key does not exist well that's what a default dict is for if the key does not exist the default value will be an integer which is zero and that's what we would want for the initial count anyway so this works out pretty nicely though we could have if we weren't using a default deck we could have like an extra if statement here and also if you really just want to be like a smart ass you can actually use a collections counter in Python passing in the input string s and that will actually do this by default for you we don't even have to write that code sometimes I feel like this is cheating but I guess your interviewer is the ultimate judge so I would just ask them like are you fine with me doing it this way or you actually want to write out the extra like for Loop and if statement or whatever once we've gotten the count now it's also important to remember this is still Big O of n time and space it's creating an extra data structure it still has to iterate over the string s but after we're done with that now we're going to go through every character frequency pair in our count dictionary or hash map and to do that we actually have to get the count dot items and as we do that we know that ultimately what we want to do is record the frequency of this character and making sure it's Unique so I'm actually going to create a separate set a hash set called used frequencies and here we're going to record all of the used frequencies we don't even need to record which character maps to that frequency that is irrelevant in terms of the result we just have to count the number of deletions so I'm going to have a result variable to make that count so here we know ultim ultimately what we want to do is say in our used frequencies we want to add the current frequency of the current character but before we can do this we have to make sure that either this frequency is unique so I'll leave a comment frequency is either unique or it's equal to zero we know that zero just by default is considered unique or maybe that's bad wording but basically zeros don't have to be unique well we can do that pretty easily here we can say while the frequency is already in the hash set meaning we've already used this frequency before maybe the frequency is three well what do we have to take that frequency and decrement it by one so and essentially we're deleting one of these characters now if we do a deletion we should probably increment our result by one and then after we're done with that we can add it to the frequency hash set now here's the bug remember it can also be zero it doesn't necessarily really have to be unique so try to fix this bug in your head if you can but I'll just go ahead and tell you that we also have to check that the frequency is greater than zero and this is the case because maybe we've already used the frequency of zero but if it's zero that's okay we can immediately break out of the loop we don't have to do any deletions anymore and we can go ahead and add that here and after we're done with that we're going to go ahead and actually return the count just like this so now let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io thanks for watching and out neatcode.io thanks for watching and out neatcode.io thanks for watching and I'll see you soon
|
Minimum Deletions to Make Character Frequencies Unique
|
can-convert-string-in-k-moves
|
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.
**Example 1:**
**Input:** s = "aab "
**Output:** 0
**Explanation:** `s` is already good.
**Example 2:**
**Input:** s = "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ".
**Example 3:**
**Input:** s = "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters.
|
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
|
Hash Table,String
|
Medium
| null |
252 |
hi guys this is nikash here as i promised i have started making the lead code solutions and other interview preparation videos again and before digging into today's lead code problems i just want to remind you that i have started a page by name techytux i have started a facebook and instagram page by name techytux so please do like and follow this page and if you want to connect with me you can easily connect by sending just a message here so you can send me a message or email as well i'm pretty responsive here and all my lead code solution videos are in our interview preparation videos will be going to this page now right so but yeah do like and follow this page so that you get uh regular updates regarding all the interview preparation videos and as i said if you want to connect with me and if you need help with preparing your for your interviews do bring me via this page and i'll respond you as soon as possible so yeah let's dig into today's problem so today we'll be going through an easy level problem so it's a frequently asked in facebook interviews if you can see here it's asked in facebook amazon and karat okay so yeah the problem statement is something like this given an array of meeting time intervals where intervals i is equal to start time and an end time determine if a person could attend all meetings right so there are a couple of examples which we can go over and see how we can solve this and what's the intuition behind our solution right so let's go over the examples and see what exactly the problem is so if you can see here we have been given three intervals zero comma thirty five comma ten and fifteen comma twenty okay so let's say the okay let's uh draw this into a pictorial representation so what i can do is so this one let me draw a graph so let's say 0 5 10 15 20 25 and you have 30 yet so 0 5 10 15 20 25 and 30. okay so if you mark these meetings right so the first meeting start time is 0 and n time is 30. the first meeting starts from year to year so basically the room is occupied for the start time 0 and it goes for 30 minutes okay the second meeting starts from 5 and goes till 10 okay and the third meeting starts from 15 and goes till 20 right so if you can see if the meeting one is so let's say you are an engineer who goes to the meeting one right and then you're starting from zero and you're coming out only after 30 minutes but other two meetings have already been started which you will not be able to attend so in this case our returns would be false right so let's go over the second example so yeah the first interval is 7 comma 10 right so someone will start somewhere here and he'll go till here this is 7 and this is 10 right and the second is two comma four so he'll start here and here so basically he'll start at two and end at four and then he'll come out of the meeting after three minutes he'll go and go into the second meeting so in this case he's able to attend both the meetings so how do you come up with a solution for this so if you can see here so first we mark the second meeting and then we came back and marked the first meeting so what do you get to know by this so if you are an engineer you will always attend the meeting which is first let's say at nine o'clock then you'll attend the meeting second which is at seven o'clock right so basically even if the given input is not sorted the first thing what you need to do is sort right software start type okay second so always how do you determine if you are able to attend the next meeting if your current meeting ends before the start of the second meeting so basically start so end of i minus 1 if it is less than start of i right in this case you are able to go ahead and attain the next meeting which is i meeting so yeah ever if you encountered a scenario where you are not able to satisfy this condition you come out of the loop and say that yeah you are not able to attend all the meetings so this is a quick solution and let me go ahead and write the code for this so if you have any comments or concerns do let me know on the comment section below or you can pick me up take a text page as well yeah let's go and write the code now so yeah that's how you solve the problem or how you come solution for that so i'll be putting a next video link in the description below where i'll be coding the solution for this problem hnc plus and it'll be a pretty quick solution for this so please do watch that as well and let me know if you have any concerns or questions yep as i always say keep learning every day thank you bye
|
Meeting Rooms
|
meeting-rooms
|
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106`
| null |
Array,Sorting
|
Easy
|
56,253
|
1,629 |
hello friends in this video we will solve lead code problem number 1629 slowest key so the question says that we have given string keys pressed of length and pressed i represents the i iaf key pressed in the testing sequence and the show test list release time array we have given where release time is ith key was released at that time so we need to find the key of key press that have longest duration if there are multiple key pressed written the lexigraphical largest key of the key pressed means we need to return largest character from that string which have maximum difference between their time let's understand this question with example so this is example one we have this release time and key pressed as the string so first we need to find difference between all the release times so from this we have 29 minus 9 20 from this we have 49 minus 29 20 after that we have this 50 minus 49 it will be 1 so for 9 we have c for 20 we have b for this 20 we have c and for this one we have d then from this 20 is maximum from this all but we have two 20s it means we need one largest value and it should be lexiographical largest so here legiographical means in dictionary order so if we have a and b so a is smallest character and b is the largest character we need to find largest character lexiographical so in this case we have b and c as 20 so lexigraphical from b and c is largest is c and b is smallest so we will return c as the answer here we can see our output is c let's understand the approach for this problem so here we need to find difference between each time interval so this is our time interval so we will use postfix approach to find this time intervals difference so from this we will use postfix so it will be 50 minus 49 it will be 1 49 minus 29 it will be 20 29 minus 9 it will be 20 and for 9 we don't have previous value then it will be 9 so this will be mapped to this string so it will be 9 20 and 1 we will check which have largest value according to the character so b and c have largest value which is 20 so we will find this both of these we will find which have highest ascii value so from both of this we see here largest ascii value then we will return this as the answer now let's see the time and space complexity for this solution time complexity will be off and because we are iterating through the array for precalculation after that titrating through the array and finding the maximum ascii value and space complexity will be one let understand the solution for this problem so here i am finding the postfix to find the release time between the two characters after that here i am initializing the minimum as release time index 0 and here i am converting character into ascii value so we can find out lexiographical largest value and here i am storing answer as the character here i am iterating through the each character and finding the lexiographical largest character so for each character i am storing the release times difference into the tap variable and converting each character into the new ascii value after that i am checking if our minimum value is smaller than the current character release time then we are assigning minimum value to the maximum amp value and after that assigning ascii value into it and character into the answer we have same difference like we have seen in b and c we have 2020 time we need to find maximum one from both of that so we are checking if new ascii value is greater than the previous one then we are assigning previous ascii 1 value means b value overwriting it with c value and overriding here answer value with the c value so at the end i am returning the answer thank you for watching my video please like and subscribe to my channel because it motivates me to create more videos
|
Slowest Key
|
minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits
|
A newly designed keypad was tested, where a tester pressed a sequence of `n` keys, one at a time.
You are given a string `keysPressed` of length `n`, where `keysPressed[i]` was the `ith` key pressed in the testing sequence, and a sorted list `releaseTimes`, where `releaseTimes[i]` was the time the `ith` key was released. Both arrays are **0-indexed**. The `0th` key was pressed at the time `0`, and every subsequent key was pressed at the **exact** time the previous key was released.
The tester wants to know the key of the keypress that had the **longest duration**. The `ith` keypress had a **duration** of `releaseTimes[i] - releaseTimes[i - 1]`, and the `0th` keypress had a duration of `releaseTimes[0]`.
Note that the same key could have been pressed multiple times during the test, and these multiple presses of the same key **may not** have had the same **duration**.
_Return the key of the keypress that had the **longest duration**. If there are multiple such keypresses, return the lexicographically largest key of the keypresses._
**Example 1:**
**Input:** releaseTimes = \[9,29,49,50\], keysPressed = "cbcd "
**Output:** "c "
**Explanation:** The keypresses were as follows:
Keypress for 'c' had a duration of 9 (pressed at time 0 and released at time 9).
Keypress for 'b' had a duration of 29 - 9 = 20 (pressed at time 9 right after the release of the previous character and released at time 29).
Keypress for 'c' had a duration of 49 - 29 = 20 (pressed at time 29 right after the release of the previous character and released at time 49).
Keypress for 'd' had a duration of 50 - 49 = 1 (pressed at time 49 right after the release of the previous character and released at time 50).
The longest of these was the keypress for 'b' and the second keypress for 'c', both with duration 20.
'c' is lexicographically larger than 'b', so the answer is 'c'.
**Example 2:**
**Input:** releaseTimes = \[12,23,36,46,62\], keysPressed = "spuda "
**Output:** "a "
**Explanation:** The keypresses were as follows:
Keypress for 's' had a duration of 12.
Keypress for 'p' had a duration of 23 - 12 = 11.
Keypress for 'u' had a duration of 36 - 23 = 13.
Keypress for 'd' had a duration of 46 - 36 = 10.
Keypress for 'a' had a duration of 62 - 46 = 16.
The longest of these was the keypress for 'a' with duration 16.
**Constraints:**
* `releaseTimes.length == n`
* `keysPressed.length == n`
* `2 <= n <= 1000`
* `1 <= releaseTimes[i] <= 109`
* `releaseTimes[i] < releaseTimes[i+1]`
* `keysPressed` contains only lowercase English letters.
|
We want to make the smaller digits the most significant digits in the number. For each index i, check the smallest digit in a window of size k and append it to the answer. Update the indices of all digits in this range accordingly.
|
String,Greedy,Binary Indexed Tree,Segment Tree
|
Hard
| null |
374 |
That aapke ajay ko hua hai Hello hello everyone welcome to new video in this video by going to discuss another problem from last 4 p.m. Key Problem problem from last 4 p.m. Key Problem problem from last 4 p.m. Key Problem Is Problem Barfi Se Zor Is Number Higher Oil And Related Problems Statement Problem Number Of Subscribe Number Five With Number Of Every Time A Strong Will Tell You Adhir And Love You Call A Predefined Peeth Gas In Name Visitors Every Possible Result - 1the Pimple 140 For Return number is any number between the two appointed here, one more, subscribe our, if our number, subscribe, the number we have and after this - Vande's this till minus one, and after this - Vande's this till minus one, and after this - Vande's this till minus one, this number which has been reduced to From our number, after that the forest department will be bigger on Thursday. Subscribe to our channel for three from our number. Subscribe to our note. If there is a subscribe toe then what will we do here. Here we our people come from the village. Subscribe to the labs and if That team of hatred has come in any position, if we subscribe to it means that our number was taken as a village and it is not so, no number has been found from one to the end of K, then we are out of the loop on this, because our number has been taken. So if we do it then it was that subscribe to the youth, here we click on and subscirbe subscribe that we are not using the data type. Okay, so let's go and look at the top of the editor, so you are done with your editor. Above what we have to do is we will directly take our phones from where to where we will fry it from this will run 6 this is equal to one from island end will run this equal to one 6 is equal to one from done end and will give you a big one every time and what we will do inside this If we have a lump in any position inside it, if we don't get the number even after finishing, then while doing our front, it is Oo for our country and this is our accepted solution for sample test, please submit and let's see C for the rest of the face. That's how the result is and if we look carefully here, what is the time limit, we are not able to directly ask this question here, if subscribe, then we do not have to do anything, if we have to copy paste the code, then from here to here. Till we control now we will take participate in above control C now we will go paste this on top of its glass and see this is our C plus there also the runtime time limit directly here we submit the result comes where But our time limit exceeded solution is correct but it will not be accepted by us because our question is how many solutions are there in our solution, so now we will see what we have to do in our optimizer properties approach and what we have to do in dimize approach. Have to do binary search and subscribe, here we appoint our function and here we appoint and second point - we could get it done - we could get it done and if it is not found here then we subscribe if it is ours that without whatever function. If our gas is made of gas, before that we will have to make meat. What will our meat be equal to? Enter made me, our tomorrow will be star plus and by two, we can write the same for the same issue, plus and minus start divided by two, subscribe, what is this our Ghaghra? But if our ghagra is reduced somewhere and if it does not happen and our gas admit key is a gift, our gas admit my tab made, if we get its value minus one, then what will we do in that case? If our required number is less than our number then what will we do in this also our if we example if 123 45678910 what where but our how many and do not add we do that and Whose minutes minus one is fine and apart from that, if the debit is not giving our zero - and is if the debit is not giving our zero - and is if the debit is not giving our zero - and is not giving then what are they giving you for internet and we are late then what will we do in that case. What we will do in this and there is this part, we will do it, in this we will end up like plus one, this will be ours and if ours is not found here, our answer will be the answer because our 1212 - has been covered 1212 - has been covered 1212 - has been covered because ours is left. What might have happened which reduces our number, if earlier I was searching here then what would happen if earlier I was searching in this complete, what will happen now if despite this I searched in the loop then it will return the truth on the right, after that I will know on the left. If you are searching, then its two pieces will keep coming either on the left or the left, then what will be its time complexity, should its time be mixed with the long end because then the bay time is connected, if we talk about graph end space then it is above. Above, first of all, what do we have to do, so first of all, we will come to the village, use this - the accused will have to subscribe, note the intensity, chilli and ours will be ours, this card plus that and minor start divided by two, okay why our balance Two will be Star Plus and White above, what do we have to do, we have to check here, if our gas add, whatever our gas will be admitted, if they return free, then this will be our answer, what will we do, we will return whatever our gas is here. We will be okay and if it doesn't happen then two more kisses will be left if we see if our ghagra if he is killed - if he is killed - if he is killed - what will we do in this we will do that - we do that - we do that - we are matching the point with if it doesn't happen then we What will we do, we will come inside this and inside this we will do plus one K Okay, like this is our end, we will get our answer in the form of M, if our answer is not there then we will come inside this mile and we are thieves, this is our If the answer is not found there, then our answer will help and we will return it. Let's see if our solution is correct or not for NCVT Result. Here we start with 'A' and we have Here we start with 'A' and we have Here we start with 'A' and we have defined 'Aishwarya', 'S' defined 'Aishwarya', 'S' defined 'Aishwarya', 'S' is 'I' and this too. Let's do MS so let's is 'I' and this too. Let's do MS so let's is 'I' and this too. Let's do MS so let's run it again. You should not do this. Here we have a successful year for this Ranu and this is our successful year for this. Anushka submit this. See the result. There were spaces left above. This is our successful year. Which is then subscribe online very much and do the arrests here 13010 You do not have to do notification in the evening that we are here on the face from now onwards if we submit let's see what our answer will be And this is our successfully summit which is Pastor No Subscription No Subscribe If you have any doubt then you can comment in the comment section below Thank you for watching
|
Guess Number Higher or Lower
|
guess-number-higher-or-lower
|
We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n`
| null |
Binary Search,Interactive
|
Easy
|
278,375,658
|
1,770 |
hello everyone welcome to csl and i am nishant here let's solve the another lead code problem maximum score from performing multiplication operation by saying it seems it's so easy problem and we'll go inside then we will find out no it's not a little bit tricky and the first thing we should know when to use and how to use algorithm and i'm talking about approach what approach will be if we will get this then it's so easy only okay basically we have to get the like numbers is given we have to add we have to multiply these number in this either we can take the first and last not in middle okay we can't sort it okay so like example minus five is there okay and here minus ten minus five three 4 6 so what we can do we can just uh multiply minus 10 to the minus 5 or 1 which will be the greatest we have to find it out okay so that's all let's see first i'll solve then i'll explain we are going to do by recursion okay so just say operation nums it's a big name let it change let me change starting index we need some starting index then we need some um i index zero okay so see how many time we have to multiply how many uh length of the multiplier okay like 3 is there no we have to multiply the three node number only here how many 1 two three four five no we have to choose the five only we have to multiply five element only not more than that in that only we have to get the maximum number maximum sum okay so let's see all right so private operation nums oops okay nums multi indexing guy that will be uh for multi okay for multiple array indexing is start for our num sorry okay so if when multiple dot length is equal to it will be better i is equal to multi dot length then return 0 okay nothing else in a and d is equal to end a and d is equal to start means here is start end means from here okay so likewise so how we will get it then nums dot length minus i this you do dragon you will understand it properly minus i okay excuse me int operation one is equal to what we are going to find we are going to multiply multi i into nums start okay plus operation multi i plus one next time right start plus one all right till here no problem i guess let me paste operation two so from end right from end and a start should not increase start will like this only all right return we need maximum one okay that's all but this is a recursion it will go exponential time complexity we will get time complexity error okay so let me use the dynamic programming into dp and dp is equal to new and we have to get the s how much it is 10 to the power 3 right 10 to yes so this much now here if dp i start doesn't is equal to zero return dp i start okay here what you do dp i start okay let me run it multi invalid okay i didn't return right and typo error now let's now what happened man m-u-l-t-a all right multa multis so here we go let me submit it that's all guys let's go for explanation who got it they can go if who didn't get properly let me explain so you can get it no issue okay so here what here we are seeing that 5 minus 5 3 minus 3 okay minus 2 not minus 2 7 1 okay these are given minus 10 minus five three four six i should type i should write before okay so what basically we are doing know what we have to do they are asking like we can i either multiply minus this one and 1 into minus 10 or this one like this two or these two okay so okay either we have to multiply this one or that for s from first or from last okay so here what we are doing with the help of recursion see if we take minus 10 okay or which one is greater obviously this one is greater right this is giving 15 this is a minus 10 all right okay now go to next minus 3 into minus 5 and 7 into minus 5 which one this one great obviously okay now go to next minus three into three okay uh here one into three which one this is minus nine and this is 3 so according to this we will choose this but it's wrong here if we choose 3 over minus 9 then we will find only 84 if we'll sum it up but we need 1 0 10 or 1 not 2 okay so for that reason we are using recursion why using okay i'll tell you i'll show you minus 5 how it will work i'm going to tell you minus 5 minus 3 2 7 1 okay minus 10 minus 5 3 four six okay this is given here starting in starting we will choose uh this two if we are taking this two okay but we will check with this which is greater and if greater if this is the greater then we will take it for example here we are getting trouble here we was getting trouble so here maybe we will take this two we are doing okay but with this we are checking okay if we are starting up for ending one how we are checking for ending one we will check like this we can see maybe this and this is taking so how we will check yes how we will check like this okay so if you do tree no like zero and value is how much value is almost minus five if you do then go one the values how much minus three then two to lose too much minus three likewise if you'll go we will make three and all you it will look clear for you so i hope you got it if not go do to dry them definitely you'll get it thanks for watching guys see you soon bye
|
Maximum Score from Performing Multiplication Operations
|
minimum-deletions-to-make-character-frequencies-unique
|
You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of the array `nums`.
* Add `multipliers[i] * x` to your score.
* Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on.
* Remove `x` from `nums`.
Return _the **maximum** score after performing_ `m` _operations._
**Example 1:**
**Input:** nums = \[1,2,3\], multipliers = \[3,2,1\]
**Output:** 14
**Explanation:** An optimal solution is as follows:
- Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score.
- Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score.
- Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
**Example 2:**
**Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\]
**Output:** 102
**Explanation:** An optimal solution is as follows:
- Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score.
- Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score.
- Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score.
- Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score.
- Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
**Constraints:**
* `n == nums.length`
* `m == multipliers.length`
* `1 <= m <= 300`
* `m <= n <= 105`
* `-1000 <= nums[i], multipliers[i] <= 1000`
|
As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.
|
String,Greedy,Sorting
|
Medium
|
1355,2212
|
290 |
all right let's talk about the word pattern so you're giving pattern and the string s so finders s follow the same pattern so here's follow means uh full match so such that there's a direction between a letter in pattern and a non-empty word a letter in pattern and a non-empty word a letter in pattern and a non-empty word in s so basically a represented though b represents a cat right so if b occurred again you have to know this is k and not at all so this is not right it's because a the first a and then the last is either dark and or fish right so it's false so basically this will be really simple you have to create a hash map so i'm going to store a character and then string map new hash hashmap and i need to split the uh split the string and split by the space right so i can definitely know like if my length of flow pattern is equal to the array right so if they are not matched i will just return false okay so now let's talk about uh how you actually need to do it so basically you need to traverse the entire um it's either strength lens or the right so contains key see if you find it in the map you have to do something if not you have to do another thing right so if you find it right if you find it then you have to check if messed up get c equals if that is equal to the string s then you don't have to worry about if not right if not equal you have to return so i'll just make one example so you put a into the map so a represent dope right and you see a again right and then you have to check if they are equal or not right if they are not equal you return false okay so this will be it right so how about if you don't have it right if you don't have it basically you have to traverse the entire map to making sure like the value in the string the pad the string should be the unique one so you don't want to like have a different value in other patterns so if key so basically like uh if dog life don't represent a dog represent a and b we also take those right over here and then i know oh somehow like the character b also represent dog right and this is not allowed like basically this is not if everything else i just have to put the current character with the current string and this will be the solution to right here and let me run it all right so let's talk about time and space complexity so for this one this is actually split by the space so this is actually all of n and this is all the fun so contains key this is using the hash index so this is all of one but the problem is you have to know the contents value is actually traverse the entire map right to check if i do have the value for the string s i right and this is all the fan so inside the folder it should be the total you should be unsquared right and the space is pretty much all the line right and this will be the solution and let me just copy and paste my primary space compressively note and then represent and represent the length uh should be the linear pattern or length of string doesn't matter so this will be it right and i will see you next time bye
|
Word Pattern
|
word-pattern
|
Given a `pattern` and a string `s`, find if `s` follows the same pattern.
Here **follow** means a full match, such that there is a bijection between a letter in `pattern` and a **non-empty** word in `s`.
**Example 1:**
**Input:** pattern = "abba ", s = "dog cat cat dog "
**Output:** true
**Example 2:**
**Input:** pattern = "abba ", s = "dog cat cat fish "
**Output:** false
**Example 3:**
**Input:** pattern = "aaaa ", s = "dog cat cat dog "
**Output:** false
**Constraints:**
* `1 <= pattern.length <= 300`
* `pattern` contains only lower-case English letters.
* `1 <= s.length <= 3000`
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in `s` are separated by a **single space**.
| null |
Hash Table,String
|
Easy
|
205,291
|
10 |
hello my friends this is Alexander bmin and this is a new episode of my YouTube show lead code with me where we solve coding challenges Brew your morning coffee and let's get started and go ahead okay as ordinary let's start with the task definition so given an input string s and a pattern P Implement regular expression matching with support for DOT and as risks where dot matches any single character and asterisks matches zero or more of the preceding element the matching should cover the entire input string not partial other than that we have couple of constraints so first constraint is that uh only English lowercase letters are present other than that the pattern may also include dots and asterisks and it is guaranteed that for each appearance of the character asterisks there will be previous valid character to much not as easy as it seems so let's try to think about it a little okay let's try to come up with the simplest possible solution so let's assume we have a string and other than that we have a pattern let's assume we have a string like a b it's important for us because in most scenarios it covers most of the cases so A and B if as a developer as I took a look into this string and the pattern itself I see that it matches but how can I uh be sure in that so let's read the pattern from left to right so what does it mean it means that um a and asterisk means that any character uh there might be any number of occurrences of a so any number means zero or more than one 0 one or more and next B so what can I do with it how can I implement it so let's assume I need I will start marching my string with the pattern and if I see that actually it is a pattern with asterisk I will try to shrink my string and move it one character to the left so what I mean by saying that so I see that a asterisk B definitely uh a suitable pattern for this string so that let me compare it with this string when I remove the first character okay it still matches and next again it is still matches and next it still matches but uh what else I need to notice is that this will match as well but uh what else I need to notice is that well this will not match the first part so that in this scenario let me shrink my pattern and remove this and next match be with next mat characters does it work yes it works so that let's try to implement it so first of all let's add a condition for exit in case our pattern uh we don't because this approach will be focused on shrinking the string and it will be a recursive approach what we need to do in the first place we need to establish a condition for uh for exit so let's assume if I have no more pattern to match H that um my string will match only in case if it is over as well because it is said here on the condition that Mar shink should cover the entire input not partial so this will be condition one condition okay next part I need to cover scenarios like this a uh asterisks B in my pattern uh so what I need to do in this scenario I need to check that actually my pattern is longer than one so it has at least two characters and the second character P Char at1 is asterisks so it checks that A and B is a and star and asterisk are two First characters in my pattern so what else I need to do so uh in case if length of the strings is longer than zero string is bigger than zero um and now I need to start uh marching to make sure that the first character of the string matches the first character of my pattern so if uh in my pattern Char at zero again it is a in my scenario is equal to dot any character or P Char at zero is the same as first character of my string uh what I need to do I need to make sure that other characters of the string matches so let me provide some details here so this is my pattern a is asterisk B this is my string as it was in the previous example a b so what I'm doing here I need to I identified that this is a pattern with asterisks so that I need to check that uh is first character of the pattern is the same as the first character of the string and if so I need to continue doing that uh I just remove move this until it stop matches stop matching so uh and next I need to call this um recursively a sub string uh removing one character from the string and try to match it with the remaining expression if it doesn't match return FSE other than that here I have a scenario then it no longer matches so for example in thisa this case is no longer covered so what I need to do a aisk b what I need to do I need to remove First characters first two characters from my pattern okay so in this case what I will do is I will try to check if is much of my string remaining part of the string and pattern without first two characters okay this is the first bit the second bit in case if my string does not my pattern does not include the character so it's for example cases like a pattern is a and my string is for example a b okay it's also suitable scenario so in case if uh I still have string too much string length is more than zero and first character of the string pattern Char at zero is dot in this scenario doesn't matter what care what is in the string or P Char at zero is the same as string Char at zero in this case what I need to do I need to move both I need to remove first character from both pattern and string okay so return is much string uh substring from one p pattern substring one if it doesn't match so for example when we remove all the characters from here three times it will not match I need to return false this is the first approach it's relatively simple it's just based on two uh pointers and it's acceptable it's accepted and let me submit it and let's see how it works uh it's not really good because it has a quiet long uh computation time and it beats only 5% of users with Java the it beats only 5% of users with Java the it beats only 5% of users with Java the reason is because it's a recursive algorithm so let's try to come up with something which is better from performance perspective okay now we will struggle a bit because what we're going to do we're going to apply dynamic programming approach so idea of dynamic programming is that in case if you cannot solve the big complicated task let's split into a collection of small tasks and try to solve them one by one so like building common solution from multiple particular Solutions again let's get back to my string can pattern so let's assume I have a pattern a risks B and this is my string a b for dynamic programming what I need to have is I need to have a table um let's first start with indexes of the table so on rows I will have rows we have rows and columns in the table on columns I will have pattern it's my pattern a asterisks B and these are indexes in my pattern A1 2 and zero other than that I also need to have indexes of my table so it's a uh index of a pattern it's important to highlight so this is my pattern this is index of a table with Solutions okay and other than that on rows what I will have is my string a b and again 3 four this is 0 1 2 3 well okay so uh what's in the cells of my table include information where the string uh of length for example string which is built um from index0 to the given index in table so from 0 to 0o for example matches the pattern built from zero to uh index again so this will be always match because empty string always matches uh empty pattern and next in the next column and next row what I going to write is I'm going to check if for example empty string matches uh 0 to one this pattern does it match empty string no it doesn't match so that let me put no here uh does this match string empty string does it match pattern like a and asterisks okay it matches because a and asterisk you remember a and asterisk May Match multiple things it may match nothing it may match a string so that here I need to put yes because for empty string on row I have a string and uh here I have a my pattern it matches uh it matches any anything so a and asterisk match actually anything so that it's why here so next again I'm moving from row to column and again what I need to check is that will it match the empty string well for this exact scenario I know that it is just a b so it's and B as a character does never matches empty string so that it's no here because I have an empty string here this row is about empty string this is empty string row I'm checking will this uh small pattern match empty string yes it will and B will it match uh will it Mar the empty string no it will not because string should definitely include B so what's next what next I need to do uh if I have an empty pattern this is empty pattern will it much empty string yes and if in case of my pattern is empty will it match string of any length no okay this is what I'm going to and next what I need to do I need to start filling this table in columns so I'm filling First Column again row by row and actually I'm doing the same so what I need to check so this is my pattern of length one and it includes a so when will it match it will match only in case if actually character here in the first position 01 is the same as the character in my pattern is it the same yes it is the same next again I'm moving forward it is the same yes it is the same and again so what's next in my column it's uh asterisks it's pattern uh obviously here it's no because pattern a doesn't match the string B so what else I have an asterisk and it's more complicated case and in this scenario I need to check was the previous uh pattern the previous pattern March the string and in this case well I need to check what was uh the character for example uh previously was it the same as in the pattern yes it was the same so again here it was the same and this is why it still matches so a this is a different scenario this is different scenario so my patternn is asterisk and for asterisk I'm checking that previously on the same row it matches no it wasn't so that here it also does not match so what does it mean it means that uh string a b does not match the A and asterisk pattern now what I need to do I need to match my string again string piece by piece uh with longer pattern so in this scenario I'm checking that okay so what's in my pattern is it uh asterisk no it's not an asterisk is it a DOT like to mat any character no it is not so that in this scenario what I need to do I need to check what was the previous result so did it match the previous string so yes here it matched the previous string and also here at the end uh it the character in pattern and character in the string is the same so that here on the crossroad I put yes and all other scenarios are no so what's the solution for this task I need to take uh the last one element in this table this looks complicated implementation also doesn't look simple but this allow us to split more complicated tasks to the collection of simp playar tasks let's get back to the implementation and let's start writing the code so what we need to start is we need to create a table uh of booleans Boolean table um and size of the table will be uh Boolean s length because we have uh s number of rows and plus one because we need additional uh column for additional Row for fully empty string P length + one additional one for fully length + one additional one for fully length + one additional one for fully empty string and table 0 is always true because empty pattern uh always matches empty string so next we need to fill the first row for I is equal to zero I is less than P length i++ okay so what's important here is we i++ okay so what's important here is we i++ okay so what's important here is we need to compare the pattern with empty string so it will work only in case if it is asterisk in the pattern and in case if it match it uh in case if it was matching a previous character so for example in case if asterisk goes uh at the very beginning of string for cases like a asterisk B so this is my asterisk and I need to make sure that the string before asterisk also match it so if table zero and IUS one uh I can write here equal to true so that table at 0 and I + 1 is also equal to at 0 and I + 1 is also equal to at 0 and I + 1 is also equal to True uh we have plus one here is because you remember we introduced this additional column and now uh let's write condition for the exit so s length we need to take last one element and now we need to fill our table uh column by column so let's start in e equal to z e is less than S length I ++ I ++ I ++ for INT G is equal to zero g is less than P length g++ and let's start so what's in our g++ and let's start so what's in our g++ and let's start so what's in our pattern in case if our pattern PG is equal to a is equal to dot so our P what it means for us it means that we can uh do p g + one and means that we can uh do p g + one and means that we can uh do p g + one and other than that e+ one uh and it also other than that e+ one uh and it also other than that e+ one uh and it also means that string continuous to match the part PN if it was matching before so that table I + 1 and G + one will have that table I + 1 and G + one will have that table I + 1 and G + one will have the same value as table i+ uh i n g so the same value as table i+ uh i n g so the same value as table i+ uh i n g so what do we do by saying that we say that in case of previously string match it will continue to match in case if we have uh the same character in the string and in the pattern again I'm writing chart at uh G is equal to S charart at e it will be the same so in case of um character in the string is the same as the character in the pattern we saying that well if previously string matched the template m match the pattern it will continue matching the pattern even now other than that we have another scenario and this is most complicated part if P Char at G is equal to asterisk so in case if we have an asterisk so what we what else we need to check is that uh was it matching uh the string before and what was the character before the asterisk so in case if P Char at uh G minus one the previous character it was not the same as uh the character we have right in the string right now and it was not Gus one G minus one it was not a DOT so in this case what we need to do we need to say okay uh if it wasn't we again continue marching our string in the way it was before h g j minus one I + one so what before h g j minus one I + one so what before h g j minus one I + one so what do we say by doing that if it was uh if previous string if previous character matched we can uh go ahead and now I + 1 and G + now I + 1 and G + now I + 1 and G + 1 uh and here we have a condition we need to cover multiple scenarios so for example scenario when it was multiple strings uh like scenario like uh a star in the pattern and string like a so we need to say that in case it will continue to mat if previously in the previous column it was matched or uh we also have the same scenario table e and G + one this cover table e and G + one this cover table e and G + one this cover scenario like uh in case if in the string we have roughly speaking pre previous character which was repeated once it's this scenario and also we have last one scenario to cover is that we had a string like pattern like this and string is like this so table e + 1 and G minus is like this so table e + 1 and G minus is like this so table e + 1 and G minus one hooray not really simple let's submit uh it's ordinary does not compile table equal to True oh not a statement Boolean table new bullan uh table are you sure ah yes of course it doesn't line 32 just miniers and again I'm struggling with chat it seems I need to create a chat somewhere for this channel is Leng uh my favorite types P length all the typers I collected all the possible typers I or I regularly do okay whilea it doesn't beat everything but as you may see it works almost uh 500 times faster and beats 73% not 500 times faster and beats 73% not 500 times faster and beats 73% not really simple solution but uh much better from performance perspective thank you very much for watching my videos hope you enjoy it please don't forget to subscribe to my channel write comments and uh put a like to this video that's it for today see you next week bye
|
Regular Expression Matching
|
regular-expression-matching
|
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "a\* "
**Output:** true
**Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ".
**Example 3:**
**Input:** s = "ab ", p = ".\* "
**Output:** true
**Explanation:** ".\* " means "zero or more (\*) of any character (.) ".
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= p.length <= 20`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'.'`, and `'*'`.
* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match.
| null |
String,Dynamic Programming,Recursion
|
Hard
|
44
|
1,641 |
if making six figures is one of your dreams you gotta first solve count sorted vowel strings so you're given an integer n returned the number of strings of length n that consist only of vowels A E I O and U okay and our lexicographically sorted a string s is lexographically sorted if for all valid i s of I is the same as or comes before s of I plus one in the alphabet okay so we want to return the number of strings of length n that only consist of vowels and the strings created are sorted in terms of the placement so a has to come before um e has to come before I has to come before o has to come before you right so it's a sorted string like for example this string would be valid a if n was three for example or a e o but uao would not be valid because not valid because U comes before a right and this has to be sorted right so if you see it U it has to come after a e i or o if you see an i it has to come after an A and an e right just essentially assorted string that idea should make sense to you it should be pretty intuitive what that means okay so it's a pretty simple problem it's a pretty straightforward prompt um this is definitely one of those problems that can be misleading because of the constraint states that n is going to be less than or equal to 50 so that's you know 10 to the one times five that's a very small tight constraint on the value of n so that may lead you to believe that the optimal solution is extremely inefficient right because usually when you're dealing with leeco problems if the constraint is so tightly bound that the value of your input is small then that's typically the case where the solution is like NP hard and there's no polynomial time algorithm to solve that mofo efficiently so they have to make that constraint small just so that it doesn't you know take all time existing in the universe plus 10 to the billion in order for that algorithm to complete right but that's not the case in this problem so be conscious of the fact that even if the constraint is tight you may be misled into believing that the optimal solution is inefficient there could be a really efficient solution even though the constraint is tight um most of the time it's a really good indicator to determine if a problem has an efficient solution but just be conscious of the fact that it's not as always the case I'm sorry about rambling let's go ahead and try to figure out the solution so for n equals one pretty simple right because if n equals one don't look at that you only have really five things that you could choose right if n equals one I can choose an A and then I'm done because I can't use another character because there's only one link one letter length string I can use an a I could use an e I can use an i can use an o or I can use a u right and there's really if I thought about the number of ways then I could use an a well there's just one way of doing that there's one way of using an e this is one way and if I add up the total number of ways one two three four five I get five sorted strings that consist of vowels only okay maybe two will reveal something a little bit more um helpful well if I use a as the first character the next character I can use is e or I could use well I could do that too I could use the next character as a right but I could also use the next character as e I could also use the next character o and I could also use the next character U right because I can only use these five letters but since I'm starting with a and it has to be lexicographically sorted I have freedom to use any um subsequent letter because any subsequent letter would meet the constraints listed as lexographically sorted okay you know I'm gonna color this just so that it's clear what I'm doing because this is going to get a little bit cluttered okay now for E this is where we start thinking about the nature of being lessographically sorted if I wanted to use e as my first letter well I can't use a as the next letter because it has to be lexographically sorted so in order for it to be like so graphically sorted the next letter has to either be e or a letter in the alphabet that comes after e so it could be e or it could be I could be o could be U and then we play the same game with I and O and U right for I the next letter could be I could be o could be U for o could be o or it could be U and then for U we'll just use black I guess for you the only nice thing could be you so this kind of articulates all the next options you have for n equals two right for the first character I could use a and for the next character for the first character I can use any of these for the next character I can use any of these but the links between um capture or articulate uh the connectivity that could occur right so if I was to look at any path it would give me one of the valid strings right that's the idea like from E I can go to e right and that's a valid string I could go from E to O and that's a valid string I could go from E to U right that's a valid string I could go from o to U that's a valid string right we're going to capture if we've captured all of these paths we would capture all possible strings that are valid right and you'll notice that there's no invalid string Within These boundaries because you know first we thought about the letters that we could use and then we created edges to ensure that within the let with the letters that we could use we never attach letters that can't be attached in the order of which they're set up right so e would never attach to a because there's no link from e to a right there's a link from a to e because that's valid but a link from e to a does not exist because that is not lexographically sorted okay and you'll notice here there's 15 in this case so how does that work well I guess this leads to a natural dynamic programming solution because well first we're dealing with a dag here which is the directed acylic graph if you're not familiar with you know algorithm theory that may be a little bit of a foreign term but essentially what that means is there's a way to build this system where we think about um we think about a recurrence relationship we think about adding something in terms of what it can be added to okay so when I think of a in terms of what it can be added to I look at this graph and I say what can a be added to and how many ways can I do that right so the number of ways we're going to call this n of you at n and what I'm basically saying with this weird system I just created is this is going to represent or this is going to be used for our catch our recurrence relationship this is the number of ways to create a n length string ending with a u now this is you as in the node U not you as in the letter U so maybe we should give it a different letter so let's call this uh X okay with a X letter so basically what this means is how many ways can I build a string that ends with the letter X which could be aeru such that it's of length n Okay so in this example how many ways can you draw a letter a ending uh ending with an a that's only length one well that would be one right the number of ways that I can the number of ways to create a one length string ending with a is what it's one because it's a itself same with e same with I same with o same with you how about a well in this care in this case well how many ways can I create a string that ends with a well either it's based off what goes into a well what goes into a it's just this length here so this would be two this would be one as well right corresponding to a well how about e while e could attach itself to a so that'd be a e or E could attach itself to this e so that would be e so this would be two how about I could attach itself to this a right because I'm just dealing with the links that go into it so it can attach itself to this a and become a I or e i or I so this could become a-i-e-i or I so this becomes three and a-i-e-i or I so this becomes three and a-i-e-i or I so this becomes three and then you'll just kind of notice where we're going with this pretty clearly right this becomes four and five right because o can attach itself to a-o-e-o-i-o-o-o-u uh oh that's it and a-o-e-o-i-o-o-o-u uh oh that's it and a-o-e-o-i-o-o-o-u uh oh that's it and then U could be a-u-e-u-i-u-o-u-u-u-u me you me uh a-u-e-u-i-u-o-u-u-u-u me you me uh a-u-e-u-i-u-o-u-u-u-u me you me uh so that could be five so that'll give you the total number of uh things that we could connect and you'll notice if we were to extend the system out right we could continue this process and at the end what we have is we just sum this up and that'll give you the total number of solutions right because the total number of ways we can do this is the total number of ways that we the total number of ways we can make an End length string is the total number of ways that we can create an end link string ending in U plus the total number of ways of creating an end and Link string ending in O and an i and an e and an A so if we sum these up we should get the solution which is 5 plus 5 which is 15. and then just for the sake of making this a little bit clearer let's make this n equals three which would correspond to adding another one of these systems let's first uh clean it up a little bit before we add it so if we made this n equals three it would be the same edges right because if it ends in If the previous thing ends in e now we know that's the LA the number of valid strings ending in e so then we need to we have the same links because now that ends in e the subsequent things have to come uh have to be e or have to come after e well all right so let's link these up again like that so then how would we work with n equals three well for a there's one way to get to a and there's one way to get to that previous a so this would still be one now here's where it gets a little bit more interesting because there's One Way um there's one way to get a and e so if e attaches itself to a there's one way to get there so we'd get one there but if e attaches itself to e well there's two ways to get to this e so that means there's two additional ways that we could get to this e right the idea is basically if this had a e an ee right there's two ways to get to this e so we can attach this e to these two previous solutions to get a e and e right so that's the basic idea so I just sum up the total number of ways I can get to the things that I can connect to before me right so this would be two plus one equals three now for I can attach itself to a or e or I there's one way to get to a there's two ways to get to e there's three ways to get to this so this is one plus two plus three equals six an O can attach itself to a or e or I or o so that's one plus two plus three plus four which is uh 10. all right four three seven ten okay all right and then U could attach itself to five to four to this and this that's one plus two three plus three six plus four is ten plus five is fifteen like so and you can notice that this problem would just keep propagating forward right so the recurrence relationship then is well the number of ways to get to a node X using n characters it's just the sum of the nodes y such that Y is less than or equal to X right because to attach to a node right to attach to this node I can only attach things that are less than or equal to it right I can attach i e or a because it's less than or equal to I right to attach an E I can only attach things that are less than or equal to it so that's e or a right so I can only attach y's to X such that the Y's are less than the X and I'm going to look at all nodes y I'm gonna sum up their values using something that's um one less in terms of the length of the string right all the link three strings I can create ending in i right so an example would be this I here right so this I is length three right and I can attach this I or this e or this a so in terms of the relationship that'd be n of I using length three equals the sum of nodes y less than I of length two this is an I here or no this would be a y of length two right because that equals n of a of length two plus n of B uh n of E length two sorry plus n of I length two right I'm basically adding up these links this link and this link okay so this basic recurrence relationship will get us to the solution so let's go ahead and write that and then we'll think about some further optimizations that we can create so well we'll just do it with a default deck so we'll create end with a default dict where the default value is one to represent um to represent what to represent our values I guess because that'll be the default value so look at each n value in the range one two n plus one right now A and E so we should probably start uh trying to think about the best way of doing this because I know a much faster solution where you don't need to think about this so it's kind of hard to be like think about in terms of I mean that's not even optimal but okay so we'll go from one to n plus one actually we'll start at two we'll go all the way to n all right that's fine and then we'll say okay we'll look at each letter we'll call it X why did I capitalize it for X in range one to five or no to five right because there's five vowels there's a e i o and u so we'll just capture all those vowels by using numbers um we'll say okay end of this letter n of this letter using of length n equals the sum of n of each letter y using one less length so I'm just converting this sum right so n of X of n equals the sum of all y's less than or equal to X using one less letter for all y's that are less than or equal to n so that'd be from 0 to Y plus one all right and then at the end we just return the sum of each n of length n for X in range zero to five right because that'll get us all vowels int object is not subscriptable oh because this is a dictionary sorry so all these things need to be like this to represent them we're using a dictionary not a uh linked list or a list Y is not defined oh oops an X plus one because X is a current node that we're looking at not a good sign all right cool so this solution works it looks pretty quick technically your Solutions are going to be wild and all over the place right because your n value is so small so you might get like one submission that's better than 99 and the next submission is better than four percent right I wouldn't really trust whatever that runtime timer space check or whatever determines right without autograder determines because there's going to be a huge variance because your constraint is so tightly bound so how do we make this just a little bit more efficient well I guess the first thing is you know we're only basing the current thing on the previous thing so we don't need to keep track of things that are two iterations before right we only need to keep track of what's occurring right now and what you'll also notice is that there's a running sum right so let's first make that first uh first make that first that primary fix which is you know we don't need to update everything we can just keep track of the last iteration right because the idea is this regardless of how large the system is you know this iteration is only based on the previous iteration so we only need to keep track of like two things after when we're looking at this iteration the values here no longer matter right the stuff that happens on this column is no longer relevant so we don't need to keep track of that so to save space we just need to keep track of the previous thing that occurred right but one two three four five and then that means that we can create a new array this would still be one so I'm trying to think about how it's gonna work so then we go through all range we go through each index and we'd say okay X now equals the sum of d at y for y and range X plus one right so we only need to keep track of the previous iteration and then at the end we just reset D equal to DD and then at the end we just have to return the sum of B because that will give us the sum of all the values right so now we're basically just keeping track of the previous iterations value right so if we print uh we don't need to do that hopefully that makes sense right so now I'm just keeping track of the previous iterations value for each of the vowels and then shifting it each time right so I basically I set this equal to D I find out what d is and then I set D here so on the next iteration when D is here I can look at d here so I can just shift over every time so that's essentially what I'm doing right I use this as D I find out what the next iteration of D will be and then I set that as D and then I find the next iteration of D and said that is D and so on and so forth okay now the net now technically this is the there's a constant solution which we're not going to cover because it's more of a statistics based solution but this is as good as the dynamic programming approach we'll get in terms of runtime and space complexity but you could technically do a small optimization to make it a little bit faster to think about the fact that um well you know one thing you'll notice here right is like this is one and this is two plus one and this is one plus two plus three this is one plus two and this is one plus two plus three plus four plus five so essentially because the way that this works is everything's just based on itself and everything that comes before it there's just running some idea right this is one and this is just one new thing added to it which is itself right and this is one plus two which is this part and then we have a new value three that's added to it so it's just yourself plus the previous thing right what is o well the value at o this is an O here is one plus two plus three plus four I'm talking about within this context here okay what's the value of I is one plus two plus three and what was the value of O before it was four so the weird thing here you'll notice is well D of o equals D of I plus what D of O was before I'm using D now and I should be using n but the idea is you become what you were before plus whatever was previously added right this is what is D of u d of U was five and then it becomes one plus two plus three plus four plus five well that's just D of o plus d of U right d of U equals one plus two plus three plus four plus five it used to be just five so it's really just one plus two plus three plus four plus five right so you don't really need even this DD idea all you have to say is well for I in range one two to five D of I equals whatever it was before plus whatever we populated before it and then notice it's slower but again you're gonna have huge variance because your n value is small this is technically an optimization right and you could move this right if you really wanted to be fancy with it you don't even need this value anymore you just need to make sure you do this process that many times so we could do a product and we can move this all onto three lines like so now I'm wondering if I want to think about the constant time algorithm but I don't want to push my luck so we'll just stop it here and talk about what this is well let's say that and okay we already have n given so time complexity we have to look at all n variables right I mean we have to look at all end length strings from one to n um and then we do five operations where we update this thing so for all n variables we look at five things and we update them accordingly so we look at a constant number of things and we do a constant number of operations so for All N Things We Do a constant number of things which include constant operations that's a constant times n was just n and then we return the sum of N D but that's just those five variables that we populated so it's O of n runtime in terms of space regardless of the length of the string that we're creating if it's length five or length a thousand we're only going to update it but we're only going to create space for the five values that we're populating so regardless of the size of n um we only have to store information about five things so that's o of one space all right guys hope you have a good uh rest your day peace
|
Count Sorted Vowel Strings
|
countries-you-can-safely-invest-in
|
Given an integer `n`, return _the number of strings of length_ `n` _that consist only of vowels (_`a`_,_ `e`_,_ `i`_,_ `o`_,_ `u`_) and are **lexicographically sorted**._
A string `s` is **lexicographically sorted** if for all valid `i`, `s[i]` is the same as or comes before `s[i+1]` in the alphabet.
**Example 1:**
**Input:** n = 1
**Output:** 5
**Explanation:** The 5 sorted strings that consist of vowels only are `[ "a ", "e ", "i ", "o ", "u "].`
**Example 2:**
**Input:** n = 2
**Output:** 15
**Explanation:** The 15 sorted strings that consist of vowels only are
\[ "aa ", "ae ", "ai ", "ao ", "au ", "ee ", "ei ", "eo ", "eu ", "ii ", "io ", "iu ", "oo ", "ou ", "uu "\].
Note that "ea " is not a valid string since 'e' comes after 'a' in the alphabet.
**Example 3:**
**Input:** n = 33
**Output:** 66045
**Constraints:**
* `1 <= n <= 50`
| null |
Database
|
Medium
|
615
|
485 |
what's up guys Nick white here techni coding stuff on torsion youtube it is very late by me and I'm about to go to bed but I was just looking for some problems for tomorrow and I saw this one and I was like I could do this in two minutes cuz it was super easy you know maybe if you're beginner you thought it might I don't know but I mean it's pretty easy if you've done a maximum number pretty much so you're giving a binary array which is an array where each element is either a 1 or a 0 because binary encoding if you didn't know zeros and ones and you output the maximum number of consecutive ones so that means however many ones and the maximum time ones occur in a row that's how many you output so what there's two ones in a row but there's also three ones in a row so we return three because that's you know bigger than two a little math lesson for you but nonetheless if we had a zero here's the idea we're gonna keep a maximum and then a current maximum current consecutive number of ones are current some kind of variable to keep track of the current consecutive ones so it'll that will keep track of the current consecutive ones you know pretty easy it'll go one two and then when it hit zero it'll go back to zero because there's no consecutive ones in a row anymore and then I'll go one two three and there will be a max so the max will also be getting updated whenever we see a one so it'll be one ok well now the max is one I'm gonna - now the max is to max is one I'm gonna - now the max is to max is one I'm gonna - now the max is to zero max is still two but the current consecutive ones is back to zero one max is still two - max is still two three is still two - max is still two three is still two - max is still two three all right now max gets updated to three hopefully you get that lets pretty much it let's code it out so you can see though so wait a max is zero and then we'll say current one number of ones very descriptive I would not use that variable name because it's pretty long but just to make it visually appealing for you guys and you know so you understand it no I'm stop so look through the array I would assume you understand the loop and then we have the two options right if nums of I is equal to one well and if it's not equal to one right there's two options there and what we're gonna return at the end is max so if it's equal to one well we're gonna add to the current number of ones we've seen one obviously and if it's equal to zero well the current number of ones is equal to zero because we're starting over at that point if we see another one it'll get added blah and then at each iteration like I said we just have to update the max whenever we see a one we have to check all right did we reach a new peak here so we check against max we use the math dot max method to see the bigger out of the current number ones in the a total max that's it super easy problem great beginner problem though so I don't hate this being on lis code I think so there's the success and I think a bunch of people get mad I have easy problems and they dislike but like come on there's beginners obviously you gotta start somewhere I think they should have some easier ones honestly give it some more rankings here's the here's a cool one I saw where they do it in like a line basically they do ternary conditions but this is for the more advanced programmers watching but that's cool so that was the problem I mean I guess the angle me know if you have questions oppression it's pretty easy and I'm doing the premium I got premium now so I'm doing those on patreon only and yeah thanks for watching and I'll be uploading some more tomorrow because I know you guys are you guys like the leak code so join the discord see you guys thanks for watching
|
Max Consecutive Ones
|
max-consecutive-ones
|
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_.
**Example 1:**
**Input:** nums = \[1,1,0,1,1,1\]
**Output:** 3
**Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
**Example 2:**
**Input:** nums = \[1,0,1,1,0,1\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
|
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window.
How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
|
Array
|
Easy
|
487,1046,1542,1999
|
859 |
Hello friends welcome to code Sutra let's all lead code product number 859 buddy strings in this problem we are given two strings see though the problem is a very easy level problem it is necessary that we generate all the possible examples before even diving into the implementation part why because any string problem that is in late code or that is as in interviews have the same pattern that is there are n number of Education edge cases so if you don't know it before implementation you have to re-implement the whole solution the to re-implement the whole solution the to re-implement the whole solution the whole track of the solution will be changed so it is very important that we write down all the examples that comes to our mind only once we have written all the examples and solved it on a piece of paper only then we'll be diving into the actual solution this is true across all the string problem so the first thing is here we are given two strings one is s and the other one is goal for example A B C D E and AD CBE here we have to swap two characters to make them equal for example this B and this D what happens once we swap this actually becomes the same a d c b e are they equal yes they are equal let's take the second example which is similar to the same example but here we have X and here we have C can any two characters be swapped the constraint of this problem is only two characters can be swapped they have to be swapped so if you swap B and D we still have X remaining which is not at all there here so this won't be a buddy string let's take another example this and this are already equal but the question is you must swap so in this case this will are also not body strings let's take another example though they are already equal can this a be swapped with this C yes right so this is a body string let's take another example A B C and A B are they can any two characters be swapped why their length is only not same so we will not consider it any further let's take another example where a b c d and the goal is equal to a c d so can any two characters be swapped here no right why because only one of them is changed for example even in here let's take e can any two characters be swapped no right why because only one character is different or let's take a b e so only one character is different so this can also not be done so these are the various edge cases that has to be considered before solving the problem now let's write down what all the observations we have drawn the first thing is if two strings are equal we need at least one character whose frequency is greater than one that is in this case we saw that these two example if two strings are already equal we need at least one character whose frequency is greater than one that is the first observation that we draw and we understood this at Max two characters can be misplaced the second thing is we saw here is here three characters are misplaced at Max only two characters can be misplaced if three or more characters are misplaced we can directly return false the third thing is the misplaced characters should be exchanged that is whatever was there at ice place and J's place can be swapped and they both have to be equal and what was the fourth observation that we brought that is they should be of equal length what is the fifth observation that we actually drawn from the last example one is there must be exactly two misplaced characters there are there can't be just one misplaced character so once we are drawn all this observation now the implementation part will become very easy let's dive into the pseudo code the first thing is we're going to directly Implement that if they are not of equivalent why are we writing this first because it doesn't make sense to continue the problem if this is not true that is the first thing the second thing is if both of them are equal what we are trying to do is we are checking the frequency of the character how are we checking one thing is we can do it with the help of a asset or a hash map but here we are given that only lower cases will be there so what we are doing is we are creating a count array of 26 and each represent for example a will be represented by 0 B will be represented by 1 and so on so once we get the account will be increasing at any point if the frequency increases to 2 we'll just return true because that's it what we want then we will keep track of index 1 and index 2. that means we can only swap two characters so we are keeping track of index 1 and index 2 both of them are minus 1 and minus 1 why because the index can never be equal to is minus 1 or less than 0. now what we are trying to do is we are checking are there any misplaced characters if there is a misplaced character for the first time we are changing the index one if there is for the second time we will be changing the index to if there is for the third time we will not do anything and we will return false and one more Edge case scenario that we got here there can't be just one misplaced character so that is the condition that we are writing here that is if index 2 equals minus 1 will just be returning false why because there can be just one missed based character the final statement is that they can be swapped that is what we saw here this statement is written so let's dive into the coding part actually so before diving into the coding part I know this is the easy level problem but if you are interested in solving problems similar to this these are some of the problems that you can consider which have the same pattern with the increasing order of difficulty and we do have a telegram group where we will be discussing the solution to this problem and the link of the telegram group is mentioned in the description do consider joining the telegram group and let's dive into the coding part it is a straight away implementation from the pseudo code that is first thing is we are checking if the lengths are equal if the lengths are not equal it will just be returning false this case is 1 to count the frequency when they are equal the next case scenario is we have index as minus 1 and will be changing the index at every point that is if they are not equal will be changing index 1 first then the index 2 and finally we will be comparing them thank you for watching the video please do like share and subscribe
|
Buddy Strings
|
design-circular-deque
|
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._
Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`.
* For example, swapping at indices `0` and `2` in `"abcd "` results in `"cbad "`.
**Example 1:**
**Input:** s = "ab ", goal = "ba "
**Output:** true
**Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'b' to get "ba ", which is equal to goal.
**Example 2:**
**Input:** s = "ab ", goal = "ab "
**Output:** false
**Explanation:** The only letters you can swap are s\[0\] = 'a' and s\[1\] = 'b', which results in "ba " != goal.
**Example 3:**
**Input:** s = "aa ", goal = "aa "
**Output:** true
**Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'a' to get "aa ", which is equal to goal.
**Constraints:**
* `1 <= s.length, goal.length <= 2 * 104`
* `s` and `goal` consist of lowercase letters.
| null |
Array,Linked List,Design,Queue
|
Medium
|
860,1767
|
391 |
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now Hayaku between 91 perfect rectangle given and axis aligned rectangle where n is greater than 0 determine if they're all together form exact cover of a rectangular area Norwegian each rectangular region is represented as a bottom-left point in a table white point bottom-left point in a table white point bottom-left point in a table white point for example unit squares represent 1 to do OK return true Oh 5 tango from the exit of a rectangular region ok what are the constraints and I think of any smaller well if the numbers represented in and is smaller than we can much McCoy then we can just draw a thing draw it out and we still can I think my intuition here is basically just put it in a grid and then just check for it that'll be like n square the kind of two thing that you may have to look out for is that some of these numbers can be really big but in this case you only need to care about it being a rectangle and not um not much record a square or anything of the shape and it's access a line so what you can do is use a technique or I figure it's cool but it's just come put a coordinate compression or something like that I don't think that's an official name but you could compress the coordinate so that it fits and then because at most you could have n unique I guess two times n but oh and unique X access points and also an unique of and unique Y access points then you could construct an N square rectangle so yeah so that's let's do that okay let's start doing down then we'll kind of play about it and now that is nice you go to what so simple why mm and then now we want to put that in a in a hash table so actually it's just do next lookup is to go to numerate this let me know if this gets to coffee index and then we just do XS you go too high okay so that and sing for here okay yeah okay and then now we can just well let's a X to the 9 of X Dhaka and Michigan and of I look up and now we construct a grid where it is your x we can just go through this again okay so for let's say current X and range s X to Y X plus one except for now wonder next or top version of this and then the same for the why and then now we just a cross one and now ideally every quit should be felt so now we can just do a symbol for good for so I guess if so it's not you've got a one we turn for us cuz if it's either zero or given multiple then it's true let's go see mmm-hmm knowing to copy test cases is mmm-hmm knowing to copy test cases is mmm-hmm knowing to copy test cases is that right are they smell okay so it's well let's take a look well let me put in the cone for the test cases first guy do the same one now it's a slightly different okay let's print out the grid how I think I did this a little bit off so okay maybe I don't need a pass one on this because we don't actually do that so okay that's right yeah I know why his force am i off by one then I guess that makes it I'm mostly not I mean dude this is good enough to print we never we're never used to the max one I'm cooperating it so what's happening is that I'm conflating the points and they're square and it's like that's pretty essentially what I'm doing but it's submit I wish her good luck just some one thing that I should have test was a big number I think that's what I was saying to myself and I forgot why is this so stoner maybe I get time there minute no okay well I still very slow hey Dom you steer a better way I guess there's fire by the way well if nothing else I could return early I think that's I was thinking about it but I thought that maybe a little bit too slow to kind of keep on assessing it but actually I probably I've just done it here and then that would save someone to like if you have certain cases where that's just through it that just saved I let's get good enough because this is apparently good enough no ok let's try that again oh well I took out the print right that would have timed out I kept a print back in actually do use a lot of them well ok maybe not maybe I'm well so oh that is interesting so yes I barely squeezed in but so let me give it a second to think that I could i mean i debit be able to do it better faster but i mean i think some of it is a little bit tricky when they don't tell you what the n is and also just a constraint in the palm because then i don't know necessarily how to do it put on but that said it did one fast enough so that's very not but I feel like 9 second is fine not in the spirit of de-spawn I can I do a in the spirit of de-spawn I can I do a in the spirit of de-spawn I can I do a little bit better hmm I was hoping that the if statement but maybe the case that no but weird and then if I had if statement then you get to overlap in case way quickly and I definitely still end up using a lot of memory 253 max I think I forget what the percentile is but when it is not quite I don't know how to read this but okay I still palm soft no so obviously if I used kind of a faster language maybe it's a little bit better but that's no big deal is there a better way to solve this what is the easy way and again it really depends on n as well way because you can check the overlap case like as a pre-processing step if n is pre-processing step if n is pre-processing step if n is small enough and then because that's n square but it's unclear so that it makes it a little bit tricky to kind of analyze this problem as a result or like just thinking about a strategy but let me think about other strategies so yeah another thing I can do is PI sweep line because that seems pretty straightforward to sweep well at least like a we move one of the dimensions because you could just do a sweep on one of them and then you could even do like very naive like kind of like this just take taking a Napoleon on that boolean I guess an int of all the things that are in it I feel like I've done that palm actually so yeah it's actually you could what I if I was a little bit not lazy I would have definitely uh yeah I know - yeah I think I guess there's a rowing wind or to Mike or sweep line algorithm or line sweep a groom would probably well me make it and lie again and then you could sweep in both directions if you like and then just or keeping track of the current segments if you want to call it that yeah on I did well you sweep on the X and you keep their line segments on the Y and then just making sure that they're there no overlaps and there are no gaps and I think that should be okay hmm then you pop them out and you have to pop them back in yeah okay I think that's how I would do it better well I guess my solution somehow is fast enough which is not never crazy
|
Perfect Rectangle
|
perfect-rectangle
|
Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]` represents an axis-aligned rectangle. The bottom-left point of the rectangle is `(xi, yi)` and the top-right point of it is `(ai, bi)`.
Return `true` _if all the rectangles together form an exact cover of a rectangular region_.
**Example 1:**
**Input:** rectangles = \[\[1,1,3,3\],\[3,1,4,2\],\[3,2,4,4\],\[1,3,2,4\],\[2,3,3,4\]\]
**Output:** true
**Explanation:** All 5 rectangles together form an exact cover of a rectangular region.
**Example 2:**
**Input:** rectangles = \[\[1,1,2,3\],\[1,3,2,4\],\[3,1,4,2\],\[3,2,4,4\]\]
**Output:** false
**Explanation:** Because there is a gap between the two rectangular regions.
**Example 3:**
**Input:** rectangles = \[\[1,1,3,3\],\[3,1,4,2\],\[1,3,2,4\],\[2,2,4,4\]\]
**Output:** false
**Explanation:** Because two of the rectangles overlap with each other.
**Constraints:**
* `1 <= rectangles.length <= 2 * 104`
* `rectangles[i].length == 4`
* `-105 <= xi, yi, ai, bi <= 105`
| null |
Array,Line Sweep
|
Hard
| null |
1,941 |
hey everyone today i'll be going over the code 1941. uh check if all characters have equal number of occurrences so really um just counting all the characters making sure that the counts are all equal so we get this test case here we can see that a has two uh b has two and c has two that's equal we get another test case it's a b and we see that a has three b has two not equal so this would be true this would be false and that actually is the case we can see over here another thing we want to note is we look in the constraints and we see that s only consists of lowercase english letters so to count these characters we can actually just use an array i'll call this counts and uh we'll call this 26. uh because this is every single character every single lowercase english character so this is going to be our count and basically what we want to do is we also want to keep track of a max count the reason why we do this is because every single count or occurrence should be the max occurrence uh because they should all be equal so like say that each one is two occurrence the max will be two they should all be equal to two so that's what we're gonna do we're gonna go through each character in uh s so we'll do two correct turn it into a card then what we'll do is we'll increment counts uh so c minus a plus so we do this uh you can shift it by a because basically like a minus a will be zero uh you can subtract cars in java so that's how you do that and this will like uh basically count each character's occurrence so then what you want to do next is you actually want to set the new max i'll show you why we do that but we'll set the new max to be counts of c minus a so this will like find our max occurrence ever now what we want to do is we want to go back through counts so let's go through each count it counts and what did i say well we need to make sure that every single character's occurrence is equal to max so one trick is we might not have seen a character which will mean that count is zero and it won't be equal to max so we really want to make sure whether it's a zero or not and make sure that it's equal to max so uh if count is uh not equal to zero and count is um not equal to max so basically have we seen this character before and is it not equal to max well we know that we can just return false because it's violated it because every single non-zero count should be equal to max if non-zero count should be equal to max if non-zero count should be equal to max if we get down here we know that there's no issues we can just return true let's run this and we'll see if we get true oh let's submit this and you'll see we beat 100 on runtime and uh 93 on space so let's talk about time and space complexity time is just going to be o n and here's why this first loop it's just o of n we're just going through each character in the string the second loop we're really just going through counts which is always going to have 26 so it's just now the space is going to be constant and this is because we're only using this counter a and it's only going to be bounded to a size of 26 always with this constraint of the problem so we know that it's just uh oh 26 or o right so yeah hope this made sense i hope it was easy enjoy
|
Check if All Characters Have Equal Number of Occurrences
|
minimum-number-of-operations-to-make-string-sorted
|
Given a string `s`, return `true` _if_ `s` _is a **good** string, or_ `false` _otherwise_.
A string `s` is **good** if **all** the characters that appear in `s` have the **same** number of occurrences (i.e., the same frequency).
**Example 1:**
**Input:** s = "abacbc "
**Output:** true
**Explanation:** The characters that appear in s are 'a', 'b', and 'c'. All characters occur 2 times in s.
**Example 2:**
**Input:** s = "aaabb "
**Output:** false
**Explanation:** The characters that appear in s are 'a' and 'b'.
'a' occurs 3 times while 'b' occurs 2 times, which is not the same number of times.
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of lowercase English letters.
|
Note that the operations given describe getting the previous permutation of s To solve this problem you need to solve every suffix separately
|
Math,String,Combinatorics
|
Hard
| null |
234 |
Hello everyone my name is Rahul and today our lead code problem is paladal linklist so the values given to us in the linklist are linklist so the values given to us in the linklist are linklist so the values given to us in the linklist are they in a palindrome form or not and we have to find out their values let's see or not and we have to find out their values let's see or not and we have to find out their values let's see the problem okay so paladal linklist in this we Let's see first what is the statement is a single link list in which we have to return true it's column and false otherwise here if you see then the value is in column form but the values are value is in column form but the values are value is in column form but the values are in node fm list node fm linklist. In a firm, we should know what is true and in this also, this falsehood should not come, let's start, what logic do we understand in this, if we first take a view, which is our first solution, then what is that becoming in the mind, then if If we look at this carefully, whatever values are there, the first value is carefully, whatever values are there, the first value is carefully, whatever values are there, the first value is equal to the last value, the second value is equal to its second last value, then if you are wondering which data structure we are using. In this, what kind of last in first out happens, is there a rat in the stack, then we are the last, if we push all the elements in the stack, then the first will come on the top, second after that and this is the last one. So we have to match this one, so we will pop each one from the stack and match it with the head is ours, this is ours, if it is popped then it is equal, if we move the head forward then this will come, then if we pop it then this will come. So, even if these two are equal, in this way we can match all the elements with the help of stack. Okay, let's start, so first of all we create a stack, because if we match integer values, then we will make a stack of integer values. We will create instead of notes so let's call it stack okay and we will hydrate it later from the head so to hydrate now let's make a copy of it from the list node I will copy and assign head to it okay so We have to post all the elements in the stack, while copy is not equal to null push, what you will do in that is you will push the value of the copy and then go ahead copy dot next, now all the elements are inside the copy stack, okay now. What we have to do is now we will hydrate it from head to head we will item one by one value till head is not equal to n f stuck d p will return whatever value is not equal to the value of head if it is equal to the value of head. No it means and plum is not there then from here we will return it false, we will go next to the head in the else until the head is reached and if it comes out from this then write it means it is not false then in the last we True has to be returned but if it is not false then it will be true so this is also a simple category question. In this the stack has been used very well because we have to see that the first element is compared to the last. Have to do and the last element comes in the stack, okay let's run Accepted Let Submit Accepted All Right So this was not critical or complicated but the stack has been used well, write if falls in this category. If you like the video please like share and subscribe the channel thank you
|
Palindrome Linked List
|
palindrome-linked-list
|
Given the `head` of a singly linked list, return `true` _if it is a_ _palindrome_ _or_ `false` _otherwise_.
**Example 1:**
**Input:** head = \[1,2,2,1\]
**Output:** true
**Example 2:**
**Input:** head = \[1,2\]
**Output:** false
**Constraints:**
* The number of nodes in the list is in the range `[1, 105]`.
* `0 <= Node.val <= 9`
**Follow up:** Could you do it in `O(n)` time and `O(1)` space?
| null |
Linked List,Two Pointers,Stack,Recursion
|
Easy
|
9,125,206,2236
|
96 |
hey what's up guys this is Chung here again so and I want to talk about this 96 unique binary search trees problem it's a very classic problems as you can see it's got it have got they've got a lot of likes here I'm gonna give my own lights here yeah I think I kind of like this problem yeah so the difficulty its medium but to me I think this is more like hard medium between medium the heart you know yeah I think it's pretty classic questions here so let's take a look so the description is very easy you're given a number n how many unique struck unique be a binary search trees can you get from 1 to n right see he gives you an example here with 3 this one is the so first what was a binary search tree right binary search tree is that for each node the left reach node out others all the nodes on the left side is smaller than the node value and all the nodes on the right side it's greater then the root value so for N equals 2 3 goes to 1 here right so for 1 you have 3 and 2 here right because you cannot put 2 and 3 on the right side you can only put on right on the other I'm sorry you cannot put it 2 and 3 on the left side because they're greater than what so that's 1 same thing here and then 3 2 1 3 1 2 1 3 right it's pretty clear here but how can we know how many unique trees we can get with the number and write I think the idea we're using here is by using that the dynamic programming basically and you know I'll try to explain this one here yeah sorry for some reason my drawing software just stopped working so I just restarted okay so back to this problem here and so how can we deduce right deduce the result from previous result I think one thing we want to know we want to okay let's say for example with number three right with number three so the first thing we want to do this one two and three right so the total number with all these numbers is one two three the total subtree will be the so basically we pick each one we pick each of the element as the root element right let's say for example if we pick one here we pick one as the root and then we pick to as the root and then we pick three as the root if we have the unique binary search tree for all that for other the possibilities of the root node and we sum them together and then we get all the oh and then we get the result right we got the final result with n how many binary search tree we need right so basically the so the first loop will be if we have a three with loop from one to three right how many with each node we will recalculate the just calculate by using this what this element is the root node how many binary search tree is construct right and so in when it comes to this like each root no once we fix the root node right what we need to do let's say for example this one right this one here what are the nodes are left right so with this one who's the root and then the right side is two and three right so here we can't will we can only put 23 under on the right side right because they are they're both greater than one and on the left side will be basically will be empty will be zero right how about two here will be like will be one on the left side and three on the right side right for three how about three so three will be the one and two on the left side and zero on the right side right and the number of the total unique trees that for this one for example this one it's gonna be the number to tote the total number of sub tree on the left side multiply the number on the right side but basically this is the final result would be the product of the left subtree and the right sub tree let's say if this one is 1 & 3 right so on the on if this one is 1 & 3 right so on the on if this one is 1 & 3 right so on the right on the left side there's one and this one is 3 right okay so this is also 1 so 1 times 1 is equal to 1 which is this 1 and this is 0 right with 0 we also give it 1 because we don't want to make it 0 right with 0 and then this is the what this is like how many substrates for to knows right to know this 2 right 3 & 2 & 3 2 1 & 2 3 to know this 2 right 3 & 2 & 3 2 1 & 2 3 to know this 2 right 3 & 2 & 3 2 1 & 2 3 same thing here right 4 1 - this is same thing here right 4 1 - this is same thing here right 4 1 - this is gonna also be a 2 here also be a empties 1 right so in total over here class 1 class 2 right he goes to fire so that's the total binary unique binary search tree for N equals 2 3 & 1 search tree for N equals 2 3 & 1 search tree for N equals 2 3 & 1 okay one thing kitten keep in mind here right you need to do a mind jump from here see we don't care about what are the nodes number here we don't care about if it is 2 or 3 here or where it's 5 600 or whatever all we care about is how many nodes on this side right as you can see here so 1 2 & 2 & 3 right as you can see here so 1 2 & 2 & 3 right as you can see here so 1 2 & 2 & 3 there are different numbers but they're both 2 nodes right as long as they are two nodes we know that it will have two binary search binary tree that can that these two nodes can construct right so and as you can see here so now and then one is obvious is one right and now seems to remember we have calculated oh why did the way it is it's different fine different nevermind I think this is better right yeah this spider marker here so I okay remember see we have N equals to 3 here right 3 is 2 1 equals to 5 right so what does it mean it means that three numbers or three nodes can give us five unique binary sub trees right let's assuming we have this 4 5 6 and blah right when we deduce this kind of numbers there will be a case that the left subtree will be what would be 3 nodes right whatever 1 2 3 4 5 6 or word or something war or 3 5 4 right so in that case we don't need to care about what are those numbers we know ok with three nodes we will have 5 nodes right oh sorry we will have 5 unique binary search tree and then we can do use that right took to build up the bottom from bottom up right to build all the results we need right the phrase I move for here right with for here the left side would be one two or three and then here will be a pool before right and then we know one two three will have five so we can do you to a five here and here will be four is one right so it's a fire put five times one what would be five right so for this like for this route as a size and for this known as a route will have this result all right I hope this is I hope you guys I didn't understand so I know it's a it's not a easy I know it's not easy explanation to understand but yeah okay so let's try to code it so the code surprisingly is very simple all right so like we said okay we have to have a we need to have a array here first to store all the previous result right so we have a teepee here and the for the DP array here we do at zero right because we offered we're gonna initialize with zero and the length will be n plus one why because remember we have a on the only one here right on one here on the left side we basically it means zero it doesn't have any node right so but we still won't have we will still want to use this as one right because we don't want to be 0 we still want to have a value for the frizzy row for the 0 node right so that we can use that to the time with the other side that's why we need like 0 at the beginning and we know that 0 we want to give you the one right we want to make it a one big like I said we don't want a 0 times 2 will be 0 right we don't want to do it so we want to give it a 1 here 1 plus 1 times whatever on the right side we don't want to have any effect and that's 0 node and for the one node we already know the result right it's also but with OneNote you can only construct one tree right that's pretty obvious and so and now we will need to loop the rest after the numbers right for range now we have we need to loop from to right remember we already have the result for 0 and 1 so that's why we have 2 here and we'll loop until the end here so n minus 1 right I'm sorry n plus 1 okay remember what did we say so this number with the number I here so we want to pick all the possible numbers within the this range here right is all without missing did this range I here and we use each of them as a root to calculate and then in the end we stop them to sum them together so how do we pick the each note right so basically we just loop through from the beginning to the current I right so we're gonna use a J here in range right so we're gonna start from 1 right from start 1 2 I my I plus 1 why because we didn't want to start from 0 because 0 means 0 it means it doesn't do means there's no note right basically remember this one means the first number right the first number of the this I here and it is 0 means that there's no and we want to keep we want to pick at least one node as the root right so and what do we do here so with DPI here that's the DPI is the current result right fruit for this node right for the number for a number I hear right how many subtree are unique sub trees binary sub tree we can construct because we are summarizing order the result for the for each note right remember here so what do we do here remember the number that the number value itself doesn't matter we only care about how many notes on the left side and on the right side right since this is the index right so the index means and the index sorry I'm starting from 1 right so what then what does it tell us right so that's that the root index so any numbers from the index 1 to the current route number that's how many doesn't tell us how many nodes on the left side and so what is so how many nodes on the left side right that's the that would be the J minus 1 right that will give us J minus 1 it's the number how many numbers on the right side out of the corner roots J right and then we need 2 times the number of nodes on the right side right how many because we know we are recalculating for the current I right so on the right side there will be I'm on I minus J number sorry J right number of nodes right so left side number of nodes and the right side number of nodes and then we just do a product and then we just summarize all the results for each node for each root right within range I yeah basically that's it right I mean and then in the end we just return right we just return the dp1 DPN right because we're creating and minus 1 I'm sorry n plus 1 number of nodes and it's 0 base right 0 base which means that the end it will be the last node the last number right in range 3 v sub meet yeah well see that's pretty easy right but the thinking process is definitely not easy it requires some really deep thinking here ok recap what we have discussed right using the dynamic programming concept right and then watch the and then for each eye for the current eye how do we calculate it's up the sub the unique binary surgery for the current I we try between all the numbers right we try all the numbers within I we use each of them as the root since we since the root is different so we can make sure the result will be unique right and then we wait to what we do are left not right this is the this I basically left side I hear mr. James sorry this is Jay there'll be a left side of note and the right side of note so for each note we because we need to know we need to try each of the elements within I arranged to be then to be the root so we can have all the other results for each of that the Jay here we find how many nodes on the left side and how many nodes on the right side remember here so the not the value of the node doesn't matter all we care is about the number of nodes right and then we do product of them we get the current result of opted of the number of the unique the trees with I am sorry with J as a root and then we sum everything to that the I here and then we will get the result of I and then we can just keep using it from here then in the end we just return the last element in our DP array cool yeah hopefully I do a decent job or a okay job to explain this problem I know it's not a easy problem but try and understand it I think it's pretty cool problem yeah ok cool guys I think that's it for today thank you yeah bye
|
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
|
1,925 |
Al so this question is Con Square some triple and then given the integer and you want to satisfy a square + b square you want to satisfy a square + b square you want to satisfy a square + b square = C square and you want to return how = C square and you want to return how = C square and you want to return how many number of the sare triplet and you satisfy this right so let's the um the example so basically like from one all the way to this is a you know the range you want to say oh it does anything like one sare + 2 s does anything like one sare + 2 s does anything like one sare + 2 s this is 1 +4 it and it has to be the X squ right +4 it and it has to be the X squ right +4 it and it has to be the X squ right and this is five now we don't get a you know the x square for five right X has to be square root of five or plus equal xal plus equal to square root five then I'm X is all integer right so one of the solution for this is going to be 3 4 5 right 3 S + 4 square is actually what 9 + 16 = 25 + 4 square is actually what 9 + 16 = 25 + 4 square is actually what 9 + 16 = 25 = to 5 squ right so this is how it is 25 = to 5 squ right so this is how it is 25 = to 5 squ right so this is how it is right we can swap the X and Y so it's going to be 4 squ + 3 square and it's going to be 4 squ + 3 square and it's going to be 4 squ + 3 square and it's going to be 25 it's going to be 5 squ all right so uh one of the trick is want to be you know you add everything every square into the set and then you Traverse the set twice and then to see do I have you know um the value when a square + b s = c² so you want to find square + b s = c² so you want to find square + b s = c² so you want to find there's a c Square in the set so let's run it and then I mean sorry let's write it and then we can see what happen so integer something set new headset and then for in traversing for I to one less than equal to n and I ++ so to one less than equal to n and I ++ so to one less than equal to n and I ++ so set will add the I * I right so it's set will add the I * I right so it's set will add the I * I right so it's going to be a squ b squ a squ b square I mean sorry it's going to be I Square two uh I Square I + 1 square I + 2 square uh I Square I + 1 square I + 2 square uh I Square I + 1 square I + 2 square since this way so how do I do the a square is going to be a s set so this is going to be a square I'm going put like this a square right so in b² I'm going to transver B uh say again so b square so there must be a value if you have contains a squ plus b squ right so you have to use the if statement oh so this is the condition and then you have a counter ready if you contain a sare + b square ready if you contain a sare + b square ready if you contain a sare + b square it has to be c squ right you return result um wrong it submit yeah so this is the solution so space is all of time is all of this is actually what all of time all so it's n Square time is basic all of them and if you have question comment below subscribe if you want it and I'll see you next time bye
|
Count Square Sum Triples
|
count-nice-pairs-in-an-array
|
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2:**
**Input:** n = 10
**Output:** 4
**Explanation**: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
**Constraints:**
* `1 <= n <= 250`
|
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
|
Array,Hash Table,Math,Counting
|
Medium
|
2129
|
594 |
Oh 594 longest home angeles harmonious subsequence subsequent man i can it's a mouthful day we define it Hamada man this spelling things to hum come on ears heart we define a harmonious away there's in a way where the difference between them at its maximum value and its minimum while you it's exactly one now give it an injury aware you need to find the length of his longest homogeneous subsequence around or is possible subsequences okay cool twenty dollars that's tricky so subsequence I think I always get this one a little tricky is kind of I always mixed up subsequence and supper where your sub something did a lot of things we're like it matters where you skip letters or not it's a kind of tricky one I think this one is for me my gut instinct is that well n is gonna be twenty thousand so you can do like some N squared type thing so you could do in linear time and I use a hash table here where instead of matching just based on one number you want to match also the two adjacent numbers because the difference is exactly one yeah so as long as you're consistent the direction or I think that should be okay so let's get right to it wanted me oh I've been actually trying to do more Python 3 so let me try oops okay cuz I'll just type it again so definitely a Python three expert and I'm doing something really non pythonic definitely leave it leave a comment I doubly always you know I try to learn and keep on going and all that stuff okay so now just a D of X egos number of X's and X plus ones so I think that should make it clear longus and it's just ticking the backs of these dividers I think I could fly doing it when for comprehension somewhere actually did values man oh no it's not numbers the other one but uh by doing like a one line for finding thing I've been trying to get a little bit better about it so I mean I think this is right but uh there's some it first yeah okay let's just submit it maybe I could test it next time okay smaller oh it's exactly one knot at most one okay so I did miss wheet slash didn't read correctly okay so it's a slightly trickier think especially in this case where you know in that case we could just keep a boolean value just to kind of oh like a flag or something but it's essentially the same thing you just kind of keep the same the keep track of whether for a given number that it used both X and X plus one but and I'm glad that this was not a contest because then I would have gone now which I'm a car it and not so good plus five minutes so I shifted reading his heart okay how do I want to do I just keep them to a mask okay yeah I have my sound bring up loud and someone just ping be on text message I don't have it yeah okay look in the house right now okay I guess now you two need the keys what's the thing with the thing how'd I get porky and why use it's like that once we get other items what is items okay and I will explain this on the level because I think I do something like little bit weird but it's not a super easy read okay cool really slow pygar than faster I think it's I mean it's over and so you can't do time much faster but like it's interesting yeah not sure maybe I'll take a look at it later but I'm oh yeah but same frame which is that I guess we could have actually just hash to take one then uh yeah maybe I didn't need to do this actually maybe I could just do it in one pass and then just check the sum of the current number plus the last number or one minus one okay I mean so I definitely did unnecessary work here I was I think that's I mean one thing to be said is that sometimes you need to figure out when you need to mentally reset on a problem for me I just kind of hack things on top of a previous notion that I had which is why it's a little looks a little strange because you could have actually done something like just some easier thing may have been to like yeah it's like why you press and then also check to pus one version and stuff like that right so I think that this is more pie intuitive and then you don't need to see thing but given that we already did so what I did is just this is a bit mask containing the two things so we just distract this checks that it got both those bits to be true in that case that we do the max but yeah for trade this is PI like less error-prone so I'm error-prone so I'm error-prone so I'm I have tried to done something like this but I wasn't thinking that much I try to get it out as quickly as possible in which was to nine minutes I really thought slow maybe I was talking about but yeah but uh we always straight for it - my weirdness use of straight for it - my weirdness use of straight for it - my weirdness use of hash tables I think this is a it's a problem especially dispersion which I think why it's more intuitive to people to be honest probably uh yeah probably I could tell me anything that only uses a hash table and nothing else probably could come up in interview I wouldn't surprise I mean it this there's really something tricky about it this is not one of those case so I definitely actually just practices up and it's a easy so yeah that face should be in yours no and don't do what I did actually but uh yeah I mean is it straight for my friends I'm I could get into it that much cool hey sneaked oh I hope that's it made to say your name cosine of I says you know women could actually don't use whim I used Emacs fit up and I in general but I don't know that helps me no problem first I can then see my good way of some kind of fix I don't actually don't play around is that enough you still like that just colors how I stand it Wow there's a year max fing huh actually never no never fight about me that's kind of browsing actually maybe but I don't use I mean I used my matter keys and the medic you don't do much so I don't know what's there you max settings here maybe I look it I look into another time so I would admit that I've been doing this for half a year or so you know
|
Longest Harmonious Subsequence
|
longest-harmonious-subsequence
|
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.
Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.
A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[1,3,2,2,5,2,3,7\]
**Output:** 5
**Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\].
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** 2
**Example 3:**
**Input:** nums = \[1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
| null |
56 |
hello everyone welcome to sudokodus this is raveena and today we are going to look at lead code problem number 56 which is merging Towers let's start by looking at the sum here it says that given an array of intervals where intervals of I is start of I and end of I merge all the overlapping intervals and return any an array of the non-overlapping intervals that cover all non-overlapping intervals that cover all non-overlapping intervals that cover all the intervals in the input let's start by understanding the problem here we have been given an intervals list and inside that list we have several intervals where this is the start date a start time and this is the end time uh now we have to find some overlapping intervals here and merge them so let's look at this example this one starts at one ends at 3 whereas this one starts at 2 which is before 3 really and nz6 if you look at it they are actually overlapping one is from one to three the second is from two to six that means two and three and this particular interval is overlapping that means that we can actually make this one interval that starts from one and maximum of the two so maximum of either three or six which is 6. so we can make this actually one interval of one comma six and that's what's here looking at the second interval we have it's 8 comma 10. now let's see if this overlaps with any of the intervals that we have 1 comma 6 okay and we have 15 comma eighteen uh eight comma 10 is actually independent it is not overlapping with any of the intervals so we can keep it as it is that's why we can add 8 comma 10 to our output lastly we have 15 comma 18. this is also an independent interval because there is nothing overlapping at this point so we will add 15 comma 8 into our output lastly this is how the output is going to look it's going to be 1 comma 6 8 comma 10 and 15 comma 18. now let's see how we can solve this let me open my Notepad really quick okay so uh I'm having this example here and I did Shuffle some of the uh intervals and I will tell you why in your example this example really has the start time in the sorted way but it's not always the case and that's uh that's one thing that you have to keep in mind so what I'm going to do is I'm going to sort this list by the start time in the ascending order so that it will be much easier for me to merge it later so the first step is to sort it with the start time so let me do that now uh if I sort this to start time it will be 1 comma 3 2 comma 6 the next smallest start time is 8. so 8 comma 10 and lastly 15 comma 18. so after sorting this is what we get the next thing I need is my result list which I am going to call as moist okay I have this list initialized cool now I am going to go through each of the intervals and check is my merged list empty if it's empty then I'm just going to open my interval to it because I need something to start off the second thing that I'm going to check is my end time in my merge list less than the interval the start time of the interval that I have if that is true if my end time is less than the start time of the interval then I'm good it's independent right so for example if something ends at 2 and the other thing ends at 4 that makes my most intervals in time less than my star interval the current interval start time that means they are independent so if that is the case I'm just gonna append the interval to my merge list otherwise I am going to update the end time of my most of my uh element in the merge list I am going to take maximum of the end time that I have in the merge list versus the end time I have in my interval list now let's see how it goes I have I come across this first element I check is my most list empty yes it is okay I add it to my most list I'll go to my second element I come across 2 6 is my most empty no okay on to the second check my second check is my end time of merged list less than my uh intervals start time is 3 less than 2 no that means these are overlapping intervals and we have to update the end time of my element in my merged list and What's it gonna be it's going to be maximum of the two end times so maximum of 6 and maximum of six and three which comes out to be 6. so this is going to be six okay moving on to my next element I get 8 comma 10. I'm gonna check if my merge list is empty no it's not okay I'm going to check is my end time of my most interval is it actually less than the interval start time yes it is that means I can just append the current interval so I append 8 comma 10. moving on to the next one is my mostly it's empty no is my intervals in time less than the interval's starting yes it is that means that is independent so I add simply appended to my merge list when I reach the end of the list this is my output now let's see how we can convert this into code let me make this big okay so the first thing that I need to do is sort it based on the start time so I'm going to do intervals dot sort my key is Lambda where I'm going to sort it with the start and that's where I have X of 0. the next thing I have is my merge list which I'm going to just initialize now I have to go through intervals so for introvert in intervals for every interval in intervals I check if my merged list is empty or I check if my merge lets last us end time is it smaller than my intervals start time so I get my end uh end sequence by using most of -1 that uh end sequence by using most of -1 that uh end sequence by using most of -1 that will give me the last element and then this is the end time so index of one is less than my intervals start time which is 0 if that is true then I just append it to my merged list so I append my indoor to my moist list otherwise that means that they are overlapping so I need to update my last elements in time so I update my last elements in time with by taking maximum of my last elements and time and my intervals in time lastly I just returned the merged list let's see if we can run this okay I think I made a small mistake somewhere uh it's Max of moist of minus one or the intervals oh sorry it should be interval let me try again yes it runs so let me try and submit this yes it was submitted faster than 75 percent so let's talk about the space and time complexity of this particular algorithm the time complexity of this algorithm would be n log n that is because it takes n log n time complexity to solve so you perform any type of Resort keep in mind that it takes n log n time complexity that will make your life really easy when you are trying to complete uh you know when you are trying to calculate this time and space complexities so my time complexity here is n login for this sorting and then here it will be linear which is O of n so o of n log n plus o of n which is nothing but n log n so the time complexity is going to be n log n if we talk about the space complexity now just uh the worst let's think about the worst case scenario uh the worst case scenario is there are no intervals to merge at that point my in my uh the space required for my interverse list is going to be the same as my merged list and that makes my space complexity as o of n so my space complexity is O of N and my time complexities and login uh so thanks for watching uh give it a thumbs up or comment on it will really help my channel and please subscribe to my channel if you haven't already and you will find this score on my GitHub Channel I'll include the link in the description and feel free to connect with me on Discord as well have a good day
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
1,090 |
all right let's talk about the largest value from label so you have a value and label array and you also have num ones and use limit so use limits actually determine how many items you can use in the send label and num one is like how many uh number one you want to use right so just for example um red rubber here so symbol one use the mean is actually one so for every single label you want you don't you can only pick one right but you want to pick the largest one so you can return what so you can return the maximum score right so since i don't know which one is the largest one so i'm going to traverse the value array so i know five by four is represent one level one but well i only need one right i mean the largest one so it should be the five and two and three and so on right so here is it so two three and two are labeled two so you wanna pick the largest one which is three so now the number one is actually uh what three so you want to pick another one which is one so five plus three plus one is actually equal to nine right so for example two uh number one is actually three but the problem is what use them is two right so uh again number one uh level one only have five and three two three four uh four three two is what label of three so you can actually pick what pick the largest one right and uh what is this so it should be what five four three yards because the number one is three so you can only pick the largest one and which is three right so five plus four nine plus three twelve right but if you want to add this one then you will get the full item so this is not allowed you want to return the maximum right so let me just quickly go over to the solution so again i'm going to just put the value and label into one class so uh later i will use the priority queue and sort this the item the class i create and i'm going to store based on the value and i will just basically use another hash map to keep track of the label count right and this is pretty much a solution so here is it so i'm going to create a list of what i did i'm going to list this again i need across cross island and i'm going to say inbound and also what label right and then create a constructor email in label list allow is actually go to that let's of labels that are able to label right and i'm going to just fibers length of the values for length at plus 45 so what let's not add so i'll i can only add the item right so that's going to be what new item and then passing the value i commonly will say i right alright now i need a priority queue right sort the priority queue and this is going to be either right equal new and i'm going to compare give the lambda expression so from the biggest largest to smallest because we want what we want from the largest value getting poor right so it's going to be about b minus eight right all right so uh i need to add every single one of the list into the priority key right so i can use what at all right so it's going to be just what uh i'm going to play this right and i scroll this one all right so um yeah i need a return value for the maximum right now i need another hash map so this is going to just keep track of the label but i don't repeat repeatedly use the same level value right so now everything is set right so i can use traverse my priority q so while pq is not empty and also what and also the number one is actually greater than zero right so which is i can use uh whatever i want right um until the number is actually equal to zero so i can put the i mean break the value so i'm gonna say i then you go to what pu double so i pull the first one out of the pq which is the largest one and i put into my hash map based on the label okay so item the label from metal gear or default and then this is gonna be item.label and then this is gonna be item.label and then this is gonna be item.label come on zoom so i'm gonna keep track of the frequency of the label if i didn't have it then i initial to 0 and i increment by one so uh if i do have it and just increment by one right so if the method get i did not label if this is what if this is less than equal to the use limit so use limits actually how many items you can use in the same level right so if you have three item in the array i can use two of them right so in my hashmap you will keep track of the points right so this will be less than equal it's less than you could use limit right i'm going to start adding my item now right and also decrement my number one because i already use it right and this is going to be pretty much it right so let me see if i have any problem no all right so let's talk about the time and space so this is gonna be a space and this is gonna be a space so how many space the worst case won't be all of them storing every single item i don't represent what the value and label so the length of the value and then the end of the label should be all of them right so the worst case won't be all of them right for the full base for the time this is all open this is what priority q you have to sort right so it's unlocked this is all of them so this is all of them and so the worst case will come is going to be unlocking and represent end of the value and this is the solution and i'll see you next time bye
|
Largest Values From Labels
|
armstrong-number
|
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`.
Choose a subset `s` of the `n` elements such that:
* The size of the subset `s` is **less than or equal to** `numWanted`.
* There are **at most** `useLimit` items with the same label in `s`.
The **score** of a subset is the sum of the values in the subset.
Return _the maximum **score** of a subset_ `s`.
**Example 1:**
**Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1
**Output:** 9
**Explanation:** The subset chosen is the first, third, and fifth items.
**Example 2:**
**Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2
**Output:** 12
**Explanation:** The subset chosen is the first, second, and third items.
**Example 3:**
**Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1
**Output:** 16
**Explanation:** The subset chosen is the first and fourth items.
**Constraints:**
* `n == values.length == labels.length`
* `1 <= n <= 2 * 104`
* `0 <= values[i], labels[i] <= 2 * 104`
* `1 <= numWanted, useLimit <= n`
|
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
|
Math
|
Easy
| null |
215 |
everyone welcome back and let's write some more neat code today so today let's solve the problem kth largest element in an array so we're given an integer array numsend and integer k we want to return the kth largest element in the array by largest they mean largest in sorted order not the largest distinct element so we could have duplicates in this array and so when they say let's say a k equals one ray if k was one and let's say this array was sorted then that would mean we want the right most element because we want the first largest element if k is two we want the second largest element so not the largest element but the second largest element so that's how it works now the most obvious solution you probably could already come up with by yourself is just take the input array it's not necessarily gonna be sorted but we could sort it ourselves what would be the time complexity well it would be uh n log n right that's the time complexity to sort and since this is an array once we sort it we can instantly check the index that we want what index are we going to want let's say k is 2 what index would we want in nums we'd want the second largest right so instead of the largest we'd want the second largest so how would we do that we'd just take the length of the array minus k that would give us the index that we want to get to but this is a medium problem so you can assume that there are going to be different solutions can we do better than n log n well it turns out we can and one solution is using a max heap using a heap will be slightly better because we won't have to sort the entire input array what we can do with the heap is you can take an entire input array like this one and you can heapify it you can turn it into a heap and you can do that in o of n time but just because we have a heap doesn't mean we've necessarily solved the problem because we don't necessarily want the largest element in the array we might want the kth largest element so from that heap after we've already done an n operation to turn this array into a heap then we're going to have to pop from that heap k times because it's a max heap so we're going to pop k times so we can get the kth largest element every time you pop from a heap it takes a log n operation where n is the size of the heap how many times are we going to pop we're going to pop k times because we want the kth largest so this is the time complexity of the heap solution you can see it's slightly better than n log n depending on whatever k happens to be so in some cases it will be better than the sorting approach if k is relatively small and that's about as good as you can do in terms of worst case time complexity but there is a solution that's better actually if you want to know the average case time complexity and that's what i'm going to be focusing on because that's i think the more difficult of the three solutions that i've talked about so this third solution actually can be achieved with o of n average time complexity not worst case the worst case actually happens to be n squared so in the worst case it's not that efficient but in the average case it is pretty efficient what algorithm am i talking about well i'm talking about the algorithm quick select it's pretty similar to a standard algorithm that you may know called quick sort and if you haven't heard of this algorithm i'm going to be teaching it to you today if you have then you can probably implement this yourself let me show you how to do that now so let's take a look at this first example and like i said this algorithm is going to be really similar to quick sort and the main part about quicksort is the partition so that's what we're going to do first we're going to take this entire array and partition it into two halves right we're gonna somewhat cut it in half one half of the array is gonna be every value in let's say this half of the array is less than or equal to every value in the right half of the array that's how we're gonna partition it so how can we make sure that it's always going to be half well it turns out we can't that's why the worst case time complexity is going to be n squared and the average case time complexity is going to be o of n because what we're going to do is we're going to randomly pick a pivot let's just pick the rightmost element each time as the pivot value when i say pivot i mean this value is going to decide what goes in the left half and what goes in the right half so what we're going to do now we selected this as our pivot we're going to start at the beginning of the array and we're going to go through each element and we're going to compare each element to this pivot value so for example 3 is less than or equal to 4 right so what are we going to do we're going to make sure to place it in the left half of the array it's already in this spot so what we're going to do is basically just swap it with itself and then we're going to shift our pivot pointer over here this pointer is basically going to indicate every time we find a value such as this one or this one that's less than or equal to 4 then we can put it in this spot wherever this pointer happens to be and then once we've done that we're going to take this pointer and shift it again to indicate that okay next time we find a value like this one that's less than or equal to four then we're going to put the value in this uh position so in the actual code we're going to be doing this in place but i just drew an extra piece of memory just to kind of help you visualize it so we're going to take our three keep it in this spot three is going to go here our p pointer is now going to be shifted here originally it was over here but now we shifted it over here so now we're done visiting this element we're going to go to the next element 2 is 2 less than or equal to 4 yes it is so we're going to go ahead and put this value 2 in the position where p points at so we're going to put our 2 over here p is going to be shifted by 1. so let's put p over here we find a we go to the next element right one again it's less than or equal to four we put one over here and then shift our p value so one goes here p is going to be over here now we get to our first element that's not less than or equal to 4 so what do we do in that case we're going to leave this exactly where it is and again we're going to get to the next element 6 is again not less than or equal to 4 we're going to leave it exactly where it is and before we actually get to the last element we're going to stop so at this point we've we're basically done going through the entire array right and now our array looks something like this right we have a 4 over here and at this point what this p pointer tells us is that every element before the p pointer everything over here is less than or equal to this value four and then every value over here right p and you know all these remaining elements except for the last one of course all of these elements are going to be greater than 4 right because all of these are less than or equal to 4 so these must be greater than 4. that's what we mean by partitioning the array now notice just because we partitioned the array this is not in sorted order right it's not necessary the halves of the array the partitions are not necessarily going to be in sorted order but they are going to be partitioned so that everything here is less than everything here and one last swap that we're going to do now is we're going to take our pivot value over here which we selected as the rightmost element and we're going to swap it with whatever happens to be at this pointer right now so let's do that last swap we're going gonna put we're gonna replace this value with a five and we're gonna replace this value with a four so this might be a little hard to read but so the reason why we did that you're probably wondering why did we even do the partition in the first place so now we know all we know at this point is we have some value at this point our p this is the value we use to do the partition right now it's over here and we know that everything over here is greater than it and everything over here is going to be less than or equal to this partition value right that's good so now what we're going to check is where is that k value that we're looking for where is the second largest value in the array remember what we determined earlier that we can find that target value at the index length minus k right so what the length of this entire thing is six minus k which is two so we're going to go to index four this is zero one two three four this is index four so all we have determined at this point so far is there are two elements on this half of the array right so we know for sure that the second largest element must be somewhere here we don't know for sure that this is the second largest element or that this is the second largest element because remember these are not necessarily going to be sorted in this case they're not so we don't know it's over here but we know it's somewhere in this half of the partition right it's definitely not here and it's definitely not here right if the k value is different right maybe k was a really big number then we'd get length which is six minus let's say k was four uh then we'd get two right that would tell us that okay the target value is going to be in the left half of the array or it could even be such that let's say k was equal to three then we'd get length which is six minus k which is three then we'd get the value three so then we'd go to index equals three and then we'd see that this is that index right and then if it's ever this case right where that value that target value is exactly at p wherever that partition happened to be then we've actually found our result do you know why that's the case it's because we know for sure that this is the kth largest value in this case we know for sure right now that this value is the third largest value because we know for sure that everything in the left half is less than or equal to this value and we know for sure that there are two values that are greater than this value so that must mean that this is the third largest value right so we found the third largest value but we're looking for the second largest value so basically what i'm getting at is we're going to do this recursively so instead of basically we've eliminated that these cannot possibly be the result so now we're going to run the exact same algorithm i just showed you the quick sort partition on this part of the array until we find that result until we find k equals to the second largest element and when we actually do that partition on this we're gonna use 5 as the pivot we're going to say 6 is greater than 5. our p pointer is going to be here and then at the end we're going to take this swap it with whatever is with p so then we're going to have an array like looking like this 5 and 6 where this is our partition value this is where p is at and like i said all of this is actually going to be done in place so we will have the ultimate array and then we're gonna look at k you know the length minus two which is gonna find put us at this index then we're gonna have found our result five is the second largest element because we know for sure there's at least there's exactly one element that's greater than five right there's one element that's greater than five that must mean five is the second largest element so that's mainly how the code is going to work so if you recall how quick sort works it's a little bit different right let's just analyze the time complexity right now so with quick sort when you do the partition then you have to recursively run uh you know quicksort on the left half and on the right half which ends up giving us a average case time complexity of n log n but in this case uh the average case is actually going to be big o of n because we're not going to be looking at both halfs of the partition we're only going to be looking at most one half of the partition wherever we know that the target value happens to be and assuming in the average case every time we choose a pivot that pivot is going to be somewhere in the middle of the array it's going to be middle of the pack where half the elements are less than half of them are greater than it that's going to give us you can probably skip over this part you probably don't care but just to analyze the time complexity we're gonna have to iterate through the entire array once right so let's say that's an n operation then we're gonna have to let's say iterate through half of the array which is gonna be n over two operation then we're gonna have to iterate through half of that array which is gonna be n over 4. this is an infinite series that you might remember from calculus this infinite series evaluates to 2 times n which we know is linear so that means the average taste average case time complexity is big o of n that's the average case but we know that actually in some cases we could have a pivot value let's say six was our pivot value right six was here then when we partitioned the array our p pointer is actually going to be over here so and let's say we didn't find the result then we're gonna have to look through pretty much the entire array except one element and let's and it could be uh the array could be organized in such a way that every time we choose a pivot that pivot is always the greatest value so basically each time we iterate through the entire array we eliminate one value we iterate through the entire array again eliminate one value so that's an n squared time complexity in the worst case but like i said the average case is actually big o of n okay that was definitely a mouthful so now we are ready to get into the code it's not too difficult the code and like i mentioned earlier the easiest way to solve this problem is just two lines of code sort it and then return the length minus k you know that index and that actually happens to be faster on leak code than the quick select algorithm but i'm still going to code the quick select anyway because the average case happens to be more efficient and it's definitely a more interesting solution so like i said the index that we're going to be looking for the target index that we're looking for is going to be the length of the array minus k so what i'm going to do is just take k and reassign it to this just to make it easier for us because this is the index right k i'm going to use k as the index that we're looking for the kth largest element if the array was sorted so now we're going to do that recursive quick select algorithm and since every time the subarray that we're looking at and running quick select changes we're going to pass in two variables we're going to pass in the left and right pointer this tells us on which portion of the array are we currently running quick select on then when you actually implement quick select you choose the pivot we're going to choose the right most value because it's easy and we're going to have our p pointer initially being at the leftmost value so pivot is going to be set to nums of right p the pointer is going to be set to the leftmost position just like i showed in the drawing and then uh pretty much like the drawing we're just going to go ahead and iterate through the entire array except the last element so we're going to go from index left all the way to right is non-inclusive in python so it's right is non-inclusive in python so it's right is non-inclusive in python so it's not actually going to reach the right index and we'll go through each element if this element nums of i happens to be less than or equal to the pivot value then we're going to swap it with the left index or not the left index actually the p index right wherever we're putting uh the partition values so if this is the case we're gonna set nums of p equal to nums of i and we're gonna set nums of i equal to nums of p you can do that in one line in python you don't need a swap helper function we can do it just like this so we're just swapping these two values it's pretty straight forward remember every time we do a swap though then we want to increment the p pointer because next time we do a swap we want to put it in the next position okay so that's the partition and the last part of the partition is to swap the pivot value with the p index so we're going to set nums of p equal to the pivot value and we're going to set nums of right the you know what this pivot value is currently in the rightmost position we're going to swap that with whatever happens to be in nums of p so nums of right is going to be set to nums of p this might be confusing maybe because i use pivot so you can actually rewrite it so instead of using pivot i could actually just go ahead and write nums of r we're just swapping the rightmost value with whatever happens to be at nums of p right at our p index okay and once that is done then we potentially may have found a solution or we may not have found a solution so let's check is our k value less than p the k is the target index we're looking for if it's less than p that means we have to run quick select now on the left portion of the array because we have to look for a smaller index so we're going to call quick select and for the indices we're going to pass in left remains the same but the right pointer is now going to be shifted towards the left right is now going to be set to p minus 1 because we can look at the left portion of this array now this partitioned array that's if k is less than p we could have another case and we're actually going to be returning this value whatever happens to be and the else case is if uh k is greater than p if k is greater than p that means we have to look in the right portion of the array so in that case we can return quick select looking at the right portion of the array which means our left pointer is going to be changed to be p plus 1 now and our right pointer is going to stay the same that's the other case the last case else is if p is exactly equal to k in that case we can just go ahead and return nums of p because we know for sure p is the kth largest element and yes since all of these end up returning something that is the entire code that's the entire quick select algorithm now all we have to do is actually call it so we can call quick select for the pointers of course we'll just pass in zero for the left boundary and for the right boundary we'll pass in length minus one so that we can run quick select on the entire input array and then return whatever the result is so i'm going to run it to prove to you that it works even though since the worst case is n squared and some of the uh test cases on leak code actually happen to be you know poor cases for quick select it doesn't run very efficiently on some of those test cases so this actually isn't very efficient on leak code but you know this is definitely a good algorithm to know in the average case it does beat the sorting approach so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
119 |
In this video, we will see another variation of Pascal's triangle in which if we are given a row index and we have to print that entire row of Pascal's triangle, then how we can do it efficiently. In the last video, we saw that if we have to print this entire row If we want to print the complete Pascal triangle then how can we do that? In this video we will be asked to print a row index like Y 0 1 2 3 4 In this way we will be asked to print a row like if we are asked to print row index Th So we have to print this entire row 131. Now what is one way? We build this entire Paas triangle and then we return the third index in this row, but with this we saw what our leti comes n s but because We have to print only one single row, so we can do this in this, how to do that, today we will see which is a row of Pascal triangle like I take this 0 1 2 3 4 This is my third row so this We can also represent the element in the form of combination, how its starting element will be 3S0, first element will be 3S1, next element will be 3S2 and next will be 3S3. In this way we can represent the third row. Similarly if I have the fourth If we want to represent the row then what will happen 4 c0 4 c1 4 c2 4 c3 and 4c 4 In this way we can represent this row 4 c0 what will happen to us one 4 c1 what will happen to us four 42 what will happen to us 4 * 3 div Ba 1 * 2 i.e. 6 4 * 3 div Ba 1 * 2 i.e. 6 4 * 3 div Ba 1 * 2 i.e. 6 similarly 43 what will happen to us is equal to 41 and 4 sf what will happen to us and 14 6 41 In this way our fourth row will be then what will happen to each row like if I take arrow then nc0 nc1 nc2 up Two up to n s a In this way our entire row will be, so if we know that the value of our row will be then now we do not need to make the entire Pascal triangle, we will simply calculate these values efficiently. Now what is NCR? Your n * n - 1 * up to up what is NCR? Your n * n - 1 * up to up what is NCR? Your n * n - 1 * up to n - r + 1 is what will come at the top and what will come at the to n - r + 1 is what will come at the top and what will come at the to n - r + 1 is what will come at the top and what will come at the bottom is 1 * 2 * up to r. bottom is 1 * 2 * up to r. bottom is 1 * 2 * up to r. Our r will be as many terms as this and will be above one. Our terms will be below till r. Division of these two will be our NCR, like if I have to take out 7 c2 then what will be 7 * 6 terms will then what will be 7 * 6 terms will then what will be 7 * 6 terms will come above and below will be 1 * 2. Similarly if come above and below will be 1 * 2. Similarly if come above and below will be 1 * 2. Similarly if I have to take out 73 then what will be 7 * 6 * I have to take out 73 then what will be 7 * 6 * I have to take out 73 then what will be 7 * 6 * 5th term of ours will come above and what will come below 1 * 2 * 3 If it will come in this way, then * 2 * 3 If it will come in this way, then * 2 * 3 If it will come in this way, then what is the one way, whatever we have to calculate AC and A2 A3, whatever we have to calculate, we should use it to calculate each one. For this, we should put a loop or what is the other way because we have to remove the AC nc1 nc2 up to nc1 like this, so if I can use nc2 to remove this nc3, then my operation will be off one like my 7 s2 is this. What is 7 * 6 / 1 * 2 and what is 7 in 3? This 7 * 6 / 1 * 2 and what is 7 in 3? This 7 * 6 / 1 * 2 and what is 7 in 3? This factor is common. 7 * 6 / 1 * 2 is factor is common. 7 * 6 / 1 * 2 is factor is common. 7 * 6 / 1 * 2 is common. All I have to do is multiply this value by 5. And divide by r basically one term extra I have to add similarly 7c what I have to do is this is my value will come 7 c is the value of 3 which will come into 4 divide by 4 this is what I have to do is one term I will add here and one If I have a tam here then this is the value that I just have to multiply by four and divide by four. So using this thing we can simply calculate all our values in a treble. What will we do can simply calculate all our values in a treble. What will we do can simply calculate all our values in a treble. What will we do in the beginning we know It is nc0, it is always one, so we will put one in it as the first element. Similarly, last element n is also your one. We will put one in the last element too. What do we have to calculate? The elements in between are nc1 nc2 nc3. And so on, we have to calculate the elements in the middle, so nc1, what will be our one term above n above and one below, we will calculate nc1 from this, then we have to calculate the next term nc2, then what will come n-1 above n-1 what will come below. Aa will come n-1 above n-1 what will come below. Aa will come n-1 above n-1 what will come below. Aa will come, we will multiply only by this term, then when we have to calculate nc3, what will we do, A minus 2 and below, basically what will be ours, in each term, A minus Aa will be in the multiply above, divide by Aa, this will be our factor. By which we will multiply the number and our new term will be calculated like if from this I have to take out A4, then what is the value of A mine A, how much is P diva and what will become of my n3 Ba and what is my value on Y, then this is Every time we will multiply with the formula and we will get our next term. Once we see its code, in the code we were given n that we have to print the eighth row and it was a zero index row, so how many elements will we have in this row. There will be one in row, two in a, how many will be in i + 1, so we have taken a vector of size n + 1 will be in i + 1, so we have taken a vector of size n + 1 will be in i + 1, so we have taken a vector of size n + 1 in which we will store our values and will return it in the last. will store our values and will return it in the last. will store our values and will return it in the last. Now what we have to do is that we know our starting point. Element zero, index and last element will always remain one, so we will initialize them from one, after that what will we do, we have to calculate the remaining elements from one to n and those elements we had seen how to calculate n - r + 1 diva ba r This was our n - r + 1 diva ba r This was our n - r + 1 diva ba r This was our multiply factor, with this we were multiplying and which one we will multiply, initially we will take the value one 1 into this value, starting our will be n / 1, after starting our will be n / 1, after starting our will be n / 1, after that our result will be n / 1 By what will we that our result will be n / 1 By what will we that our result will be n / 1 By what will we multiply it n - 1/2 Then the multiply it n - 1/2 Then the multiply it n - 1/2 Then the result we will get is by what will we multiply it n - 2/3 In this way every time we will n - 2/3 In this way every time we will n - 2/3 In this way every time we will get a new term which we will store in our vector In the end we will have all Once the values have come and we will have all Once the values have come and we will have all Once the values have come and we will return them, then simply we have to multiply the formula of our combination by n - r+ 1 formula of our combination by n - r+ 1 formula of our combination by n - r+ 1 divided by r every time and we will get a new term and what will be our total result, we are simple here. By putting a loop of size n, these operations are our constants, we are doing only one multiply, our constant operation is our string blast, what will come of A and how much space will come, we have given off here to store the answer. A space of this size was taken, apart from this we did not take any extra space, so will our space complex also come off? Thank you guy.
|
Pascal's Triangle II
|
pascals-triangle-ii
|
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** rowIndex = 3
**Output:** \[1,3,3,1\]
**Example 2:**
**Input:** rowIndex = 0
**Output:** \[1\]
**Example 3:**
**Input:** rowIndex = 1
**Output:** \[1,1\]
**Constraints:**
* `0 <= rowIndex <= 33`
**Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
| null |
Array,Dynamic Programming
|
Easy
|
118,2324
|
215 |
hello everyone welcome to sud Coda this is Ravina and today we are going to look at problem number 215 which is K largest element in an array now let's start by reading the problem statement it says that given an integer array nums and an integer K return the kth largest element in the array note that it is the kth largest element in the sorted order not the K distinct element and it also asks us that can you solve it without sorting so if you look at this example number one we have a nums array and then we have a k so the problem statement says that we have to get the K largest element from this array provided that the nums array is sorted so for example if we you know sort this array uh and then we get the second last element since K is two so we get this second last element from that array so let's see the problem statement and also see how we can solve this let's move on to the notepad so I have this example uh example number one from lead code uh so the initial thing is uh you know the first thing that comes to our mind is uh we have to sort the array and then we have to get the second last element so one way of going through it is you know we just sort the array so we have one 2 3 4 5 and six and since our K is 2 so we want the second largest element so if we go from right to left so this is the first largest element and then this is the second largest element and this is our answer but if you look at the problem statement it also says can you solve this without sorting how do we solve this uh without sorting so there are uh there are different ways of solving this but um I'm going to solve this using Heap the only reason I'm using Heap is because I know there is a quick select uh option of solving it which is even you know better with time complexity but I think it's uh a bit difficult to come up with that solution during interview and the Heap solution is actually more intuitive so that's why I'm going to go with the Heap solution so that you know we have to make our lives easy in interviews right we should be able to explain to the interviewer what we are thinking how we are progressing so I think this is an easy one to uh do it with the use of Heap and it also demonstrates your understanding of it so let's go ahead and see how we can solve this using Heap okay so I have this array with me uh what I'm going to do is I'm going to go through the array and as I go through the array I'm going to push the elements onto my Heap and the one condition that I'm going to check is that once my length of Heap is actually greater than K which is uh the number that is provided to us uh we are going to pop from the Heap now how does it look like okay so first I am here I'm pointing to three so I add that to my Heap so this is my Heap okay so I have one element in my Heap I'm going to check is my length of Heap so I have you know length of Heap so right now it is one so is my length of Heap keep uh greater than my k no it is not 1 is not greater than two so is 1 greater than 2 no okay so I go on to my next element I see2 so I added to my Heap so you know right uh in python or uh in Python we have minimum Heap so whenever I add an item to my Heap it is going to rearrange itself all right so it is going to look something like two and then three Pro uh because two is going to be the minimum so it's going to come on the top so that is going to be the root uh then again you know my uh now my length of Heap is going to increase so right now if you check my length of Heap is two there are two elements in the Heap so my length of Heap is two I will check is my length of Heap greater than K so is 2 greater than two no so it's 2 greater than two no it is not okay I go ahead into my list I get one so I add that one to my heat so when I add this one to my Heap it is going to rearrange itself so it is going to be 1 2 and 3 so this is how the Heap is going to look and then my length of Heap is going to change since we added one uh element to it so it is become it is going to become three now we will check is my length of Heap which is three greater than my K2 U yes it is we have one extra element in the Heap so what we are going to do is we are going to pop from the Heap now why is this important okay this is important because if we do this we are going to have at the most uh k+1 elements in our Heap the most uh k+1 elements in our Heap the most uh k+1 elements in our Heap okay so for example since we are checking if the length of Heap is greater than K that means at the most there are going to be 2 plus one that is three elements in the Heap and once we find those we are going to pop from the Heap and how does this not affect our solution it's because we have to find the K largest element so here even if we pop one we still have two elements which are larger than one so that means it is not going to affect our solution it is not going to affect it in a negative that we are popping something that we need no we don't need one because one is less than two and three and since we want the largest second element we can pop one okay so we are going to pop one from this Heap so once we do that we are back to the Heap where we have two and three now we go to the next element we get five we add that to our Heap so we have two three and five so once we add that to the Heap our length of Heap actually becomes three again now my length of Heap is three I will see is three greater than two yes it is okay so I pop one element from the Heap so two will be popped okay we do that and then we end up with three and five now we encounter six we add that to our Heap so I'm going to draw my Heap again so 3 5 and six now I check now the length of my Heap is again three so length of Heap is again three so I check is three greater than two so length of Heap greater than my K which is two so is three greater than two yes it is okay we pop from the Heap so this is going to get popped after that is done my Heap is going to look like five and six with two elements in it okay I go on to my next element which is four I add that to my Heap so this time I don't have to redraw it because it's in the right sequence so my Heap no it is not my bad so I added to my he Heap so it becomes 4 5 and six okay so now the length of Heap is again three I check is three greater than two yes it is okay we pop this element four now after doing this ultimately my Heap looks like this and if you see I'm at the end of my array so once I'm at the end of the AR what I can do is I can simply return the topmost element in my Heap so I return five and you know what that is what we want so we find the K largest element in the array so I hope this explanation was helpful now let's see how we can code this first thing that we need is a heap so I do Heap and then I go through all the elements in my array so for every number in nums what do I push to my hep so I do Heap Q dot Heap push and then here I have to provide the name of my Heap which is this Heap and then the item so what do I want to push the number that I'm iterating through okay so once I put uh push to the number what do I check right I check if my length of Heap is greater than K if that is true then we pop from the Heap so we do Heap dot Heap pop and then we give the Heap that's how you do it in Python so uh I pop from the Heap now once this for Loop you know uh finishes what do we have to do we just simply have to return whatever is on the top of the Heap which is heap of zero so that's really the solution it's very simple it's very straightforward it just has to uh do with your understanding of Heap and how can you use it uh there are a lot of problems on lead code that use this logic so I decided to stick with it so that you know uh I can find relative problems and then I can help you guys to have a set of problems that follow a set of solutions okay uh so I am going to run it let me expand this okay it's able to compile so I submit it's taking some time all right so it is as you can see it is accepted uh now let's talk about the space and time complexity uh as we briefly touched the uh time complexity is going to be here n log K why because uh if you see in the for Loop we are going through every element so that is n elements and then here if you see the Heap is having how many elements at the most it is going to have k + 1 so if you most it is going to have k + 1 so if you most it is going to have k + 1 so if you remember whenever we had you know length of K great uh length of Heap greater than K we pop it from the heat so that means that there are at the most k+1 means that there are at the most k+1 means that there are at the most k+1 elements in the Heap so it is going to take log of K time to uh perform the heapy function where it arranges itself arranges the elements in the Heap and so the time complexity is going to be n log K because n because we are iterating through all the numbers and log K because when we push to the Heap performs uh you know its own sorting where it brings the minimum on the top and that is what's happens when you do a heap dot push so that's the time complexity what about the space complexity here is going to be K because at one time Heap is storing k + 1 and since we drop is storing k + 1 and since we drop is storing k + 1 and since we drop constants uh when doing complexities it is going to be K because at the most their Heap is storing K elements okay so I hope this explanation was helpful I hope it was intuative uh if you like my video please like or comment below uh please subscribe to my channel if you would like to see such Solutions uh in the future and I also have my python course uh which is coming up this week so stay tuned and look forward to your feedback on the videos also the code is going to be on my GitHub as usual I will link the uh I will link the GI uh GitHub link below in the description and also uh I have a Discord channel so feel free to join that if you have any questions we can connect and yeah uh so thank you so much for watching and I will see you next time bye-bye
|
Kth Largest Element in an Array
|
kth-largest-element-in-an-array
|
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
324,347,414,789,1014,2113,2204,2250
|
539 |
we're going to look at a legal problem called minimum time difference so given a list of 24 hour clock time points which is in hour and minute format return the minimum minus difference between any two time points in the list so you can see here we have time points in a list of string right and then we want to return the minimum time difference in minutes so you can see here we have two time here so one of them is this one and the other one is this one right so you can see that if i were to convert this into a minutes right if i want to convert this one right here to a minute um basically if i were to calculate right it's basically just going to be 23 times 60 right because they're 60 minutes in an hour plus 59 which is basically how many minutes we have which is going to be uh 14 39 right so 14 39 and then we also have zero so this number right here could all could be two things right it could means that we have a zero minutes right or we could have 24 right which is basically 24 hour uh times 60 minutes in an hour which is going to be this number right here right so you can see here that if i want to get the difference between those two times right those two time points it's going to be this number minus this number which is basically 1439 or this number minus this number we're like the absolute value difference between those two numbers right in this case it's basically one so in this case this minus this has a smallest value right so basically it's one so you can see here the output is basically one right that's the minimum time difference between those two times there and then you can see here we also have another one right where you can see we have the same thing but we have another uh we have another um time point right time point which is exactly the same thing as this right exactly same thing as this so we can see here the minimum time difference is not going to be one anymore right so it's actually gonna be zero because the time difference between this one and this one is actually zero right because in this case 1440 minus 1440 or zero minus zero is basically just zero right so for the output in this case is zero so basically what it means is that we could have duplicate timestamp right in our time points so that's the number one thing that we had to consider is that if we have a duplicate timestamp right a duplicate time points um then guarantee that the minimum time difference is zero because there's nothing smaller than zero well in this case a uh we're talking about the difference right the positive value right so you can see here um we're guaranteed to at least have two time points in the array and then timestamp for each every single string it's guaranteed to be in this format okay so in this case like i just mentioned before the other the first thing we have to consider is duplicate right if we have duplicate in our time stamp then we're guaranteed that we going to return zero okay so then what's the other thing that we had to consider right now we know how to compare the two to time stamp or two time points what's the other thing that we had to consider to solve this problem well the other thing that we had to consider in this case is basically that the time works around right so in this case you can see here we have this array right and these are time stamps and if it converts to a uh minutes right this can be zero or it could be 1440 like uh 1440 like i just mentioned and this one is basically 240 and this one is 1320. so in this case what you might be thinking a one way to solve this problem is we can be able to sort the array right based on um you know based on the minutes right after we convert each time stem to minutes and then we sort it and then once we sort it we basically convert compare the current time with the previous time or the nest time right and then we try to get the time difference and then we're going to have a variable to keep track of the minimum time difference throughout the array but the thing is that um in this case because you know that the time works around right so in this case what we also have to do is we have to com compare the end time with the start time right so in this case 1320 comparing with this one right so this one right here could be zero could be this one so in this case what's gonna happen is that uh we're gonna compare both ways so this one this number right here minus zero is basically this value or it's gonna be 1440 minus 1320 which is basically 120 right why is it getting 240 is because this one minus this one is 240 right and this one minus this one is going to be greater value so that's why you can see the minimum is 240 but the ideally is basically we want 120 right so if we keep going with this track right if we were to solve this problem using um sorting right based on what after we convert all the timestamps into minutes and then we sort the array based on these minutes then in this case this will give us a time complexity of the login right so we can do better is we can be able to do something similar to what we did before right we can use bucket sort and then be able to sort the array um or sorry not sort of array basically we can be able to convert times right convert these um just like what we did before like we basically convert times to minutes right we added onto the set just like i mentioned we all we have a consider is that if this minute if the current minutes is contained in our set right then what we're going to do is we're going to return zero right because in this case if there's duplicate times then we're guaranteed that we're gonna have um the minimum difference is gonna be zero right so then what we're gonna do is we're basically just going to go from the maximum minutes to zero okay um notice that we're gonna use a set here not a you know not a boolean array with a size of 1440 because in this case let's say the time points that were given is between zero and hour one then in this case we don't really need that many minutes right so in this case um what's going to happen is that hash set is more flexible in terms of space so if we don't really need that much of space we don't really uh need to create them right so what we're going to do then is um notice that just like buckets or what we did before we have to iterate from the max minutes right to zero so we're guaranteed that we're going you can go from zero to max minutes or the max minutes to zero right and notice that the max minutes is basically the maximum throughout the entire ray not 1440 right if you start from 40 just like i mentioned if the timestamp or the time points that we have is only from zero to hour one then we don't really need to go from 1440 iterate all the way down to zero right so what we need is we need to go from the max minutes right that we have in our list down to zero so what's going to happen then is we're just going to have a previous minutes right and then we're going to have a variable keep track of the minimum difference because we're going from the max to zero and we're using the hash set to keep track of that right set to keep track of that so in this case we can get a constant lookup time right so what we do is that we're going to iterate from the max minutes to zero and then if set contains this current minutes right what we're going to do is that we're going to see if previous is it does not equal null if it's not null we have to check two things one is we check to see if the previous minutes minus the current minutes right the previous minutes minus the current minutes um basically is the difference right or in this case let's say we have a situation like this right 22 and then zero right we also have to check the other way around where we basically just say current minutes plus 24 times 60 right so you can see we're going both ways here right one is we can be able to circle around or the other one is we can just comparing with the previous minutes right and then we iterate through the array and then what we're going to do at the end is just like i mentioned we have to do our final check and at the end we're basically trying to get the minimum difference returning minimum difference right like this last check or the final check here is basically trying to compare the maximum minus right the last uh minutes with the first or the smallest minutes right the maximum minutes was the smallest minutes comparing right get the minimal difference uh get the difference and then of course we also have to update the minimum difference right so basically you can see this is how we solve the problem and you can see the time complexity for this one is going to be big o of n where n is number of elements that we have in our list
|
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,431 |
hey everybody this is Larry with a shirt on it is April 17. uh hit the like button hit the Subscribe button join my Discord it looks like today is a easy palm so I'll probably try to do a premium problem just to kind of you know get my reps in a little bit today's problem is 1431 kids with the greatest number of candies uh yeah the end kits with candies you're given an integer away candies where each candies survive represent a number of candies I've kit has and it ended your extra candies to know the number of extra candy that you have we turn a brilliant result of length and where result I is true if after giving all the I've kid or the extra candy they have the greatest number of candy all the kids or of course otherwise no downloadable kids can have the num uh the greatest number of candy okay so basically I mean I yeah I mean I it is easy I suppose um I think it's just max about yeah it's just getting the match of the way right like I think sometimes I double check these things it's getting the Max and then now for uh X in candies If X Plus extra candies is greater than or equal to MX then yeah then enter that append true or maybe you could even just you know do this conditional here right oops uh and that's pretty much it right Maybe hopefully because I don't know if I misunderstood this but uh well that was pretty quick uh thanks for joining us everybody uh I mean I don't really have much to say about this one um to be honest because basically I mean it is easy and I guess it is a warm-up it is easy and I guess it is a warm-up it is easy and I guess it is a warm-up usually for me um I mean this is a good practice to um when you see a Yeezy problem I mean I think the couple things I you know if you are watching this video a couple things you can do one is kind of practice reading and understanding as fast as you can and that's kind of always going to be tricky but uh but that is going to be a especially if you do competitive interviews you probably get away with you know because you're communicating with someone else you're talking you're chatting you're having fun maybe uh but if you go with competitive programming a lot of it is reading and just reading it as quick as you can and then um try to figure out the code that you want to write right and here I'm just gonna give you some generic advice because this video is too short otherwise uh not that I usually care but you know trying to figure out your patterns yourself and figure out who you are right um as a programmer as a competitive programmer as a implementational implementer uh you know there are some things that um I think a trap that a lot of uh new Engineers or software Engineers uh get into is that they minimize the number of code or like they do some kind of like code goth you know you want to get shortest code or something right um and the thing is that there are two things one is that the thing that looks really clever because you're like oh that's really smart because I couldn't have thought of that well that's usually the reason why I mean or you know that's actually not what you want because uh yeah it usually makes means that you have to actually understand something to read it because basically the code that you want to write the right the thing that I always say is that the code you want to write um especially in production and stuff like that's readable is the code that in a way that you can everyone who reach it can imagine themselves writing it and that's how they can understand it so easily right um that's one thing that I always say about that um the other thing is just figuring out I mean this is maybe a little bit more competitive programming um it's just figuring out uh but again learning who you are and what that means is that um for me part of how I decide to implement stuff depends a little bit on a sort of a probability of how easy it is for me to make a mistake typing that out as quick as I can right like for example um if you really think about it this can really be a one-liner especially in really be a one-liner especially in really be a one-liner especially in Python but the reason why I write it out is because uh well two reasons one is that if I have a typo it's easy to debug if I need to but two is that I have fewer chance of making a typo um don't you find me long enough maybe that's not low enough but that's besides the point um so those are the things that I would kind of recommend you to do and in you know together that's gonna compose a lot of your rating if you care about that but just about speed right um speed is about getting especially on the easier problems anyway it um because yeah it's about solving it and reading it and doing it as quickly as you can in a way that you don't have to like second guess yourself right um as much as possible anyway that's how you shave you know a minute here and there and then it adds up and the other thing is that if you are you know are going hard into competitive um every minute counts uh at least like you know talking about my sticking points mostly because I don't practice to be frank so I mean but like if I were to practice one thing I do notice about myself is that um on the later problems um sometimes like on a more difficult competitive program it's not lead code so say code force or something like this um I just don't have much time to kind of really go through it right uh and so some of this is practicable meaning like you like as I always say you make observations and stuff like that and then you go into it the other part is that giving yourself enough time to be able to solve them and that's when you know you have to solve the first two or three problems easy to give yourself time to do it and obviously it also factors in penalties and stuff but yeah anyway kind of a little bit of Sidetrack but definitely my point here is that um you know if you find yourself beyond the level where you find Easy Like if you find easy it's actually easy like you can do it every time like that's saying 95 of the time maybe some five percent of the time is you know the problem is just really hard to read but um when you say easy uh especially on these daily problems just try and do it as fast as you can uh by reading as fast as you can and then kind of see you know where you can make improvements right um it's all about feedback loops anyway that's what I have for this one I'm gonna do a premium after this so definitely hit the Subscribe and all those buttons and just click on The View button or whatever I don't know anyway uh happy Sunday happy Monday will depend on where you are and when are you watching it so stay good stay healthy to your mental health have a great rest of the week I'll see y'all later and take care bye
|
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
|
332 |
hey everybody this is Larry this is day 28 of the LICO daily challenge hit the like button to subscribe and joining this core channel let me know how you feel today we're gonna go but we construct our territory I'm so euro time we love this channel I'm actually trying something new where I changed the order of things but I do the explanation first and then you could watch me live solve this form afterwards so reading this problem my first thought it's that it is audience and why do I think it's all in path because well you have to use order ticket once and only once and a ticket is basically an edge connecting between a and P between point a and B right and from that you and you have to use all the tickets and then order take it to form a valid iter a meaning that there is a loyalty in path so from that's pretty much how you solve the problem and it's a path because you have to start at JFK and it could be a psycho at the last element is JFK but it has the matter so that's kind of the idea of how you solve this problem and there a cup of algorithms to do solved Orion paths I think it's a little bit of a weird problem for an interview because not everyone knows on an path and also if grey put it you know so the album that I use is core I some guys algorithm I'll put a link below on to the Wikipedia page but the point being that the album is named after someone right it's so like if you didn't already know it can you come up with it in the scope of an interview probably not but that's okay what do you even think you needed I probably I think that it's not super necessary I think that yeah I mean if you have you know practice a lot of things and you're comfortable of everything else then sure you don't know and then maybe just add it to your list I think for an interview one is way unlikely to is that given if it comes up there just so many that you're probably not as strong with dad you can show up with like binary search or something like that right so for that reason I don't like this farm for an interview for competitive programming it comes up here and there so enough times that you should probably know it or at least know to where to google it or something like that but yeah so the code is a little bit iffy and again you'll watch me code it later but basically I just go through it and this is it's almost not worth me explaining my code in the sense that this is just an implementation after Algrim and I made some changes so then it uses an adjacency matrix just to make it slightly easier but it makes the complexity way more complex or it makes the running time a little bit slower there you know for this form it was good enough and yeah that's all I have for this problem now you're gonna watch me miss try stuff in life everybody this is 28th day of the decode June daily challenge let's get started this is the live stream we construct I turn we construct I Terry given a list of airline tickets represented by pair of departure and arrival Airport from - we construct die arrival Airport from - we construct die arrival Airport from - we construct die Tyrion order or die - all the tickets Tyrion order or die - all the tickets Tyrion order or die - all the tickets belong to man could depart from JFK that's me actually does die Tyrion must begin in JFK if they're multiple valid I terrors you should be turned I tell it as their smallest lexico order when read as a single string okay oh yeah puts represented by three capital letters you may assume that or tickets form one at least one valid I tell you must use all ticket once and only once oh you have to use oil tickets so this is basically Wow hmm so this is basically or a Lydian path it's a graph Phoebe can strut and yeah I mean I think I'm gonna just get right to it's kind of tricky though mostly because I haven't done it in a while so I don't actually remember exactly the implementation but the idea is that you start at JFK and because that there's at least one valid I Terry then we know that there's a nine million path and from that you did a couple ways to do it the really tricky way is to kind of construct psychos and then combine them in a way but I won't do I'm gonna do it the greedy way of basically you take a path and this is you know me try to figure it out from first principles which is that you take a path and if taking that path allows you to still have an or lydian path then you take that path otherwise you don't take that path yet right and what I mean by that is for example if you get a case like maybe there's an other thing that goes to SFO and then goes to JFK right like maybe is this input but there's another path for mess of SFO to JFK then you have to do the JFK class because otherwise you would not be able to go to Atlanta because there's no other way to go SFO I think that's that for this problem because we're guarantee that there's a path I think that it maybe is okay but I would say that also it is not a great interview question so yeah because I don't think or Lillian paths should be an interview question thing but that's besides the point so now I'm gonna try to prove it again from first principle in from Denver Ariens that I remember about alidium past so I don't know the implementation be quite right the first time because I'm pretty rusty bad because it doesn't come up that often but yeah but let's go through the tickets first right so let's have two arrays and by weight I mean the hash tables because I'm lazy I like it this way a little bit more I don't need extra stuff so now I'm just setting up there in degrees and out degrees of the tickets so in degree of me plus one and then out degree you plus one yeah and then I just that's just convert this to a and which record adjacency list so now okay so now that we have this up we have to start from JFK okay so one thing to know from this is that we can go for other keys in edges no yeah I think we just have to keep track of all the names that we saw is it insert okay I don't know if it gives an error on dupes and it's been a while I spelled everyone collections that default it I don't know how it's for the wrong but uh yeah okay so it doesn't crash that's good and now for each one we know that one started at JFK and now we have to figure out where we end up right and so the answer is either we end up in we will end up in the number that has an odd number out degree right yeah okay and the reason why I remember this is that if you know for every node that you have four already in path you have to go outside yep you know if someone comes in and then someone has to go out way the only place where that is not going to be the place is when you set out to Queens you go to I guess in degrees you go to optically maybe that's easier to represent right then that would be your answer and that's JFK because that's where you're starting so as soon as we do name last we should be okay what an annoying problem but yeah but this is just backtracking then no I mean it's not quite backtracking you just do an HR over time but yeah this is first is go to FK let's just do last is equal to none and just if this is still none and time into last place we're going to is JFK let me just do this whole circle loop thing so then now we sort every yeah let's that sort all the edges so that we always try to go from the you know what's optimal in terms of lexer graphically showed earlier that is yeah oh you are right thanks okay so then now we start at JFK and we can do it this way and because this graph is always good we just have to make sure that the entire graph is still connected because if it's not connected then we're not good okay I think so yeah hmm let me think about it for a second mmm okay and I think is just for edge and I say for next node and I just know can you still this is a pretty annoying pong that I've done before I don't remember I mean III don't we have turned it on leek oh I just have done only in path before we had that we won him why would we move it so now what is the complexity hmm so basically okay fine okay I think I wanted to be moving in a good way but actually what I need is a mm-hmm but actually what I need is a mm-hmm but actually what I need is a mm-hmm having we wanted deck so that we could be moved from the beginning easier but oh yeah okay I don't know if you could so you could sort okay let's actually just like this list by default we saw it and then we just set it to the tech version of it so that I could do pop laughs okay sorry I having trouble with this but yeah now I can do this because now it actually as a deck let me just run this real quick just to compounding Yahoo's or whatever okay so it doesn't complain that's good okay so now we pop off the next node we yeah we call construct node and then at the way and we add node to the list so enter that and I think that's mostly it maybe it's been a while have to okay no I do not know comb and I don't think maybe I have to but I guess I should all need this I thought I might have just in case hmm oh no now that makes sense huh how do I remove this in a good way man my Python is terrible today I know it's a penny I don't need my outdegree but I did it just so that I could do this but okay they say but I don't want is that when it goes back or no then it still has that thing again right so also this is wrong this should be next note whoops where such fear okay fine they're just keeping it away and I'm going to I mean this would still be - all right I think I'm just trying be - all right I think I'm just trying be - all right I think I'm just trying to figure out how to do it or sorting point I forget if it goes one way or the other on the query so okay so let's kind of let's take a look now that would definitely not work actually meant to do this okay this should be okay maybe but I yeah I guess I did it backwards okay let's try the second case oh no oh I guess in this case it's just there's always one I don't I do this in a good way huh usually I don't use the natural eyes for those that's okay let's just do it straight forward why with a matrix of sorts and I guess you have to do something like that otherwise set is not sordid right hmm yeah I'm just really having trouble with doing it in Python because you Jane if I join C's first person I'll be okay but it's just been a lot I don't think I've actually done this in Python before so I'm just trying to do this in a good way oh yeah this might not give me the right answer but let's say that once first parts of the sorting reasons oh yeah it doesn't don't need to pop anymore basically converted it from what our whoops they say we converted it from linked lists or sire Jason c-lister linked lists or sire Jason c-lister linked lists or sire Jason c-lister adjacency matrix yeah but so this works right and that it gives you the right answer or sorry it gives you an answer but doesn't give you the best answer because it's not sorted and that's the problem here but actually I think we just to someone like okay don't like the performance of this so I'm going to change name to Z good this is Wayde I agree by the way but trying to figure out working thing first uh yeah it seems okay let's try some base cases of just one thing and then maybe two things and there could be more cases but up it's never late so I'm gonna just Yolo whatever works oh no that's just me putting in the test case I think maybe yep okay let's give it a go oh now hmm I mean I'm short a whole frame so that's not great okay give it a go I miss simple I miss going to JFK how did that happen and it would go to jail and it's still multiple now with only ghost air once how did I just miss the entire flight huh that's odd oh no I mean I do have the JFK just on the right order so what am I missing my call to tear to JFK to tears at JFK multiple times there's definitely something off yeah but also it's just doing something we have a station this shouldn't be true the second time to tier 2 CI a to JFK because that should not be a path that is possible debugging is always the most expensive thing so you know what I'm going to say okay well don't print out everything I hope it's just something silly okay so JFK goes to a new interior text here I guess I should point that out here mmm sad face okay JFK it's East easy cuz I knew okay then goes to you see you do okay JFK goes to a newest force but tear is true tear goes to JFK is true how did JFK now has all these edges and all of them are force don't them dumb it's because I have to do someone like in the end to write it now nope okay why do you like going back to tear or TIAA I don't know what Airport that is so the white answers tear goes to Anu I really did - you go to new after this is really did - you go to new after this is really did - you go to new after this is right and Geoff Caden tear wait did I just miss it so ok um if Dallas oh ok huh I thought I was being silly but this is an easy fix it's just at the two edges from tear to her new ok huh so my album is still good I just thought I had a wrong assumption somewhere so now we could just change this in and change this to you know increment by one if its name dear if it's greater than zero we decrement and then ok alright um that looks way better right okay so that is a thing is that when you're unfamiliar with implementation sign that's why you should always practice implementation instead you wonder silly things like this but that said you know I'm not so dad you should practice already in perhaps for interview purposes but just you know in general here for implementation okay I also did make a incorrect assumption that there's only one path between you know two points usually they tell you that but in this case they don't and I just didn't realize that okay let's give it a good submit and give it a good fingers crossed and accepted yeah hmm yeah so the complexity of this album it's a Lydian path definitely look it up this is the essentially linear ish time in the number of edges because as you can kind of see we took at each edge I mean the way I implemented with them adjacency matrix it's a little bit weird because you should be able to do this by adjacency edge but in terms of implementation you cannot remove edges while you're iterating for it so maybe I got done that smaller actually but yeah but because of that I didn't Jason C matrix so the complexity is a little bit trickier in terms of time complexity but it's still roughly linear because well maybe with linear square quadratic dependence my maybe my case teach any weights but it still should be fast enough for small ends you know they don't tell you what n is but that's just the standard or Lydian perhaps of feel free to read up on Wikipedia and stuff like that this is relatively straightforward if you had practice for me what you see is in this video and this is why I like to tape these live and not to skip ahead or just be like oh yeah this is easy this is perfect you should already know why your path you know I mean I'm probably good at no programming and summing these problems but I don't remember every single detail for implementation you saw that I made a couple mistakes here and there including just a assumption that there's only one edge but yeah these are things that but practice you know used one is maybe you start making some of these are silly assumptions but you also just get better with implementation and yeah and I hope that by watching me struggle this is how you know like I remembered in about his poem where you add an edge and there's an illusion path if the graph is still connected and so forth some of this is that they tell you that is valid I tear away so that makes it slightly easier if not then you have to check that's the case where you can in degrees and out degrees which I actually didn't and abusing but yeah otherwise it's quote-unquote standing or otherwise it's quote-unquote standing or otherwise it's quote-unquote standing or Leland path but it's not something that is I don't know I don't think it would come or I don't believe it should be in scope for an interview maybe things will change if you especially if you watch this in the future and things get harder at a time for comparative programming it does come up well toughly often but not that often just like relatively often another one delete code level generally though I mean I say that but this is a legal form so you know by I honestly don't think I've ever heard anyone ask and or get asked a no lydian path question on interview I could be wrong there are a lot of people there's a lot of interviews out there but that's just my experience and yeah that's why I have this form I'm taping to the world a little bit yo yeah let me know what you think and I will see you tomorrow bye okay
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
296 |
hello and welcome to another video in this video we're going to be going over best meeting point which is the problem week for this week and in the problem you're given an M binary grid where one marks the home of one friend and you want to return the minimum total travel distance total D travel distance is a sum of the dist between the houses of the friends and their meeting point and you calculate like this so for example if this is the meeting point for every person you add their X distance and their y distance to get it so like here if this is the distance then like this person would have an X distance of Two and a y distance of zero this person would have an X distance of Z and a y distance of two and this person would have an X distance of Two and a y distance of zero Al together we would get six so this is the meeting point and in the second example if you just have a grid like this then you just pick one of these two and pretty much the travel distance is one right one of them is going to have to travel and the other one's not so the tricky part to this problem is the constraints now and I think once you start doing these hard problems I think a very uh useful skill is look at the constraints and figure out right away if you're going to get like a t so in here um M and N are 200 so if M and N are 200 something you might consider that would be pretty straightforward if you could do it is you just Mark every single point for example right and then you can just say like okay well for each distance let me just get those points so you could literally just like it would be something like for every single meeting location let's say you try to meet here you would just get every single one and you would subtract that location right so you'd say like okay meeting is at 0 let me just Loop through this entire grid calculate all the distances and then get that total distance right so it be like this would have a distance of zero you'd keep going this would have a distance of five you know this would have a distance of whatever it is right and so essentially this complexity right where you just say like let me just pick every single point as my possibility and let me walk through my entire grid and then for every one or even if you don't walk through your entire grid every time let's say you store these ones in like a dictionary and you just say like okay for every single meeting point let me go through that dictionary and calculate the total distance of every single one of those points the problem is you can have a ton of ones here so like half the grid can be ones and then essentially you're going to have an M byn times M byn complexity right because for every single possible location that you try which will be M byn locations you'll have to look at all the ones which are also going to be M byn like I said if ones are like half the grid so you can't do something like that and that would be kind of like the easy solution maybe it would be like a medium problem if that worked so that doesn't work so it's actually pretty tricky to find out the solution on how to do this because essentially we need something like M byn uh by like a log or something right like or M by n by m like one of Dimensions would pass and how would we do that right and that's kind of the tricky part here so something like uh essentially you can't have four M byn so like this would pass something like that would pass or like one of the dimensions or just m byn overall you know like any one of those would be fine so the way we're going to do this is we're going to actually go through one row and really try a bunch of different things and then really figure out like where is an optimal meeting point and then we're going to draw conclusions from there and apply it to the whole grid and kind of if you do this problem there's a hint they give you like try to do this for a row um so let's do that so just say we take this row here and we're just going to put in some ones and some zeros so let's just say like there's a one here zero so get a little bit better one0 1 0 something like this we can even actually probably get rid of some of these because we don't need this many cells so let's just get rid of it make it like a few plus it's good enough let's do six there we go we don't need that many so for something like this or let's start with something really easy like let's start with something like this you might think okay well the optimal meeting point is going to be like here or here right it just kind of like you see like that's the middle and in reality it's actually doesn't really matter where you meet so let's just look at this so let's say we meet like right like one of these two places what would be our distance so here our distance from the left is two and our distance from the right is three so here we have a distance of five let's check this point here we have two three distance of five what about if we just pick something like this we have 1 two 3 four and one so we have a distance of five and here we have a distance of five and actually here we have a distance of five because one person has to travel five and then the other one uh doesn't have to travel at all so if you just have these two numbers you might think like let's meet in the middle but actually all of these work so now let's change this a little bit let's say we have uh like this so from the Lo from before when you had two it didn't really matter where you meet well now you probably want to meet like out of every point where would you want to meet well now that you have a third person you probably want to meet at the third person because then the third person doesn't have to move so this is actually the best and we can take a look and actually calculate this here so here we have a distance of this person have to move two this person would have to move one two 3 four five so we have seven here this person would have to move one and this person have to move four so six here we have two + three six here we have two + three six here we have two + three so we have five here we have uh 1 2 3 four five six here we have one two 1 two 3 four so six I think seven hopefully I did that correctly just double check two 1 2 3 four six yeah I think so and this one is one two yeah I think it's correct and here this is 1 2 3 and 1 2 3 4 5 8 so you can see that like when you have three the best place to meet is the middle um and if you do enough of these you will kind of realize that essentially if you have an odd number doesn't really matter which way like we can even do something like this the best place to meet will still be the middle guy because as we noticed before when it was this remember it didn't really matter right where we met so now if we add a one here it makes sense to me at that middle one because that person would have to travel zero so we could like do this whole thing again but you would you will notice that the best thing to meet is at here and if you actually had ones all over the place like let's say you had a one here and one here let's do one or actually let's not make it symmetrical let's make it like this and you'll see it actually doesn't matter so you can see this isn't symmetrical so you might think like it doesn't you know like where do I meet so actually if you just calculate this for all of these the best places to meet would be here and here so it's always going to be e the middle one if you have an odd or it's going to be one of the middle two so if we actually calculate this let's do this really quick so this person moves one three and then four five six seven so we have a seven here then this one is this person moves two this person moves three so five and then seven again and everything else would be further so that's kind of the general rule for here and you have to kind of play around with it enough to do that so we can write this down so for odd number of ones meet at middle for even meet at one of the two middle ones doesn't matter which ones now we really want to be able to figure out where to meet without actually like if you notice we don't really need to store the zeros like what if we just stored instead of storing it instead of doing this what if we just stored every number and its index and that's kind of what we're going to do so essentially like for this we'll just store like and let's write down the Ines here and let's get rid of these so if we just store like 0o one two three like this right what we're going to do is we're going to have a hash map of a row and if it has a one or a zero we're just going to show the one dimensional one first so we'll say like row zero oops row zero will have one row one will have one and we're not going to include any rows at all that have zeros cuz we don't really care like we're never going to meet at a zero we're always going to meet at a one so Row 3 1 Row 5 1 now we can just like get the sum of the values and we know the sum is four so if the sum is even remember we have to meet at one of the middle one so what's the middle one it's going to be two or three so let's just say we meet at like let's just say we meet at three for our generic case so we can just like go through these values and we're going to have these keys in order because the nice thing is a python dictionary we're going to put these things in order right we're going to go like column by column so this will be in order and we're going to say like okay we'll have a total and when our total reaches three or like when our total encompasses three I guess in this case it's only by one so when our total is three that's the one we want to have so like we'll go through this one we'll have a total of one we'll go through this one we'll have a total of two three and we'll say okay this is the one we're going to meet at and this would also work for odd so notice if we just add like another one here so now if we change this to we add another item so let's do that let's move this zero over here I probably should that's fine okay so two will have a one uh one will have a one and zero will have a one and then what we need to do is we can do the same thing right so we can say like where do we want to meet well it's odd so if we have five we want to meet at the middle one so we just like 5 over two and you can just round this up right so you take whatever number you have over two and round up so we'd round up to three and if we had 6 over two we could meet at three or four so we would just meet at four so we can just like uh divide and then do a ceiling there so we could say like when our sum is three we'll just go down our keys add it up so we have like one two three and that this is the place we want to meet and this would be the best place to meet if you do this whole calculation again you're going to want to meet if you have an odd number you're going to want to meet and it makes sense if you think about it logically like let's say you are at this Middle Point what happens is if you move left every single number to the right of it the distance will add one and then every single number to the left of it you will remove one right but when you move left you will also add one here so you will add one to these three and then you will remove one from these two so ideally when you shift it everything to the left gets like if you have it here let's say and you try to move it over here then same kind of thing all of the these will add one to the distance and all of these will subtract one and because you're subtracting one from three numbers and adding one to two numbers that's better that's kind of a more intuitive way to think of it is you want to put your thing you know where there's an even number of ones on both sides okay so that's kind of how we do it for a 1 by one now let's add a little complexity and let's actually add another row so we can just copy this hopefully this works there we go put it over here now we're going to put numbers all over the place again and this is where it gets tricky and a little bit unintuitive so let's say we just have some random stuff like this so like we realize to meet here but what if we have a bunch of rows and if you think about it this is basically the same thing as these things now have weight right so this has like one this has two this has one this has two and so on so we can actually write it out as a sum so we can say like okay for the totals we can just say like this has a total of one total of two total of zero total of two so now these has this has weights all these ones have weights once again we don't really care about any row with zero so it's going to be the same thing so now what we're going to store is we're going to store it in this format so instead of storing just one we're going to store the same dictionary but we're going to store a total so we'll have row zero will have total of one row one will have a total of two row two will have a total of one row three will have a total two and this is just to get the X distance right because the Manhattan distance if you look the X and Y are mutually exclusive so like we can just figure out like what's the best X location and then we could figure out what's the best Y location so the Y location would be kind of the same thing except the X you're going through the columns and the Y you would go through the rows and it would be the same exact thing so let's do this total so for four remember we don't care about any total to was zero so for five we have two now it's kind of the same thing we are going to want to meet at a median and if this doesn't make sense to you um you can just kind of write out the index of this so you can have like let's say this would be like index zero index one index two index 3 index three index five and you'll be like okay what's the median location so we have four here and four here so it's going to be at either index two or three and let's double check here and kind of do this total thing so if we do a total again we will have a total of three uh seven eight so we'll have eight items so that means we can meet at either four or five remember we're going to always choose a higher one because that way it would also work for the odd number because if we had seven we're going to meet want to meet at four so you can meet at four or five but we're going to pick the higher one so let's check where we have a total of five so we're going to have one three four now we have a six and so this total uh as soon as we hit a total that's bigger or equal to the value that's going to be the thing here right because this six that means it has the five and the six right like this has the four this has the five and the six and so it encompasses it so that's kind of like we will just keep adding the value and then the first one that gets over the total that means that uh column encompassed it right so it's going to be this column over here and we noticed before that was one of the valid columns right because we wanted four or five which was uh when we did this kind of thing we saw it was uh it was this right two or three so four and if notice if we picked four so this would have six if we picked four then it would be this column which would be two so that's kind of the idea is you sum up the values for each so when you want to get the x value you sum up the values for each column right so you sum up the values for each column we can write that down as well X sum up values for each column and meet at median and then why it's going to be kind of the same thing except now you sum up the values for each row because we're trying to figure out like where we would want to go this way right so we sum up the values for each row and then we would meet that way so let's say this had you know if our let's say our row values were like four five 6 42 or something we'd do kind of the same thing where we would figure out like what's the median and then we're going to have these same keys so what we're going to do is we're going to have two things we're going to have a um column sums which will be this one right and then we'll have a row sums and basically what's going to happen here is we're just going to go through these things figure out like where does the median need to be and then where how do we get it and so now the nice thing about having these column sums and row sums the alternative you could do and it will totally work is instead of doing these dictionaries you could just take every single one and you can like put it in an array right so you can take every single one and put its index in an array kind of like I did here and then get the median and that would totally work like so for example for your median X you would make an array of all the rows for every single one and then you just figure out like where's the middle that would totally work but the problem is so this would actually pass on Le code as well but that would be M byn because you can maximally have like the entire Matrix where now if we store the sums it's actually M plus n so it's like a small optimization and I did notice once you do enough hard problems you're really going to get better at making these optimizations it's going to be a lot clearer like oh I don't need this I can make this faster even though like At first the solution was kind of hard maybe you didn't get it once you kind of get into the swing of things you're going to start to see these optimizations as you do more and more of these problems but that's the idea so we're going to get a um we're going to get like an optimal row and an optimal column just by getting the median for both and figuring out like we're just going to keep adding to the we're going to have a dictionary of column sums and row sums and when we get a median for the uh X we're going to go through the column sums figure out like what column that does that need to be in and then the same thing for the row sums when we get the median for y we're going to go through the rows figure out where that needs to be then once we get an index it's pretty straightforward so like let's say we determine the index was here then it's pretty sure for we can just pass through here and now we can calculate the Manhattan distance for every single one right so we'll say like okay for every one of counter what's the Manhattan distance to this point for how about this one to this point because we only have to check one point right we're going to get a point and then that is going to so we're not going to check every single point we're going to know exactly what the best point is but then we just need to calculate this distance that's kind of the idea and then we are also going to Traverse this graph twice in the beginning because I don't want to sort the keys I want the columns to be in sorted order so in order to have the columns be in sorted order what you're going to want to do is for every row you're going to want to go through the columns like first right so you're going to want to go like row by row you want to go from the start column to the end column like this that way when a column has a value you will get it first actually I think what you want to do um so actually I think uh scratch that I think if you want to get a column total instead what you want to do is instead of going like this you want to go through the column right so in order to get a column total instead of going row by row because let's say this had a one this had a zero and let's say this had a one now this would be problematic right because what would happen is you would be like you'd go row by row and be like okay this Colum four perfect column four has a one but then you'd come here and then you'd have a column three so your columns wouldn't be sorted so the better way to do that if you want a column total is you go one column then you're guaranteed to get it then next column the next column and python uh when you insert keys they will be sorted you could also just insert the keys yourself uh you could just insert all keys or like you can make an array and that would guarantee you sorting but because I'm not including any rows or columns with zeros it's going to work better like that for me so you could like I said you could do that's up to you um so yeah you could have an array or whatever and then when you want to get the total for the rows it's going to be the same thing so we're going to go through row zero like this then Row one then row two right so we're going to do two Nest data for Loops to get all our keys in order get a point and then we are going to uh calculate the Manhattan for everything so let's take a look at the code for this because this video is getting kind of long and there's a lot of code so let's full screen so we're g to first of all get the rows and columns right and then like I said we're going to get a row sums and a column sums right and to get the row sums you want to go through the row like row you want to go through each row like through the whole row and then to get the column sums you want to go through the columns so you basically swap these around that way your keys are always in order then we just calculate a median like I said you just take all tall all the values um add them all together so let's say you have like 26 ones you knew that like okay I'm I have to be at one number 13 or 14 and I'm just going to pick the higher one so I'll say 14 so you get those the rows and the columns and then you have basically the same code twice essentially what it does is you go through the keys and you figure out where the value lies right so what's going to happen is you're going to have a row median for example so for a row median you're going to go through your keys for the row and you're going to say I'm going to keep adding uh the current for the key like I showed in this picture right so let's say our median is whatever like seven we're going to say let's have a current let's keep adding these keys and then when the total is greater than or equal to seven that's the row or the column that we want and that's essentially what we're doing here so we start with a uh total of zero and we just keep adding until we eclipse the row median and the first item to eclipse the row median has to have the row median in it so once we get it we break and otherwise we just keep adding the value and keep going then we actually have this uh optimal location right so we have a row result and a column result and that's going to be like the location we want to be at then we Loop through one more time and we just calculate Manhattan distance so that part's pretty straightforward you just say like if we have a one let's calc let's calculate the manhatt distance to our optimal point and then let's return the result and so let's go through the time and space and I did look at the editorial for this one actually and I think we actually beat the space for the editorial uh and the time is the same you can't do you can't really do better than M byn so let's but it's n byn but let's go through Y and things like that so this is M byn obviously right n for Loop by n and by n um this part is worst case uh this is O of so if row is M and uh column is n this is M plus n and then going through the key it's n values in a row is M and then going through the keys and values in a column is n so this like M plus n again and this is M byn so we have a bunch of M byns and we have some M plus NS so it rounds up to M byn now like I said the nice thing is we not storing every single one in here we are only storing the totals this is very similar to the problems of the day that I did in the last few days where we did these like column n totals except this just like a significantly harder version of something that uses that and I think I did a few other problems that were like super hard that uses other optimization but except for that one you actually needed it to pass this one you don't need it to pass but sometimes you will you know like let's say your constraints are you know instead of whatever it was you have to have like M byn * m plus n instead of M byn that can byn * m plus n instead of M byn that can byn * m plus n instead of M byn that can happen for like very hard problems um they will give you constraints where your stuff barely passes if you have the optimal solution so that is something you can do um anyway so let's go through this so row sums for every row we will have a total so this is O of M this is O of n for our storage uh these are of one o one so essentially we are storing for the row sums and column sums this is M plus n and we can run this so I think uh because like you can probably optimize the number of times you around these Loops I noticed everyone code is roughly in this like little thing but you notice our space is really good um because we have like a an M plus n solution and most people have M byn or worse so you can probably do this in less Loops where that's the other thing is like you can look at people's code and you can see roughly where it is and you can see like everyone's code is roughly in the same vicinity so like let's say our stuff was like 116 but then you get some other person like 36 that means they probably use a different solution or a better solution but this just means like you just run it a few times and it falls all over the place right so it's not really significant like I think I ran it before it was here you know and so on so if you look at something like this uh yeah they're essentially this is an m byn space but there's less Loops so that's what it's faster so it's kind of like tradeoffs but the time complexity can't really be better than this um yeah so that's going to be all for this one so hopefully you like this one I thought this was a really interesting problem um and it was pretty difficult to be honest like if the like I said if the BFS just or not the BFS if like just manually trying every single cell passed compare it to everyone that be that would be like a medium problem but figuring out like okay how do I actually where do I actually want to be in the center and then how do I do this with multiple rows is definitely pretty tricky and something very rare that I haven't seen before but now that I have seen it like you can definitely see problems like this and if you see something similar you can definitely apply it um yeah so hopefully this is helpful pretty nice problem and if it was please like the video and subscribe to your channel and I'll see you in the next one thanks for watching
|
Best Meeting Point
|
best-meeting-point
|
Given an `m x n` binary grid `grid` where each `1` marks the home of one friend, return _the minimal **total travel distance**_.
The **total travel distance** is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using [Manhattan Distance](http://en.wikipedia.org/wiki/Taxicab_geometry), where `distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|`.
**Example 1:**
**Input:** grid = \[\[1,0,0,0,1\],\[0,0,0,0,0\],\[0,0,1,0,0\]\]
**Output:** 6
**Explanation:** Given three friends living at (0,0), (0,4), and (2,2).
The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
So return 6.
**Example 2:**
**Input:** grid = \[\[1,1\]\]
**Output:** 1
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `grid[i][j]` is either `0` or `1`.
* There will be **at least two** friends in the `grid`.
|
Try to solve it in one dimension first. How can this solution apply to the two dimension case?
|
Array,Math,Sorting,Matrix
|
Hard
|
317,462
|
1,710 |
hello everyone so today we will be solving maximum units on a truck which is day 14 of late code june challenge and the question goes like this you are assigned to put some amount of boxes onto one truck you are given 2d array box types where box types of i is the number of boxes of i and number of units per box is i so number of boxes i is the number of blocks of type i and number of units of number of units per block i is the number of units in each box of type i you are also given an integer truck size which is the maximum number of boxes that can be put into the truck you can choose any boxes to put on the truck as long as the number of boxes does not exceed the truck size so here is the example and you can see this is the zeroth box this is the first this is the second and zeroth box have one box which have profit three this profit means basically the number of units per box so we want to return the maximum total number of unit that can be put so this will this we can consider as a profit so box type 2 we have two boxes of this type and each box is having a profit of two for box type three we are having three numbers of this box and each box is having a profit of one and we have a truck size of four so at max we can have four box in our truck so we optimally need to choose which boxes will give us more profit so if you can see the box first which is having three profit per box is giving us the maximum profit so what i will do is that i will choose the first one box of first type that contains three units now since they are exhausted i will move on to the another and find which box out of these two which box type out of these two will give my maximum profit so second box of second type two box of second type that contains two unit each will give me profit of two which is greater than profit one so i will choose two box of this and after that i will choose uh so these are three now we can choose one more box so i will choose one more box from this which of profit one and the total number of units we will get is eight so total number of profit is eight so let's see this example also how we can approach this problem let's see so we are given array like this so here each type of box are given and with the quantity and the profit it gives so we have truck size of 10 now we want to choose 10 boxes optimally such that a profit is maximum so what i do is simply i will first find out the box which is giving me maximum profit so here out of these four boxes 10 is the profit that is maximum and it is given by the first type of box so what i will do is that uh let's say profit and remaining box a remaining size so let's make this so initially my profit was 0 and i could have choose 10 boxes now what will happen is that firstly since i see that 10 is the maximum profit given by the first box so what i will do is that i will take 5 boxes of profit 10 so it will give me a profit of 50 5 into 10 so i will take the profit of 50 be happy and now i will say that now i can choose 5 more boxes so how to choose 5 more boxes again simply check out of the remaining boxes which box gives me which type of box gives me maximum profit so here we can see that the last type box which is having a profit of nine gives me maximum profit so i will take three boxes of it so let's say if i take three boxes of nine my profit will comes out to be 27 and now i can choose only two boxes more to fit in the truck so now we only are left with two comma five and four comma seven so it is pretty obvious that four comma seven so seven is maximum profit out of these two so i will take two boxes of seven since there are four i can only take two so i will only take two so if i take two boxes of seven the profit will be 17 and now i don't have any uh remaining size so i will return my profit and profit turns out to be 91 which is the sum 91 is our answer now let's try to uh dig it deep so what we can do is that firstly we can try we can sort the array on the basis of profit a box gives and then out that after that we can continuously select till our size becomes uh zero so this is the approach we are going to use for this so what we can do is that firstly let's sort on the basis of uh profit so what we do is that we will use lambda function in the c plus first so let's say sort box types we want so let's do it dot begin comma dot and now we want to sort this custom so let's say this is the custom sorting in c plus so here we define the reference let's give it now here we want to define the type of argument this trucks each element is having box types each element is having so it is a vector of vector so box types element will be a vector so vector of end let's pass by reference a and vector of end ampersand b and i want to return if a of first is greater than b of first and that's it so what we have done here is that we have sorted our array such that this array will become sorted according to its uh profit size so 3 comma 9 will come here after 5 comma 10 and this 4 comma 7 comes before 2 comma 5 so this is what the array we will get after sorting now what we want to do is that i want to take out elements i'll take out the boxes so let's say and index and i let's say is 0 and while i is less than boxes dot box types dot size till we can choose what we will do so we can check whether we can take the full of these boxes or not now we know they are sorted according to their profit size so we can directly take one after the other so now since let's see there are 10 boxes so let's see can i choose all of these boxes so what i will do is i will take a element count will be having the number of box remaining which i can choose remaining size so count will be initially uh truck dot size so truck size it will be now what i will do is that if count minus this box types of i zero is greater than equal to zero what does that mean is that ten minus 5 so here 10 minus 5 is it greater than 0 yes it is greater than 0 this means we can take all the element all the boxes from of this type so what we will say is that so for this our profit so let's define profit also and profit initially it will be zero so a profit will be plus equals to and all the uh for one box it is boxes of box types i z one so for the all the boxes it will be this so a profit for all the boxes will be 5 into 10 here 5 into 10 so uh total boxes and profit of each box so it is all the boxes and profit of each box and what we need to do is we need to decrement our count so count minus equals to uh count minus equals two will be uh the boxes which we have taken so this will be the count minus and i we will increment so this will be do if we can take all the boxes and else if we cannot take all the boxes now we need to check so here we see that we cannot take all the boxes of 4 which gives us profit 7 uh so what will we do is that we will take hmos as so when we take as much we can so for int j equals to 0 and j less than is box types and it's i comma 0 and j plus so what i will do is that uh if any time our count is zero then i will break otherwise i will add profit of this to box type i of one so now you yeah this time you are adding single profit so we'll decrement count as minus one and after this we will say i plus so i think this should work let's try to run this out yes let's submit it so it is accepted so this is the solution for today's problem thank you everyone have a good day
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
258 |
in this video I will show you how to solve with co2 challenge number 258 at digits so we are given unknown negative integer now we need to repeatedly add its digits until the result is only one digit so we can solve this problem recursively by adding digits and then adding digits of the resulting number but we can see it follow-ups just has to but we can see it follow-ups just has to but we can see it follow-ups just has to solve this problem without any loop or recursion and to solve it in big hole through one run time and to do this let's look at the output produced by the numbers so let's look let's start from the zero produces zero one produces one two results to the output of 2 and so on and nine results to the output of nine and then start from 10 we can see that the output is 1 for 11 it's 2 and so on and for 18 it's 9 and then for 19 it's 1 again or 20 it's 2 and so on and for 27 it's 9 again so we can see that the pattern repeats it starts from 1 and then goes to 9 then it repeats from 1 to 9 then also from 1 to 9 and we can spot that all the numbers that are divisible by 9 it's 9 18 and 27 they produce output of 9 and all of the other numbers produce the output of modular nine so ten module name is one and eleven module nine is 2 and so on so we can solve this problem easily just by thinking modulo nine from our number and returning it so for a thing for the numbers divisible by nine the module will be zero so we will check if the module is 0 we will output and also we have one special case here it's zero so we'll check if our number is 0 then we will output zero so let's implement this problem now so if our number is zero then we will return zero and else we will compute the module of our number and then we'll check if it's not zero then we will return our module and if it's zero we'll return nine let's check our solution okay it was accepted so guys please subscribe to my channel and ask me to solve another little code problem and thank you for watching this video
|
Add Digits
|
add-digits
|
Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime?
|
A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful.
|
Math,Simulation,Number Theory
|
Easy
|
202,1082,2076,2264
|
816 |
hey everybody this is larry this is me going over may 13th of the may league daily challenge hit the like button in the subscribe button join me on discord let me know what you think about today's prom ambitious or i mean ambiguous coordinates um yeah so you should stop this live so it's a little bit slow fast forward come back or skip ahead watching 2x whatever you need to do uh the people who are very uh have ego eyes might notice that i'm actually trying out brave a new browser i have no affiliation i have no referral or whatever i'm just kind of you know let me know if it looks a little bit funky a little bit weird because i've been using chrome for probably the last i don't know 10 years now or something like that whenever it came out uh was firefox before that um and you know i'd say it feels faster but um but i don't know you know sometimes uh you know maybe just a lot of uh random things that is the case but anyway let me know what you think because one of my issues is that sometimes my computer hangs up because my chrome is just doing too much for some reason i mean right come here so it's not that old anyway it's too much of a rant but uh let me know anyway today uh about your opinions uh potatoes bomb is uh ambiguous coordinates so you have two co uh two d two coordinates you remove all commas that's one space ran up the string yes we turned a list of strings of possibilities that could be okay so this is going to be some sort of um so it's just one string right and you have to output all possibilities so i mean this seems very um very straightforward i don't know why oh well because this is a new browser maybe that's why i think oh that's kind of so maybe now for obvious reasons my old farms have to kind of look because there's no uh it's not in the javascript cache or cookie cash or whatever i don't know what storage they store of it but anyway it's not that important but it just seems like it's going to be brute forcible the interesting thing is that star length is only 12 but i think you just literally try every possibility um yeah because basically you have three delimiters up to three delimiters which is that okay for a string of and you can probably skip the beginning and the end i don't think it matters um double check yeah it doesn't matter um but basically you have a string that looks like this and we can just ignore the whatever um we're going another uh parents but yeah so basically now you have a comma that could go between every space possibly maybe one at a time obviously but yeah that would go well maybe not the first place but you know you get the idea and then after that there are also two periods right that could one on the first number and then one in the second number and because of that you have three delimiters and length of the string is going to be 12 and they're part they're like 11 spaces each or something like that depending on i don't know how they count the thing with respect to uh so i guess they're only 10 real characters because you that this counts the parents itself so they're gonna be ten real characters and they're just you know nine spaces in between all the things some of them aren't allowed but you know you just kind of do a brute force of um yeah you just kind of brute force everything and then just check to see if it is possible um with helper functions along the way and i think that should be fast enough because it's going to be at most nine spaces between ten characters and so it's nine to the k uh nine cube roughly speaking is actually even less than that because it's like you know it's really constrained for example the periods would not be in the same you know in the same side of the comma and stuff like that so i think that should be good so let's kind of set up that for loop uh oh and in this particular problem you it's not just uh returning the count you have to return the string um and do that to be sorted in any way it could be returned in any order so we get we're okay so basically yeah let's set that up and yeah i think that's pretty much it the idea anyway the implementation might be a little bit tricky but that looks okay to me i just have like one string to kind of make sure what it is so we're going to just remove the beginning and the end the parents because it doesn't it's not that interesting for us and then now we're going to force the comma for uh comma index maybe in range sub n let's set n as well let's set it to new n new s and yeah and let's set it at one so then now we can split the string um and this maybe this is n minus one i don't know to make sure that it has yeah one character so then now you have it's a coordinates i'm gonna use the word x and y even though it may seem like i'm lazy with the naming x and y makes sense for coordinates i think so yeah x and y is equal to and maybe there's a easier way to spread it down something but let's just say comma index something like that let's print it out real quick because i'm always really bad at off by one for these string indexing because i always forget it's inclusive or exclusive or sometimes in other languages the riff um so this is one and two so this is going to be a lit it's missing the you know um one two and it should be two different chords one and okay this is a little bit off uh oh whoops of course this is off i missed the thing yeah so that looks exactly what we want let's try actually you know a bigger string just real quick because i'm really bad at off by one so um so i am overcompensating a little bit but you know testing along the way allows you to verify i mean obviously in real testing you have like unit testing and stuff like that but for me like the same concept of testing it now along the way uh will you know so that later on if something comes up i could i know that at least this part i already tested it so it's going to be true okay so this is exactly what we want and then now we just go you know maybe possible x equal to go of x possible y's as you go to uh let's just go get numbers say get numbers of y and then now we can just um do a uh a cross product i think this if i find this buy a way to do it but i'm gonna just ignore that for now um and let's just print it out or like i'm gonna do it manually and it's fine too but i just print it out uh but of course it's not gonna pronounce anything we have to get numbers which uh okay now let's actually look at the rules because i read it but i skipped it over not gonna lie i just know that we have to find a valid number so there are no extra zeros a decimal within a number never cursify at least one digit occurring before it so okay let's just actually uh but this part may be a little bit messy but in the if statements but we can do it um but yeah okay so you know so the first thing is that let me double check this so no so i'm just checking the no period case in the no period case only no period case is okay if um so answers is equal to an array list um but so the no period case is good if it the if it's not a leading zero right okay so if length of s is z is greater than one and s of o or s sub o is equal to zero then we so we want the not version of this right so if the length is equal to one or it's not equal to one then we append s um this is basically saying you know if there's not a leading zero or if the length is one meaning that if the number is zero then we can return this as an answer later on and then now we're going to move first a period a little bit um yeah same idea as we had before so for period index range of 1 and n so yeah so the period never appears before the first number it can appear in a second number um okay let's actually change this real quick to have a helper so um leaving zero has leading zero of s and then we just change this to if this is greater than 1 and this is equal to 0 then it has a leading zero right um so then now we can say if it does not have a leading zero then we can use it as an answer otherwise let's try all the periods we're going to use the decimal part doesn't have any constraints so i think we're okay here let me also double check that yeah i just want to make sure that we don't put a period before the end so yeah so now you have to watch my call it whole point and the fact it's a fraction that's more is equal to that's uh same idea we had before so this time it's slightly easier to have confidence of course i just have to make sure that i type the correct thing but yeah if has leading zero of whole number uh or if it doesn't have leading zero then we're good then we enter that we could append um this thing of whole dot decimal right oh we're trailing zeros never start with zeros oh okay so we have to check for trailing zeros as well what is the and not 0.0 is also bad so hmm and 1.0 is bad so that means that it's and 1.0 is bad so that means that it's and 1.0 is bad so that means that it's always it's going to be bad if the last digit is just zero is that true what's that means that it is a uh i feel like we might get a few and uh wrong answers here but uh we'll see and of course this is actually easy because we don't have to worry about length because well now we have to do the same thing basically because if it's one digit then we don't care about it now in this case in this particular case for the trailing it yeah even if it has only one digit we do not want it because that means that it does not need to be x dot zero so uh okay i mean this is only a guess this is a little bit iffy there's a lot of like rules that um to be honest maybe during contests or doing an interview more specifically i might think about it a little bit longer but i'm a little bit lazy at 3am here um so yeah so this is generally the idea um so let's give it a spin real quick just to kind of see what these prints out uh in my syntax if i have a typo somewhere whoops oh i copy and paste that's how it happened but this should hold half oh because this n is a different end so that's me being silly so this is link for best because this n is different than uh it should not carry i mean it does carry disco for that reason but it maybe it shouldn't but uh okay so this is the first number and this is the second number um is that correct i mean obviously you have to do a cartesian part a cross product or cartesian product but i think this looks right at least for this one i mean i the second one there's a long list but it looks like orbiting is valid there's no extra zeros but that's because i don't do any extra zero so we should at least do a case with a lot of zeros uh there might not be an answer for this one though uh let's actually just put these cases a little bit and it's just a hundred as last one and the last part is very easy to write so maybe i should just write it but it doesn't matter because like the expected answer is not in any particular order so we might just get you know like it doesn't matter right because it could be in any order uh we cannot really eyeball it anyway so okay this looks 0 1 it has no answer is that right now it has some answers so hmm so i might be having the wrong answer here let's just actually write out the answer so yeah so we just want a quotation p x for possible x uh what are we pointing is this the string okay so also i'm using f string definitely recommended in general uh px is that right is that the expectation okay let's give it a go whoops oh whoops what am i doing and i did it twice what am i doing twice okay so this looks good except for problem three um so this should be good because zero is a good number why is hmm i don't know if the rest of the stuff me uh matches but this one is definitely a situation um has leading zero on the whole number the trailing number doesn't really matter so if this is length one it should be good no matter what on the whole side and then the decimal has to just be anything that's weird maybe let's print it out again what are we seeing let's also real quick so yeah so definitely at least these test cases mean that we can debug it uh okay i was looking at the wrong one here but okay zero and zero once that means that we should be able to put 0.011 in it and also well now this is that's only that's the only one with this case and here it should also do 0.001 and here it should also do 0.001 and here it should also do 0.001 right so what am i saying wrong here okay i mean i guess it is what it sounds like uh 0.001 is false but why uh 0.001 is false but why uh 0.001 is false but why has that leading zero and this would return force as drawing zero oh this is negative one whoops i was thinking about i mentally copy and paste from leading zeros even though i don't mean to per se and it wasn't that actual copy and paste it was just mentally i look at that as a code and then okay and now everything looks kind of good even though the ordering is in a weird place so yeah let's see so now let's remove our print statements real quick and then we'll probably give it a spin i'm going to sort this real quick it doesn't change the answer and we don't need to sort this for the answer but i just want to see if we may be matched here and so if i sorted it maybe it's unclear but i also don't know if i have the right answer because one troll i think we're okay here unless i'm missing one i think we just have them in a different order maybe because that those looks like right numbers so let's just give it a spin then um but the rest looks okay i think uh just eyeballing which they could you know it was a length is easier but all the other ones looks okay so this one seems like it's there's not even any zero so it should be okay the only thing that i seem to have trouble with is maybe zero so let's give this a minute cool um yeah i mean i to be honest it wouldn't surprise me either way whether i need more but there's just more test cases i don't think conceptually there's anything hard about this uh it's just implementation and just being careful and deliberate and far being deliberate means just more test cases um okay uh let's see so let's go over the complexity real quick as we said there is there are three follow-ups i mean you there are three follow-ups i mean you there are three follow-ups i mean you change within each of these there is one for loop so this is going to be just this part it's going to be n squared and then here we construct this um which is also another n squared inside the o of n so this is going to be n cubed at most um yeah that's basically that this the time uh for space that is also kind of true because in the worst case i think in the one that in this case it'll be like about n square i mean it's actually way fewer than uh n squared directly but it's going to be o of n square oh sorry i keep on saying n square my bad i mean n cube um so it's going to be o of n cubed you know in running time it's much faster because it's going to be a lot uh faster than or it's a lot faster than n cube directly um because there's like a because it gets constrained in multiple ways and you at best is n choose three uh which is not which is already an overestimation and n choose three is like n cubed to over six or something like that right uh depending on you know how you do the off by ones or whatever but um so yeah um yeah that's all i have the space is maybe a little bit more because it depends how you want to count per character but in this case the end is so small that you know like given that it's 10 it's uh it's not a big deal um i think this is some because this one is uh more implementation oriented um because they give you all the rules they're nothing tricky about it per se um so that's why the code i think i have i mean you could say that maybe i you know like you could abstract these two libraries or something like that and then have unit testing and stuff if you want to go like more under on them you know code quality portion but otherwise but like you know for the most part for something that you do in like 10 minutes even i took 20 minutes because of explanations like debugging uh like i think this is relatively clean this is how i would lay out the code there's some caveats with you know whatever but you know in a really self-contained way i think this is self-contained way i think this is self-contained way i think this is pretty good um for the most part i mean there's like some inefficiencies here and there but in terms of readability i am okay and happy with it um yeah that's all i have for this problem uh that's what i have for today let me know what you think hit the like button to subscribe button again and also just you know stay good stay healthy have a great rest of the week uh and i will see you later keep that man to help good bye
|
Ambiguous Coordinates
|
design-hashset
|
We had some 2-dimensional coordinates, like `"(1, 3) "` or `"(2, 0.5) "`. Then, we removed all commas, decimal points, and spaces and ended up with the string s.
* For example, `"(1, 3) "` becomes `s = "(13) "` and `"(2, 0.5) "` becomes `s = "(205) "`.
Return _a list of strings representing all possibilities for what our original coordinates could have been_.
Our original representation never had extraneous zeroes, so we never started with numbers like `"00 "`, `"0.0 "`, `"0.00 "`, `"1.0 "`, `"001 "`, `"00.01 "`, or any other number that can be represented with fewer digits. Also, a decimal point within a number never occurs without at least one digit occurring before it, so we never started with numbers like `".1 "`.
The final answer list can be returned in any order. All coordinates in the final answer have exactly one space between them (occurring after the comma.)
**Example 1:**
**Input:** s = "(123) "
**Output:** \[ "(1, 2.3) ", "(1, 23) ", "(1.2, 3) ", "(12, 3) "\]
**Example 2:**
**Input:** s = "(0123) "
**Output:** \[ "(0, 1.23) ", "(0, 12.3) ", "(0, 123) ", "(0.1, 2.3) ", "(0.1, 23) ", "(0.12, 3) "\]
**Explanation:** 0.0, 00, 0001 or 00.01 are not allowed.
**Example 3:**
**Input:** s = "(00011) "
**Output:** \[ "(0, 0.011) ", "(0.001, 1) "\]
**Constraints:**
* `4 <= s.length <= 12`
* `s[0] == '('` and `s[s.length - 1] == ')'`.
* The rest of `s` are digits.
| null |
Array,Hash Table,Linked List,Design,Hash Function
|
Easy
|
817,1337
|
270 |
hey guys how are you doing this is jaser who is not good at algorithms in this video i'm going to take a look at 270 closest binary surgery value given a non-empty binary search tree bst non-empty binary search tree bst non-empty binary search tree bst okay and a target value find the value in the bst that is closest to the target given the target value is a floating point you're guaranteed to have the only one unique value in the bst that is close to that value target which is like this target 3.7 of target which is like this target 3.7 of target which is like this target 3.7 of course it's obviously uh closest to four so return four right but how we do that uh how we can we solve this problem while it's bst uh the first idea it will be binary search we search first we search for 3.7 we search first we search for 3.7 we search first we search for 3.7 right it might end up in on the node or just between two nodes well for four it's not four it's smaller than four so it must be in the left tree right between the or between the left tree like between the left three and four right for this case would be search on four and then two answer three and just bigger than three so and uh actually it's between three and four right so yeah we can just search on the binary tree and along the path we can update it the closest value right yeah so the idea is clear um binary search target update closest value along the path cool let's say let's result equals infinity uh while because we're going to do the search we don't need to use re we don't need recursion right okay so for the irregular case if root is null return ah we're guaranteed there is a value so it's only one unique value so root is not null so let p equals no that's node equals root we will go until node is not null right so for each pass we will check if updated to the result update result right so if uh math abs result node valve target okay if a node valve it is target then result is target and we just break for the other case nothing is found we should search it right so math if uh if math is uh if it is if it itself we break if it is closer to the target we update also we update the result math abs target is smaller than math uh no uh results minus target abs result equals target oh no result equals node value and then we need to go to next one right so if a node val no if target is bigger than node val then we go to the right tree right so node equals node right for the other case because it's cool it's bigger then it's smaller right so node equals node left and when they met when the node of their leaf load the leaf node and this while loop will end and finally we could return the result right so let's review once more between we before we submit the result okay for we got four we updated to result to four and then we because four is bigger than it we move two right and uh we check two if two is closer ne and uh because and it's bigger than two so we move to the right uh-huh yeah i found a to the right uh-huh yeah i found a to the right uh-huh yeah i found a mistake we should add else here and we go to three is closer no and is it smaller yes so we go to the left but it's new we stopped cool it should work let's submit cool we're accepted and uh what's time complexity well it's spanish binary search so it's log n right worst case it's linear time when the tree is uh it's just a straight line for space well we use a variable to keep track of the node it's constant cool okay so that's it for this one i hope it helps see you next time bye
|
Closest Binary Search Tree Value
|
closest-binary-search-tree-value
|
Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest.
**Example 1:**
**Input:** root = \[4,2,5,1,3\], target = 3.714286
**Output:** 4
**Example 2:**
**Input:** root = \[1\], target = 4.428571
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 109`
* `-109 <= target <= 109`
| null |
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
222,272,783
|
29 |
Hello Guys Welcome Gautam Miding subscribe and subscribe the Path of your Result Problem Appointed mid-december Loot Id Problem Appointed mid-december Loot Id Problem Appointed mid-december Loot Id Lesson Temple Now Let's Understand What Problem That Loot Vighn Subsidized Subscribe Button More Id Am Id Problem Thursday Appointed Entry Subscribe Put Into All Subscribe Appointed Width Subscribe Our Video Hello And Behaviors Pet 351 Stop Hair And Get Free Live Web Result For Subscribe Kr Veerwal YouTube School Remedy subscribe And subscribe Video Subscribe Shri Radhe Din Tak Writing And Continuously Doing What Will The Govind Subscribe Video Subscribe subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Result Inter After Few End 589 Video subscribe Video plz subscribe Channel subscribe and subscribe the Video then subscribe to The Amazing Freud subscribe our Channel Jai Hind Is Problem Dwiid operation at will be performing the most obscure depression subscribe cr in the representation 10 subscribe 06 subscribe The Amazing subscribe to ek baar hai scientist sohrauna chatting se zara lutab screw Video subscribe The Amazing subscribe Video ko share topic science objective video ko loot device where in Question More Subscribe To That Boat Browser Path Vaikuntha To Check Facebook And subscribe The Amazing And Loot Liya subscribe this Video Channel And subscribe The Amazing Mist subscribe Video subscribe and subscribe the Video then subscribe to subscribe Video to Quitted Account Time Know * Then Track Quitted Account Time Know * Then Track Quitted Account Time Know * Then Track From Video Subscribe Time Subscribe Result Otherwise Will Return Result Subscribe Result Otherwise Will Return Gift Result Subscribe Part subscribe this Video Please subscribe this Video subscribe hua hai hua
|
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 |
1,345 |
hey everybody this is larry this is day 15 of the leeco january daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm jump game 4. there's so many of them i don't know which one this is apparently it's hard though so let's give it a try um yeah so let's see given a rate of integers you're given the first index of the array okay you can jump from i to index i plus 1 or i minus 1 or j where i is equal to oh they the same amount okay um okay that's not so bad right uh yeah i mean i think this is just my first search um the idea is that you want to you know i mean this is just the shortest path problem right you just you're trying to get from uh the first index to the last index and the minimum number of steps this is literally faced like a shortest path problem and of course you have this uh twist of this thing um and i think the tricky thing is uh the tricky thing is that these are all equivalent classes so you can a couple ways you can handle it maybe with um yeah i mean there are a couple of ways you can do it but i think that should be pretty okay um i think the key thing is that you don't um the key thing is that you have to be careful right because for breakfast search um the complexity is going to be replaced e and what that means is the number of vertex plus number of edges um but the number of edges in this case can be tricky right number what is n here n is big enough that um if you're very sloppy um or maybe not very sloppy just a little bit maybe if you miss analyzing it the g part is the key part about this and if for example in the worst case analysis um if all the numbers are the same okay let's say all the numbers are the same except for the first two numbers or something like that right or oh sorry the first time on the last number or something like that then in that case if you're not careful you can definitely if you're not careful the number of edges in that case is about v squared or you know quadratic right i mean in that case we plus e is not gonna be fast enough because e is i'm gonna be five times ten to the fourth square which is like 10 to the a from one to the nine for or one times ten to the nine for something like that right um so yeah so i think that's the stuff that i would uh think about and of course in this case the second thing that i would uh think about is that um once you go to an equivalence class you're all done right i'm meaning that yeah meaning that you don't have to you just have to put them you have to kind of think about how um how to handle it um and it is it's as easy as an if statement but you know you can definitely make it complicated or more generic or whatever it is and i'm kind of thinking about that in the moment um but yeah but i think the idea is that make sure you don't handle all of ye um and taking advantage of the greek friends classes meaning that if you handle one number you handle all of them right or at least like you don't have to keep on adding them to the queue um and i think that would be the key idea here um so let's um let's write out what we would look um for now actually what i want to do is i'm going to write a very generic preference search and then we'll play around with the time limited component of potential time limit i think it'll be time limited e-square think it'll be time limited e-square think it'll be time limited e-square solution um and then after that we'll um after that we'll figure out how to um yeah how to optimize it right and it could be is i don't think it's that bad sorry i got a little bit distracted by a message but yeah uh cool um so let's get started and as you go length of away um in the index i'm just trying to right now i'm just making sure that zero and one index don't really matter um because this goes to first and last but it actually doesn't mention index so zero index is fine um that's something that i double check because these numbers are not they almost actually reminds me of like um i guess not i was gonna say like an express train or something where you have like a subway line or a metro line or whatever but eh okay so then now we start at zero right um well let's start by having a q um and then we have an unq let's say unq function on index x or index let's just call it index um we can append index into the thing um and then yeah okay let's just leave it at this for now and of course there's a done thing so yeah so if not done of index uh oh yeah okay i guess if it's done then we just return um okay right um and this is relatively standard though i mean i put into a function but this is relatively standard uh this is very typically standard breakfast search so far my typing is terrible um one thing that i would say and i see this a lot with i see people use wow q which means that this is true e um i actually for readability purposes just as a side note because i see this a lot for some reason and it is technically equivalent or maybe not equivalent but in this case they'll evaluate to the same value um but i like to kind of express it out because for readability this is exactly what i mean right while q has any items and not while q is choosy or something like that right um and then also in this case maybe there's some scenario where you can change this to i don't know where like there's at least five items on the q i don't know whatever the problem is asking it makes it more adaptable instead of just like weird true but not true value so yeah um anyway yeah so current is equal to q dot pop left um and then now we have to do two both uh well these three conditions i suppose um yeah and then maybe i have dx is equal to negative one and plus one uh i mean i could write plus one i guess it's the same thing i know it's the same thing but yeah foot or maybe this is um yeah delta maybe i don't know for dx in delta um current plus uh dx let's say next yeah let's just say let's just call this extra for consistency purposes um of course x is just an index but i look at it as a value on the timeline or on x-axis timeline or on x-axis timeline or on x-axis um yeah and then okay oh um i actually forgot to do the number of steps so that's a little bit silly of me salute me um and in this case i actually surely don't need done anymore um i just wait distance is not equal to infinity or if it's yes no yeah if it's not you go to infinity return okay um and then now we just enqueue nx right um yeah because we don't have to check for bounds do we have to check for bounce no i mean i guess not but uh well i guess we do a little bit okay but then we can check it here so that's fine um if index is less than zero or if index oh this is i mean i said english right but i implement this wall return okay um and then what else do we want to do i guess that's pretty much it uh oh i didn't set the index something like this all right okay so still so far already generic but for search maybe i wrote it a little bit with an abstraction but pretty standard um yeah and maybe you can write something like if nx is equal to n minus one return distance of x plus 1 or something like that just an early termination though not really necessary per se maybe i'll take it out just for confusion or less confusion if x is equal to n minus 1 uh we turn distance of x plus one and of course i'll actually just return this but of course this is going to be a little bit slower than writing d uh putting it here um the reason why i have it here instead of here is because i have another condition that i want to accomplish so i didn't want to write that i don't want to write this if statement twice but i mean it's fine either way but that's my logic of why i put it here instead of here because i didn't want to repeat myself um but yeah now we go something like oh and let's do a lookup table at this point i actually forgot oh i didn't forget but i didn't plan out ahead because i was focused on writing the generic by first search but of course if this was uh complete then we would have written return negative one though this is actually not possible because you can always just go plus one right so let's just say a cert force um in this case um yeah and and um yeah okay and now we have to process the same train stick stop thing uh negative 23 is different than 23 right okay um so then now we can have just um let's just say we have a lookup table right let's make it a collection start default deck of a list uh where do i want to put it right and then now for i x in enumerate of array um lookup of x is a pen i right so basically what we're here doing is that for the numbers that are the same we put it in the lookup table that just puts all the lists together it's a list um yeah of the indexes right so i is the index so then now we put it together and then now the naive thing we can do is now for uh let's say next x in lookup of um lookup of now x is the index in this case i'm messing that up a little bit um x is the index so yeah oops so yeah so i could just do something like this um yeah uh and then we're just in q and x right and this should be good but like i said this is gonna timeout but this should be conceptually good okay maybe not that's all right hmm that is odd actually maybe i do it uh yikes oh maybe this is the case because one i think this is actually i don't know that's true let's see i don't maybe that i mean that's definitely an edge case that maybe i didn't consider but um but that's not the only issue why do what why does this happen i is index right that messed up oh i forgot to uh i usually do this at the very beginning but i think i distract myself with a lot of things but the other thing that you do before is of course then q zero right i mean that's it is what it sounds like um you started with a q uh oh whoops negative one i suppose um that yikes actually yeah actually okay fine i was just a little bit lazy um okay let's write this um and then we can then cue zero at in zero and then this is just to do now we have some duplication of code which is yeah well we'll focus on getting it right first i suppose but yeah uh okay now we don't need this print now we're good um and you know you'll be tempted to submit and maybe to be honest i might have in the past um sometimes i would submit this and i'll be like oh this is time limit exceeded this is silly lie you made a silly mistake but yeah but now we can just do um you know a case uh and then see if just time limits right i actually don't know if this is what number that is uh how big this is so let's print out the n real quick um so that it may be fast enough because i didn't put enough numbers but then we'll see how many numbers there are um yeah 15 000 is hmm this is actually remarkably fast for 15 000. oh did i mess up huh did i lie 10 to the fourth right hmm it is a good question huh this is actually faster than i expected to be honest um 15 000 is roughly big enough i mean maybe i could just do it three more times bigger but it's not that much bigger right maybe that is the difference who knows huh 45 000 and still raising fast hmm did that mess up i feel like oh i made a silliness um the seven is not the same okay there you go whoops uh i modeled it after this one but then of course you just jump straight from beginning to the end and of course that's going to be fast enough silly larry but yeah now you see his time limit exceeded as expected um okay a little bit sloppy today but uh my ideas are right but my you know execution's a little weak right so yeah so as you can see this returns time limit exceeded and then and this is because here it makes it order yi right um order um uh um you know uh order like this makes it yi which is v square what we want to do is that once we processed a number for example because it doesn't really make sense like let's say in this ridiculous case if you right on from this six to this six for example it doesn't really make sense to go back to another six so one once we're done with one six we don't have to um yeah we don't have to go again so we can hack it that way there's also another way of doing it where instead of doing all the numbers at the same time um you could also do um a zero one queue uh a zero one binary search that is uh you can also do zero one binary oh no sorry but first search not binary search my bad zero one but um binary uh breakfast search where you know just keep on adding uh adjacent sex to it or something like that but it's a little bit more complicated so we'll do it this way where what we have to do is just let's just say uh we just add another done thing done is equal to set maybe and then if arg of x um in done or is not in done of course then we do this thing but of course market is done first and i think this should be good enough right because you only want to do this for the first time you see a number right and as you can see this is much faster and it has the uh correct answer with 176 running time so let's give it a submit um yeah and not surprisingly i did mess it up previous time because that's what i thought i feel like i would have messed it up so yeah um what is the complexity of this is now so if we did not have this would be all we press e like we said because this is linear and that's the number of edges um but here because of this we know that every um every node every index can only be um every index can only uh be the target of an nq um even if it gets here um twice right so it um and it only gets so this function at all only calls from twice right one from the left one uh okay three times sorry one from the left one's from the right and then once from the same station if you call it if you use my metro uh analogy so therefore is going to be linear in the size of the input which is all real um so yeah so because in this case this only gets called for each item once and uh each unique value of array of x uh once and of course they can be at most n distinct items so this on this thing even though there's a loop here it's going to be amortized o of one of n in total times or we in and to keep track of what we said uh and of course this is also going to be all of v space because i mean there's a deck which is all v there's distance which is ov there's a set which is also all v so this is going to be every um total space um yeah um that's all i have for this one let me know what you think um yeah actually let me take a look at previous solutions because they went a little bit faster how did i do last time um oh and i actually did have the same idea for stops um okay so i guess i did the same thing here where yeah oh this is actually much cleaner to be honest uh i don't know about much cleaner but it is cleaner it's basically but that's the same way that i uh the same idea that i have uh today so yeah and when did i do this one okay this is the same thing except for we delete all the edges um so the same idea because i got a time limit exceeded because i didn't do it this way which i guess maybe it was i knew on the subconscious level and then i had a syntax error which i don't know why so oh i had an extra finger here because i was trying to comment on the print um but yeah um okay yeah that's what i have with this one let me know what you think uh hit the like button hit the subscribe button join me on discord have a great weekend stay good stay healthy take your mental health i'll see you later bye
|
Jump Game IV
|
perform-string-shifts
|
Given an array of integers `arr`, you are initially positioned at the first index of the array.
In one step you can jump from index `i` to index:
* `i + 1` where: `i + 1 < arr.length`.
* `i - 1` where: `i - 1 >= 0`.
* `j` where: `arr[i] == arr[j]` and `i != j`.
Return _the minimum number of steps_ to reach the **last index** of the array.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Input:** arr = \[100,-23,-23,404,100,23,23,23,3,404\]
**Output:** 3
**Explanation:** You need three jumps from index 0 --> 4 --> 3 --> 9. Note that index 9 is the last index of the array.
**Example 2:**
**Input:** arr = \[7\]
**Output:** 0
**Explanation:** Start index is the last index. You do not need to jump.
**Example 3:**
**Input:** arr = \[7,6,9,6,9,6,9,7\]
**Output:** 1
**Explanation:** You can jump directly from index 0 to index 7 which is last index of the array.
**Constraints:**
* `1 <= arr.length <= 5 * 104`
* `-108 <= arr[i] <= 108`
|
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
|
Array,Math,String
|
Easy
| null |
23 |
hello guys welcome to algorithms made easy today we will be discussing the question merge key sorted list in this question we are given an array of k linked list each linked list is sorted in ascending order we need to merge all the linked lists into one sorted linked list and return it in the first example we can see that we are given three linked list each one is sorted in an ascending order and then we output one single linked list with all the values the rest two examples are of empty linked list so by seeing the list and the response we know that we need to sort all these list so the brute force approach will be to add all these value into a list then sorted using in the inbuilt sort method and then iterate over this sorted list and create a linked list out of it the code of which will look like this we will have a dummy node head taking it in temporary variable having a list adding all the values in all the list into this list sorting that list now iterating over this list and creating a new single linked list and returning head dot next this is a brute force approach and the time complexity will be n log n where n is the number of values in the list the space complexity is often now moving on to the second approach we will see how we can leverage the fact that each list is itself sorted so let's see this with the help of an example consider these are the three list given to us as we see that each of these three lists are sorted in itself we can compare the first three values of this list and pick whichever is the lowest we will have a dummy node so we'll put that smallest value next to this dummy node now from whichever list we have selected this node we'll move the pointer to its next node now again we'll compare the three values and whichever value is the smallest we'll put that node in the result list we'll move the pointer of this third list to the next value and now we again compare the three values and we'll continue doing it till we reach the end of all the list so let's see how we can implement this so similar to brute force we will be needing this null and empty check and also needing this head and temp head we won't need this arraylist or looping so we'll remove this we need to loop till there exists even one value in any one of the list in this array so we will have a while loop which will be infinite we need to find the lowest value in all of the lists present so we'll have initially this pointer which will point to the list with the minimum value now we need to loop on this list array and if the node at p is equals to null or if the list at i is not null and also the value of this node at p is greater than the value at i then we need to put the index i at p position if even after iterating over all the list we found no value that means if the list at p is still null then we are sure that there are no values present in the list so we'll break this loop otherwise the next pointer of this will become whatever node we have at p now we'll move the stamp to the next pointer and also at this p position we need to move the pointer to the next so this completes the coding let's run this so it runs successfully let's submit this so it got submitted successfully the time complexity in this case is lk where k is the size of the list and n is the number of nodes the space complexity is o of n now this program still has a higher time complexity and we can further reduce it so let's see how we can reduce it so let's see this with the help of an example suppose these are the five list given to us what we can do is instead of checking all the first value of all the list we can combine two list at a time and creating a new list which is sorted we have three list left that is list one list three and list 5 because when we merge list1 and list2 we are reusing the space of list1 hence we have shown list1 as the resultant list of the two lists that we have merged and similarly for list three and list four now we will again combine list one and list three creating list one and at the end we'll combine list one and list five thus creating a list 1 which will hold the sorted list for all the 5 list that were initially given to us this approach needs us to implement the code for merging 2 sorted lists in of one space we have already seen this question and discussed it in one of our past videos so we won't be discussing as to how we will merge the two sorted list into one we will be directly using its code so this is the problem that we were talking about that is merged to sorted list if you haven't already watched this video the link is at the top we will use the same code that we have in this problem and we'll paste this now we won't be needing this head temp or this while loop for now and at the end the result will be present at the zeroth index initially we need to merge every adjacent list into one so initially the interval will be 1 we will be doing this till the interval is less than the length of the list for every level we will be starting from the zeroth index going all the way till the end of the list so i will be starting from 0 till i plus interval is less than the list length we need to jump from 1 to 3 in the first level which means i will be incremented to i plus the interval into 2. now this is we will be putting the merge list we will use the method merge 2 list the first list will be the list at ith index and second will be i plus interval in the first level the interval was 1 that is we're jumping from 1 to 3 in this next level we were jumping from 1 to 5 so the interval will be incremented by a factor of 2. so this completes the coding part let's run this code so it got successful let's submit this so it is submitted successfully the time complexity of this approach is n log k as the number of lists are reducing by a factor of 2 at each step and the space complexity is over 1. thanks for watching the video see you in the next one
|
Merge k Sorted Lists
|
merge-k-sorted-lists
|
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.
_Merge all the linked-lists into one sorted linked-list and return it._
**Example 1:**
**Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\]
**Output:** \[1,1,2,3,4,4,5,6\]
**Explanation:** The linked-lists are:
\[
1->4->5,
1->3->4,
2->6
\]
merging them into one sorted list:
1->1->2->3->4->4->5->6
**Example 2:**
**Input:** lists = \[\]
**Output:** \[\]
**Example 3:**
**Input:** lists = \[\[\]\]
**Output:** \[\]
**Constraints:**
* `k == lists.length`
* `0 <= k <= 104`
* `0 <= lists[i].length <= 500`
* `-104 <= lists[i][j] <= 104`
* `lists[i]` is sorted in **ascending order**.
* The sum of `lists[i].length` will not exceed `104`.
| null |
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
|
Hard
|
21,264
|
399 |
so the question as you can see on the screen is we have given these equations and corresponding values and we have to find the answer for these queries like here a to b it represent a divided by b uh and the value is 2.0 similarly b uh and the value is 2.0 similarly b uh and the value is 2.0 similarly b divided by c and the value is 3.0 so divided by c and the value is 3.0 so divided by c and the value is 3.0 so these are the output for these queries and now let's jump into the intuition how we are going to solve this so let's discuss the solution so solution is very simple build a simple graph with reverse edge relation and we will do dfs and find the source to target value so as you can see we have like i have built the graph with using the value that is given that is a to b we have like a to b 2.0 value and b2c like a to b 2.0 value and b2c like a to b 2.0 value and b2c 3.0 value now for example for this query 3.0 value now for example for this query 3.0 value now for example for this query a to c we can uh like calculate the answer like 2 into 3.0 by going from a answer like 2 into 3.0 by going from a answer like 2 into 3.0 by going from a to b and b to c so initially the value will be 1.0 because 1.0 is the will be 1.0 because 1.0 is the will be 1.0 because 1.0 is the multiplicative identity of any number so if we multiply with any number it will give the same value so that we that's why we will start with 1.0 why we will start with 1.0 why we will start with 1.0 so if we go to one a to b and b to c we will get the answer is 3 into 2 into 1 that is 6 and also if you want to go to b to a so there is no relation so that's why i told you to build a graph with reverse relation so while at adding a edge a to b in the graph we will also add a edge b to a with the value like this so b to a and the value will be 1 by 2.0 that is equal the value will be 1 by 2.0 that is equal the value will be 1 by 2.0 that is equal to 0.5 to 0.5 to 0.5 so similarly we will add the value for c to b that is 1 by 3.0 that is 1 by 3.0 that is 1 by 3.0 okay so that's how we will build the graph uh while adding the edges in the graph so now let's answer this b2a so b2 as we can see is 0.5 which is the answer can see is 0.5 which is the answer can see is 0.5 which is the answer and now the query is a to e so as you can see e is not present in a graph so it will check for all the uh dfs in the graph and we will not find the target value e so it will return minus 1 we will see in the code that how we are going to return minus 1 if we didn't find any target value so now the uh the query is a to a so as i told you i will start with 1.0 because it's the multiplicative with 1.0 because it's the multiplicative with 1.0 because it's the multiplicative identity so the a to a will be source and target value will be same and it will just return the starting value that is 1.0 so that's that for this and x to is 1.0 so that's that for this and x to is 1.0 so that's that for this and x to x so x is not present in this graph so it will return -1 we will see in the it will return -1 we will see in the it will return -1 we will see in the code how we are going to do this i think you get the intuition now let's jump to the code now as you can see we have given values and equations what we will do we will first create a graph with reverse relation as i told you in the intuition so here we are adding edge from u to v and v to u so as i told you u2 will be direct value that is given in the values and v2 u will be 1 by the value okay so that's how i build the graph now we will for all the queries we will find uh find out the values corresponding answers okay for that what we will do simple dfs as i told you so as you can see we are taking the input as uh adjacency uh map and also a visited uh set and then a source node and a target node and the value we will start from so as i told you we will always start from the value as 1.0 because it is the multiplicative as 1.0 because it is the multiplicative as 1.0 because it is the multiplicative identity of any number and then what we will do the simple the dfs and if we find the source equals to target so source and the target equals so we will change the source any time we will do the dfs and we will move to the next node so if we find the source equals to target we will check if it present in the adjacency list or not otherwise we will return the minus 1 as the answer as you can see here if we find that we will return the just the value which we calculated while doing the dfs here you can see we are calculating that is multiplying with the current to the next we are going the next node we are going on so that's how so here max will represent if there is a minus one or there is actual value so there can be possibility that one dfs do the minus one result so we just not written the minus one we will see if there is any answer or not so that will store in the result and it will return the result here so in this way we will have all the uh values for the queries in this answer vector which is a double and we will return the answer vector so if you like the video please like it and if there any better plus b please comment down in the comment section
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
203 |
all right this lead to a question is called removed linked list elements it says remove all elements from a linked list of integers that have value Val so the first example is a linked list 1 2 6 3 4 5 6 and Valis 6 so the output is that linked lists with any elements with the value of 6 removed so what we have at the end is 1 2 3 4 5 all right so you might think that the way to solve this is to check the node you're currently on and if it doesn't equal the value you move the pointer to the next node and if it does equal the value then you can just reassign it so let's see how that would work I have denoted the current node to be C so let's just see how this works so we're on the number one that doesn't equal the value 6 so we move it we're on one again doesn't equal the value 6 so we move it now we're on the number 6 which does equal Val how would we remove the node that we're currently on we don't have access anymore to the node behind us so what do we do now we're kind of stuck this isn't an impossible hurdle to overcome it would just be really difficult so instead of checking the node we're currently on what we should do instead is to check the next node all right let's see how that works so we're on the number 1 we check up the next node is equal to the value so is 1 equal to 6 no it's not so then we just move this up now we're on the next number 1 we check its next value which does equal to 6 so since it does we can just reassign the next pointer to the node after it instead so this looks ok but what happens if the first node in the entire linked list equals the value so what if it looked like this well if we're only checking the next node we'd be ignoring the fact that the node were on actually needs to be removed also this brings us back to the problem that we originally faced which is what happens when the node that we're currently on is the node that needs to be removed so to ensure that the next node can always be checked we should create a dummy node and put that at the beginning of the linked list all right so now we've added a node at the beginning of the linked list and given it some kind of value we'll just put a negative one in this case so doing this ensures that we check every node in the original linked list because when we check current nodes next value that would be what the original head was all right and remember the original head was here but for all we know this head could end up equaling the value that needs to be removed so now we'll just reassign head to also start where this dummy node is but all right and I'll just change this back to what it originally was all right so let's start we'll check to see if the value of the next node equals the value of the node that we need to remove the next value is one so we can just reassign current node to that what's the next value now the next value is another one that doesn't equal the value that needs to be removed so we'll just move it up one but now what's the next value is six so now we need to reassign the next property to be next dot next so we skip over what was previously the next node so now that we've done that we can reassign current to what's now current dot next all right so we do the same thing again what's the next value is 3 so we can reassign it now what's the next value is six so we now have to reassign our current next value to next dot next remember that looks like this okay so now that we've done that let's try to reassign current to what's now current dot next now we're back in the situation that we don't want to be in the node we're on is a node that has to be removed because the value of it equals vowel so that can't work let's put it back to where it was so all this tells us is that we can't always reassign current to current dot next after every iteration we only do it when our dot next property doesn't equal vowel our dot next property right now does equal vowel so we just hold off a minute and go to the next loop we do the same check does our dot next property equal vowel yes it does so now we reassign it to what is next which is this six right here dot next which would be no all right so now our current nodes next property equals null so now we break out of the loop and we stop iterating over the linked list now we can just return our linked list but now we run into one final minor problem if we returned head which is this head is pointing to the dummy node that we added at the very beginning we don't want that because that was never in the original linked list what we really want to return isn't head it's really head dot next so when you return head dot next that will give you a final linked list of 1 2 3 and then no all right let's get to the code what lead code is giving us is a function called remove elements which accepts a parameter head and head just represents the entire linked list and a parameter Val which represents the value of any node that we want to remove so the first thing we should do is we should just check whether or not head is null and if head is no we'll just return immediately so we'll say if head is null that means there is no linked list so we'll just return no all right so as we said before the next thing we need to do is create a new head at the beginning of this linked list and we're doing this just to ensure that we're going to check every node in our current linked list all right so we'll say let current node equal a new list node and we'll give it any value but in this case we'll give it a value of negative 1 so that would look like this then we'll say current node dot next equals head that would just connect it to our current link list so right now this is current and now we'll just reset the head to be where the current node is we do this so at the very end we can just return head dot next so that'll look like this that's head equals current node all right now we need a while loop to iterate over every node so we'll say well current node dot next doesn't equal null because we know that if the next node is null that means we've gotten to the end of the linked list so now we just need to check whether the next node has the same value as the value of the node that we want to remove so that's if current node dot next dot Val equals Val and what do we do in that case we have to change our next property to be next dot next which means we're skipping over that node so current node dot next equals current node dot next if we look to the left does current node dot next which is one equal Val all right just so we could walk through this let's say Val equals six all right so the while loop says while current node dot next doesn't equal null does it equal null no it doesn't it's the number one so it goes to line 23 and checks whether the value of it equals Val well the value of it is one that doesn't equal Val so we need an else statement and in that else statement we'll just reassign current node to be whatever current node dot next currently is so that would be current node equals current node dot next then it checks again is the next value null no it's not does the next value equal Val no it doesn't so we'll just reassign it again next loop does the next equal no it doesn't what does the next equal Val yes it does so like we're saying on line 24 will reassign current node dot next to be current node dot next all right so notice that current is still on the node with a value of 3 so next while loop starts thus its next value equal null no it doesn't it equals 4 because that's what we just reassigned it to does its next value equal Val I know it doesn't so then on line 26 we'll just reassign current node to be whatever it's next property is so current node will now be the number 4 all right line 22 asks if current node next is null and yes it is meaning we've come to the end of the linked list so all there's left to do now is to return not head remember but head dot next because head dot next represents what head used to be all right so let's run the code see how we did looks good let's submit all right so as you can see our code was faster than about 76 percent of other JavaScript submissions as usual decode and written explanation or link down below if you liked the video give it a like and subscribe to the channel it helps out a lot see you next time
|
Remove Linked List Elements
|
remove-linked-list-elements
|
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50`
| null |
Linked List,Recursion
|
Easy
|
27,237,2216
|
34 |
Hello hello everyone welcome to my channel let's all the problem find the first and last position of element in solid as a very famous problem and this is my favorite problem of most everyday life is Google Microsoft and solve this problem of starting and position of India. - 110 time complexity of all times in hindi that for life starting date selected tree in life from the - 110 similarly right tree in life from the - 110 similarly right tree in life from the - 110 similarly right index in his life but also from b minus one half are like it is the pure target so let's your first day first president to Find a re-look 528 0280 president to Find a re-look 528 0280 president to Find a re-look 528 0280 liquid 90 number 8 subscribe like and every time you hindi current time when ever you find a correct number will give number nine avatars iso seere laptop display and keep updating 4804 is the answer pichwade expected in the First Step Which Starts With A New Way Will Interact In Water From - - - - Subscribe Solve This Problem And Divide Of Britain Laut I Explain Any Time Complexity Of Dissolution Saunf Editing Role Number 3 Our Are Offline Time And Space Complexity Of Dissolution Is Vansh Person Who subscribe to the Page if you liked The Video then subscribe to the Difference Templates Video Is How To Do You Like Two Points Like This Who Is The Chief Left Best Wishes In Pondicherry No What Will You Find The Element Searching For Starting Index Of its first service delivered directly colleges are aware of name of is lies to plu target me two point two plus one hour video for two new delhi ant in that case how will update my r2h minus one has every state that 9th class one We Are Right Somewhere Reduce Please Like Me No Will Do It Is Equal To A Guy But I Don't Know Decision On Left Side Decide What We Will Do Subscribe To And Finally Bigg Boss Back Loop Subscribe My Life Is The Most Wanted To Update - 121 Wanted To Update - 121 Wanted To Update - 121 Well listen down in his eyes and it is which represents the attacks were fighting life which lies with so reminder set with minus one and five physical to [ __ ] minus one and five physical to [ __ ] minus one and five physical to [ __ ] growth current and so on but at least noted down the current in the middle of no entry no Where and left forces will return of the return applied for example let me clear that 500 600 800 subscribe school do the first time a 2ND year finding are like stars and index of those 80 first year two is not go into this world will do it is this nonveg agro loot target two three take chanod two and you will break out an order I will be custom which is the last time specific 352 left index of staff23 Similarly for being rather Than Death Will Give Us Convenience And Subscribe Now To You For Finding Love You Can Send A True And Finally Subscribe To Bigg Boss My Channel Search And Elected From Left To Right 220 Anti To The Point And This Will Be Am I Right And I Will Just vitamin E the return me vitamin new in areas of constructing like starting from left and right subah chitta na dharai f par method will right the definition of the self mother and will return all imities left with greater noida and target normandy slide lootmar hai hain to Next Measure Bullion Isn't That Tweet Uh Will Smith Youme Zinc - Isn't That Tweet Uh Will Smith Youme Zinc - Isn't That Tweet Uh Will Smith Youme Zinc - 110 Side - Wave Flu Swine Flu Plus 110 Side - Wave Flu Swine Flu Plus 110 Side - Wave Flu Swine Flu Plus Minus Overloading Of Land In The Target In The Bab.la The Health Of A Great Dane Also Target We Update Our 251 That Also Adds Kiss Direction E Will Update Hi Rain MB Chilli One Just Was Slapped By A Woman Will Update R Two Minus One Otherwise Update Two Plus 12345 Will Return To Start A Flat Compiled End Mid-2012 By 1999 Pluto Champion Are Oh Mid-2012 By 1999 Pluto Champion Are Oh Mid-2012 By 1999 Pluto Champion Are Oh How To Flower Custom Pass Bank Samay Ki Testing Pass Net Submit Jisko No Ka Record Accept What is the Time Complexity of this Solution Swift NCEPOD Simply Boys Search for Element with a Smooth Shell of End Time 100 Time Complexity of Power Solution Is That Log in the Complexity of Life my life my channel thank you
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
345 |
okay sup guys leak code 345 reverse valves of a string given a string s reverse only all the vowels in the string and return it uh the vowels are a e i o u and they can appear in both lower and uppercases more than once so real simple I'm a good example here in hello we have two vowels H and or sorry E and O in this case we just swap the places of them so o and E swap with each other in this case here we've got Elite code so in this case these ease swap in that case nothing really changes there but then this e and this o Swap and therefore we get leot seed uh so yeah so real simple um let's get into the code right quick so first of all we're going to create our array in order to because we need to Traverse this so we need to create an array um oops so let's start char uh let's call it word equals so we're going to take our string s and we're going to turn it into or send it to our array right um that way we can play with it we're also going to declare our integer start to be zero and we're going to declare an integer end to be a s dot length minus one I'm missing this cool and then we're also going to need to declare our vowels so since they haven't collided for us so they haven't given us a thing with vowels in it so we just a e i o u and then a e i o u for both caps and lowercase um right so next we're going to do first our first while loop which is uh while start is less than end we will be able to run this code essentially um so that's our first while loop our second while loop now is going to be again while stars is less than and let me just fix this right quick while star is less than and we need to make sure that again we are actually picking up a vowel when we're wherever we are in the array so in this case index survivals.index of so in this case index survivals.index of so in this case index survivals.index of uh wherever we are at word and that needs to be provided that is true then we will well we can ignore this while this section of the code but if it's false in this case if word start does not equal the vowel essentially if this isn't if these don't equal a vowel so this works whatever word start is or word at index start is then we need to increment our starts by one and the same will apply so we'll do another again we're looking for we're starting to look from the left Left Hand of the word and the right hand side of the word so in this case we've got and we'll have to do another while loop which again as long as starts is greater than and but this one's going to be vowels dot index of words and this one is and oops and correct yeah as long as that equals minus one then or in that case if it's false then we increment r or we decrement our end by one but provided we are so let's say we don't satisfy these while uh these requirements in our while loop in that case we don't increment let's say we're on two vowels in this case we're then going to need to provide the logic which will swap the letters the characters so in this case we're going to need to First declare attempt character or attempt um yeah something that's going to hold our uh word right or a letter per se or char um so we declare that's first so whatever where oops not Ward word whatever word start is now temp uh and now we will change start to end word end and then we're going to well what's going on here whoa sorry um and then we're going to change word end to temp so in this case here basically what we've done is if I bring back up our little drawing ability we've basically done like a little triangle right so in this case here we've got you know temp is here start is here and end is here right so this moved here and this moved here right um yeah actually on that quickly yeah cool so back to our code so after that is done we're going to increments start by one we decrement end by one and then obviously this while this you know our Walla wall Loop is correct so while our start is still less than our end we will continue to run through this swapping any of these uh characters and then once we're done with that we basically want to First return our answer to a string or rather word to string so we write new string word and then we simply return our answer and provided I didn't mess anything up here sorry let me Focus one up so this is accepted in our first basic test case and if I submit all is good maybe a little slow there's a lot of you know it's a very easy to understand example there's a lot of easier ways to do this for example I know that you can um you know to Upper to lower kind of this but regardless it's fast enough and it gets the job done it's easy solution um I hope that helps uh please like subscribe any questions or if you know of a better way to do it or um if you think I could have done something a bit better explain something a little bit better please comment let me know uh thank you bye-bye
|
Reverse Vowels of a String
|
reverse-vowels-of-a-string
|
Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters.
| null |
Two Pointers,String
|
Easy
|
344,1089
|
229 |
welcome back to another Le code video today we're going to be solving 229 majority elements medium given an enter your array of size and find all Ms elements that appear more than uh 1/3 time right than uh 1/3 time right than uh 1/3 time right so I mean if you haven't watched my last video you should go ahead and watch it the second problem I solve is actually something that uses um the algorithm you're going to use today so it'll be like it'll be easier to understand so let's look at the examples here three here one and then here they're both 50/50 right both 50/50 right both 50/50 right so right off the bat we can see that the max number of elements that we can return is only two right cuz uh if we were to divide something into three right so let's say um 1 22 uh 44 uh yeah 44 so it says more than more right so this not more that's not more so we turn zero right but let's say it's 111 22 44 right here uh I mean this is a kind of an odd number but basically here we would only return this because this is more than 1/3 right so we can't return more than 1/3 right so we can't return more than 1/3 right so we can't return just if it's 1/3 right so what we're just if it's 1/3 right so what we're just if it's 1/3 right so what we're going to use so I mean they can only be two more than 1/3 in two more than 1/3 in two more than 1/3 in a array basically a in a array basically so like last time we're going to use uh where is it yeah mors voting algo right so basically what this States is that uh if you were to count all elements uh the one the majority element after one iteration would be the element on top I'll just show you guys so here I'll do it for one so it's E1 that would be element one is equal to zero and the count C1 is equal to zero right so what this States is for I and nums is count Oneal equal Z so it's kind of greedy I guess E1 equals I C1 = guess E1 equals I C1 = guess E1 equals I C1 = 1 and then it's like so if it the count is zero then we would uh get a new one right and then so if the count is not zero right or if the current element is equal to the if E1 is equal to I so we just do if LF E1 equal I and then we would just increment the count right because we seen it again and then so if it's not then we just uh decrement count I mean C1 so I don't really want to run it but basically at the end of this E1 would be the majority element so actually I will run it I'll just print it yeah we'll just return empt already see this one had two but this is still a majority element anyways so we're going to use this Theory to make um two so we'll do E2 because we have to count two right and then C2 so this is basically just an iteration of what we just did right so uh we want to get the two most occurring numbers right so what we're going to do is we're just going to do the same thing so we would do if C1 equal equals zero right but we also want to check and I doesn't equal E2 right cuz I want to count them separately so we would do E1 equals I C1 equals one right because we just seen it and then now we would do the same thing for uh C2 E1 E2 C2 right so now we would do the if it's equal so we could do is it can we do LF okay yeah and then we would do if uh I'll just do F or do H I think yeah I'll just do L and then so we just do the other part right so uh L I uh all right we do E1 equal I and I think that's about it C1 what equal one I think we just do F if E2 equal I oh C2 uh plus = 1 and then just else C1 - = one C2 minus = 1 and I think else C1 - = one C2 minus = 1 and I think else C1 - = one C2 minus = 1 and I think these can just be Al all right so now let's just print it and then we'll just return the an still so this is the like two highest right these are the well this is because we initialized it zero but yeah I mean if you look at the constraints right so it's not even uh no never mind but yeah and then case two these are the two highest right so we do have the two highest now one thing we need to check is if they are 1/3 so we need to check is if they are 1/3 so we need to check is if they are 1/3 so we do T equals l n is it n or nums yeah nums divided by three right as the constraints and then we would do like for I in no and let's just we set just because we have to count the Curren of each one so we'll just do that so we'll do if I equal equals E1 C1 plus = E1 C1 plus = E1 C1 plus = 1 if IAL E2 C2 plus = 1 and then now we just have E2 C2 plus = 1 and then now we just have E2 C2 plus = 1 and then now we just have to check in aend so we close here final equals this if C1 greater than t uh final offend E1 if C2 greater than T final offend E2 and then we return final so this pretty long I mean pretty long and skinny but this should work yep and we submit it and yeah it's pretty fast I'm pretty sure okay let's see what he did return oh yeah they opened it okay well this is this has been Mo's voting algorithm make sure to like And subscribe comment down below uh what you want to see next and I'll see you guys tomorrow later uh
|
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
|
1,970 |
hey everyone welcome back today we are going to solve problem number 1970 last day where you can still cross first we'll see the explanation of the problem statement then Logic on the code now let's dive into the solution so in this problem we have a binary Matrix and we are given row and column of the binary Matrix and the cells to the array represents the cells of the binary Matrix right so they are given one based array system so the first row represents the zeroth row right and the First Column represents the zeroth column so that we need to consider here and the indices of the cells represents the days so the goal of the problem is to we can start from any top cell we can start from this one or this one so in this problem we need to find the last day that we can reach any bottom step so we need to start from any top cell but we need to reach the bottom cell can be any cell as well and so we need to return the last day where I can reach any bottom cell so we are going to use binary search to pick which day will be the last day along with the binary search we will use a breadth first search so inside the BFS we are going to check whether we can reach any bottom cell from the pick today using the binary search so basically we are going to pick a day and we are going to check whether we can reach any bottom cell in the BFS right so now we will see how we are going to do this so here the left pointer will be pointing to the first day and the r pointer will be pointing to the last day that is 4 so here we have 4 days in the cells so our pointer will be pointing to 4. so now we need to find the middle day so we need to add left and right pointers so 1 plus 4 is going to be 5 and we need to do the integer division by 2 here we are going to get 2. so now we are going to check whether 2 is my last day or not that is on day two whether I can reach any bottom cells or not right so we are going to send middle value to the BFS function so the reason why we are using binary search is that it is more efficient than order of n algorithm right since we know the days are in order it is more efficient to use binary search which is login right so in the BFS function we are going to create a binary Matrix so first we are going to represent all the cells as 0 at the start so we know the rows and columns are 2 so we have two rows and two columns right also in the binary Matrix 0 represents land and one represents water another interesting aspect of the problem is that on the I today we will block the land with water that is we will change the cells with one so what we are going to do is that even after blocking on the I today whether we can still reach the bottom row or not so I will show you guys here so we know we have considered the middle value as 2 so we are going to check whether we can reach bottom row on the day two or not so initially we are going to block all these cells till the middle index so here the first row and the First Column that is the zeroth row and zeroth column so the cells are given in one based index but when we write the code we will consider test zeroth index so the first row and First Column so this cell so we need to change the cell as 1 then we will block the second row and the First Column so we are going to block this with water so what we are trying to do here is that since we are starting from day two till Day 2 we are blocking all these cells so we know on the I today the ith cell will be one so here we are assuming that we are on day two and we came across all the days before right so we are blocking the previous days then we will be initializing a stack and we are going to add a cell which is containing 0 in my top row so the reason why we need to check is there any zero on the top row or not in the question it says that we need to start from top row right so in order to walk we need to have zero if there is water we cannot walk that means we cannot go further so in this particular example in the top row this particular cell is zero so we are going to append this row and column in my stack that is 0 and 1. so we are going to perform BFS on this one right then we need to pop this row and column from this stack so here R will be 0 and c will be 1. so then we need to check whether a row is the bottom row or not so here row is 0 this is not a bottom row so we need to move further also we will be having a visited set we need to check whether we have this row on column in my visited set or not here it is not present so we will add this row and column to the visited cell then we need to do BFS on this cell that is 0 through and first column on this particular cell right so we need to check is there any neighbor cells having 0 or not so here on the left side it is 1 and the top we can't go on the right we can't go further it will be out of bound but if we check the bottom we can go there is zero so we need to append this row and column to the stack that is one and one so now we need to pop the next row and column from this stack that is 1 and 1 right so now we need to check whether the row is the bottom row or not yes it is a bottom row right we can just return true we don't have to do anything further we just written true and based on this Boolean value we have to move our left and right pointers in the binary search right so we know it we have got true that is we can reach the bottom row on the second day since we assumed second day as my last day we don't have to check 0 and 1. we need to check the days in future so we will be having a result variable since it is true I will initialize the result variable with middle value that is 2 and we will move our left pointer by mid plus one so our left pointer becomes 3 right so middle plus 1 is going to be 3. so now we are going to check the Future Days whether we can find a last day in the future days or not so in this example 2 is the last day that we can reach the bottom row so we will be returning to as my answer that's all the logicals now we will see the code before B code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future in order to check out my previous videos and keep supporting guys so initially the left and right pointer will be pointing to 1 and the last day respectively then we will initialize the result variable as negative 1 at the start which means if we can't reach the bottom row from the any disk given we need to return negative 1. so here I will be writing a loop I will run the loop until the left pointer is less than equal to right then we will calculate the middle pointer using the left and right where the middle pointer will be the last day right then we need to check whether the peak to middle value is my last day or not if it is true we will make the middle value as my result and we will move our left pointer else we will move our right pointer then finally we will return the result so now we will see the is possible function so inside the is possible function initially we are going to create the 2D Matrix where I will initialize with 0 n and Mr rows and columns right then we need to mark all these cells to the middle day as 1 which means we came across those days so we are initializing those days as one then we will create a visited set then we will be creating a stack then we will check if there is any cell in the top row is 0 or not if we have a cell that is containing 0 we need to append those indices to the stack then we will write a while loop we will run the while loop until the stack is empty we will pop the row and column from the stack then we need to check whether the current row is my bottom row or not if it is true the Assumption of the middle value as my last day is true if it is not true we will just continue further where we will check whether the current row and column is in my visited set or not if it is not invisited we just have to append that in my visited set then we will try to check the neighbors of the current cell if there is a neighbor containing 0 we will append that neighbors row and column to the stack so we will run the loop until the stack is empty if the picked middle value is not my last day we will return false right that's all the code is now we will run the code so the time complexity will be n into M into login where n and M are rows and columns and login is the binary search that we are doing right and space complexity will be order of n into M thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
198 |
hey guys welcome back to the channel in our previous video we solved this problem legal 198 house rubber which is a very common big tech interview questions because it takes a bunch of tricks to make this work we had a really good solution which kind of made sense and we kind of explained it on paper too we explained how we derived this solution and this is our code right here on the right hand side and this how we came up by the to this good one it's going to be helpful if we i should actually visualize what's going on with the code as always on this channel we love to visualize now feel free to pause the video if you want to read through the problem just to understand what it's asking but again we take it one step further we visualize it again this is the exact same because we submitted the code i just went ahead and created a driver code based off the first example that was provided by so we know we're expecting an output of four okay so let's go ahead and step through the first okay so here we declare a function we define our variable norms okay which is just the houses and then we call our functions so this is our function scope they both point to the same nodes because it's the same variable then we're going to initialize our rob one and row two okay just exactly like we explained here on paper row one and row two are initially these two force got zero and we're just going to keep iterating and i'm going to till we get value okay so first we're in this we iterate through and through the norms right so we're in this first guy one we're going to create a 10 variable temperature we're just asking okay if i'm on this house my best choice is who do i want to pick do i want to rob this house and rob the house is two houses before this so it's gonna be between this house and rob one because like i said we're simulating having an array like this so we're on this first end one do we want to rub if we rub in we can only rub two houses beforehand so do i want to rub rock one which is this guy on our current end is he bigger do i get more money if i rub this first instance versus if i rub rob2 that's the question we're asking at every iteration of n okay so we're gonna ask the question now so temp was obviously if you rub one and zero one plus zero is greater than zero by itself right which is exactly what is right here one plus zero is greater than zero by itself so obviously temp becomes one and then we're going to set row two to the value of temp okay we're updating okay so now one we're about to be on our second iteration so around n equals to we're here right now okay same question do i get more money if i rub this guy plus the house two houses ago okay which is uh rob one is zero so this plus rub one two is he greater than if i just grab this guy one obviously two is greater than one so temp is going to become two okay row up two is going to be updated to two and rob one is going to be updated to the previous value of rob2 which is one okay rob one just change one pre the value of row two and wrapped is gonna be updated to temp which is two okay boom so now we're gonna go to the next iteration and it's three we're on this guy now okay who do i who's bigger do i get money if i rub this guy and two houses before him or did i just drop one house before him okay obviously three plus one is bigger than two so temp is going to update to four which is three plus one okay rob one is going to update the previous value of row two which is two and rob two is gonna update the current value of tenth which is four okay so next we're gonna go back to our equation so now we're on this last house we're asking the question again is it better for me to rob this guy and this previous guy versus just this guy who's bigger okay but by just this guy i mean the current value of 10 because remember we're creating this imaginary array we're keeping track of so obviously the answer will be four is bigger and now we're done with the fold there's no other elements in the for loop right so now we're just gonna have to return a value of four so that's it for the video i hope this was very descriptive and you were able to visualize what's going on and i'll see you guys in the next one as always
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
389 |
hey guys welcome back today we're going to be solving lead code 389 find the difference feel free to pause the video just to read through what the problem is asking for why find the examples more descriptive so given two strings s and c okay s is just a bunch of strings uh characters on the string and t is the same characters of s however they could be mixed up and there's always one additional character added to it in this case it's e so we want to output that additional character if that makes sense okay again you're going to be giving two strings s and c t is always going to have one additional character added to it we have to find out what that character is okay so i'm thinking some kind of hash map to keep track of whatever is going on so i'm gonna call it memo create a hash map called memo and i'm gonna iterate through s and t okay so for character and again i'm gonna do that's what i'm gonna s plus t this way i iterate through both of them with one for loop okay because if you use the plus sign for strings it just concatenates those strings so it reads through both of them i'm gonna say if that character we're on is in our dictionary if that character is an additional memo he's in there what do we want to increase him we want to increment his value okay memo of character of that character plus equals one zinder want to increment him else meaning he's not in there you want to add him in there let's set him to a value of one okay so now we're checking the character okay so once we're done with s and t what do we want to do now we want to iterate through our dictionaries i'm just going to say for item in memo okay it will include every item in our dictionary remember and what i wanted i want to say if that item the specific item obviously dictionary has key value pairs but if the value of that item of the key item okay if he shows up an odd number of times okay so meaning if we modulate him if modulus if that item the value modulus 2 if he if there's an odd count of him in the dictionary obviously that's the one extra item that is added because he has an outcome all it counts so we just return that item simple and it's guaranteed there's always going to be an item to meet this criteria so we don't have to do a else check we do after they check for hey what if should we return falsely there's nothing in there is guaranteed we're always going to have one character lecture let's go ahead and run this to accept it let's go ahead and submit it boom 83 62 perfect as always let's take it one step further again this is the same code again same example from lead code i just created a driver code to call this function so let's go ahead and call it and see what's actually going on so okay we declare our function in global scope we call that function in the function scope okay so now we pass in s and t to our function and we also create our empty dictionary memo right here okay so let's keep going now we're on the first character because we're going through s and t so on a right now the first a in s okay so we're going to at s plus t is a in memo obviously not so we're going to add a to mirror so with a value of one okay a is now a memo he appears one time so now we're on the next character b he's being memo obviously now we're going to add him b1 now c you see in memo we're going to add him c one okay then we're gonna go to d next it's d member no we're gonna add in good so now we're on c because we're done with s so we're gonna go back to a because we're iterating s plus t it's a memo yeah we're gonna increment him by one because that's what this l statement says if you up this if statement if he's in there increment him by one so he's gonna have a value of two the same for b same for c same for d so now e is the last character we're all now is he in memo no we're going to add him so now e has a value of one so next we're going to iterate through our memory dictionary and say hey anyone who has an odd count if his value might plus two equals one that's the value that's the item we're looking for so we go through a first a has evil count b has even c d what is the carbon so we return e and that's it for the video i hope it was helpful i'll see you in the next one
|
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
|
1,351 |
hi guys good morning welcome back to the new video again it's easy problem but the way to approach it the way to do it is something different and interesting so yeah um why not this problem uh so count negative numbers in a sorted a matrix so basically it's a short see Mark the word that is how you know that what optimizations you have to do I'll explain a bit but yeah please use everything that is given extra they could have given you the simple Matrix right if they have given you sorted ones so can you grab something out from this sorted characteristics of that Matrix given the M cos The Matrix grid which is sorted in a non-increasing order a non-increasing order a non-increasing order which means okay it's decreasing but it can also have the same values uh both row wise and column wise again star mark this both row wise and column Wise It's not against only sorted in the non-decreasing order like this but it's non-decreasing order like this but it's non-decreasing order like this but it's also sorted not decreasing order like this also cool that will actually make you sure that how to approach this uh return the number of negative numbers in a grid let's if we just quickly glance at the example then the example is uh this one four three two minus one so basically it is you know you can see it is sorted non-increasing it is sorted non-increasing it is sorted non-increasing it is sorted non-increasing for sure I have to fight non-increasing for sure I have to fight non-increasing for sure I have to fight one very if it had been in a contest if you look at the constraints n is 100 m is 100 if it would have been in a contest just go and quickly iterate an N across a matrix and find the number of negative numbers if it would have been in a contest don't think of any optimization whatsoever because the constraints it will just work on o of n in M into n and that will be it if it would have been a contest please go and do the very intuitive and the moves basically which is just simply trade on the entire matters and find the negative numbers but we have to optimize that right so for sure one thing which comes at the top of a mind while thinking of this okay it was sorted when something is sorted what all we can apply one very basic initial thing comes okay binary search because sorted binary search and see if you don't have this intuition and stuff just go and watch see it's a video of basic by research and its entire playlist of the different kinds of problems like different levels of problems for binary search so I highly recommend if you don't have the background of financial or you want intuitively think okay for every problem what is new how to think that okay how buying such is applied in this problem how to think the buying search will be used so for that a playlist is entirely for you just go and watch that but now we know casually okay it is assorted I want a number of negative numbers so simply go and just do a upper bound or a lower bound with the edge case such that you land up till here and all the elements which are negative so basically you have to do because you know all the negative elements will lie at one side as the entire row is sorted so I will simply go at every row do a binary search starting from the first negative element until all the elements first negative element under all the elements first I didn't enter all the elements and that is how I can simply going on to every row and doing a binary search on the column of every row I can find okay what is the location of the first negative element and up till end all the elements are negative so I can just say okay all these elements are actually the negative elements and that is for if the rows are n and the columns are let's say m but we are applying by and search are all the columns it will be o of log m right if repeat I repeat n r pros and Mr columns but we could have applied it but as an interviewer I know it has a better approach so I'll ask you hey optimizes this more and the it's the problem is also saying can you optimize it into o of n plus M so if you just clearly look at this concept what we use so far we used only the concept that the columns are sorted we did not use that the rows are also sorted right how about if we can use this part okay one thing I know for sure the rules are also sorted and I know my complexity has reached o of n into log M so the next better thing I can do is O of n plus M because it will be nothing but I can do by either o of n into log M or o of M into log n but better thing I can do is O of n plus M now to do of n plus M I can't do a binary search I have to either go out either o at every row or at every column to figure out how many number of such number such negative numbers are there right oh as I was saying I have to go at every row and every column to figure out how many numbers negative numbers are there so if I am at this particular row in all one I have to figure out how many number of negative numbers are there because I have to reduce the complexities such as that see I am helping you out okay you know you have to optimize you know at what complexity you have to bring to now you will think okay how I can bring by N I know I have to go at a 0 but I have to also find the number of negative numbers for that Row for that I have to find the number of negative numbers in that Row in work one time for at Max in total for every column I'll show what that means but yeah for every row find in over one time cool now what I will do is okay I have my pointer c as here it will just say okay now it is positive for now it is negative sorry for sure all the numbers after it are also negative because it is decreasing so if my C is here my R is here I can easily say okay for this row all the numbers because my C is here initially it is starting from the very start so all the numbers are negative so I can just say my number of negative numbers count is actually 4 for the last two now I can decrease my row okay cool again the C will remain same but now you know one thing that my rows are also sorted which means if this is negative it can be negative or positive anything okay cool it was positive but I want I'm only concerned about the negative numbers so I'll move ahead it's also positive tools no worries I'll just move ahead now it is negative for sure I will add two because up till here end it is all negative numbers now you will say Aryan when you will move up because now all the negative numbers in this row are done so when you will move up will you move up directly or will you go back I'll say I will move up directly I won't go back because if these numbers are positive for sure all the above numbers are also positive why because it was a decreasing it was decreasing so the above a number for sure must be more than or equal to the below number so for sure these numbers are same so you saw one thing what happened I am a trading on row once and same here also my column is only going forward one that's it is never going back so for every row accumulative like cumulative my column is just going forward entirely that's the reason what will happen again it is again positive so it will again go forward to C so again numbers and negative numbers are nothing but one again it is done entirely it will just go up and we again go up it is again negative so I will just again add a one that is the reason I will get my answer as 8 and that was the answer as it Q so what happened I know one thing for every row I have to bring out the columns in over one so maybe it would have been o of n but I realize okay I can't just get over in over one but for every Row in cumulative I can get my number of negative um elements in the column in O of M time because cumulatively you saw it is just going forward and then forward so basically it is iterating on this particular row M and also going once in this m that's the reason it's competitive of n plus n and that is how we actually built the solution of getting this commercial of n plus n and the code is pretty simple is just n m which is RNC and just going that above we initialize my r i initialize my C as I showed you in the beginning also then until uh both of them reaches the end which means until my R is less than or equal to 0 or my M exceeds M I'll just keep on going because I need to go on this particular thing entirely now I'll just check as I said if the number is negative I am good I should count the number of negative elements in that particular row but if the number is positive please increase your C pointer because C pointer will actually increase so I'll increase my C pointer if the number is negative just firstly you know you have to count the number rows negative numbers in that particular row and also for later part increase that row which means sorry decrease that row because this row is done what is happening this zero is done now you have to go to the next row to actually analyze that next row that's the reason I will just do a r minus and also to count the number of negative numbers in that row which have been like reduced just now but it would be M which is the number of columns minus C which is the count of which is the like just it is pointing to that location and that is how I can simply go and count and this complexity is nothing but o of n plus M ultimately I can just return the count time to open the same space over one that is how you can actually solve this version I hope that is foreign
|
Count Negative Numbers in a Sorted Matrix
|
replace-the-substring-for-balanced-string
|
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`.
**Example 1:**
**Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\]
**Output:** 8
**Explanation:** There are 8 negatives number in the matrix.
**Example 2:**
**Input:** grid = \[\[3,2\],\[1,0\]\]
**Output:** 0
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `-100 <= grid[i][j] <= 100`
**Follow up:** Could you find an `O(n + m)` solution?
|
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
|
String,Sliding Window
|
Medium
| null |
329 |
hello and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 329 longest increasing path in a matrix given an m by n integers matrix return the length of the longest increasing path in matrix from each cell you can either move in four directions left right up or down you may not move diagonally or move outside the boundary and wrap arounds are not allowed so if we look at this example here this matrix given to us our output's going to be four why because starting from this one we could go to a two we could go to a six and we could go to a nine so that's a total of a path length of four and there's no longer path um that's increasing in this matrix so if we kind of look at all the paths so from this nine we can't go to this nine because it's not increasing right it's staying the same with this six it's decreasing so that's not a valid path this nine can't go here this 9 can't go here this 4 can go to the 9 but then after that we can't go any further it could go to this 8 but after that we can't go any further because there's no increasing path then we could try at the 8 can't go in any of these directions this six could go to the nine but then it can't go this way that way and then we could go we can't go down we can't go left uh this one oh this is already the path that we tried uh this two could go here and here but that's only a path length of three whereas we have the optimal four so basically what we want to do is for each position in our um you know matrix here we need to try all the possible um you know paths that we can take and we can cut it off immediately once we see that you know we can't go any further so once you know say we start at this nine if we go to this nine and we see that okay well the value that we're at this nine is not greater than the previous value then that means that we can simply back out of searching because we know that this isn't a valid path anymore and notice how you know we explored here and saw that we couldn't go anymore and then when we went to this 4 we also came to the same nine what we can do is we can actually keep a memo dictionary to basically keep these paths in memory to tell us okay have we been to this nine here um and the way we'll do that is we can think of this as being kind of like an x and y coordinate plane oops so if this is the x's and this is the y right this would be oops uh okay this would be like point zero this would be point zero one uh you know zero two or sorry i think that's one yeah one zero uh two zero and we can assign coordinates to each one of these points and use that as our key in the dictionary and then keep track of whatever the longest path we could reach from that point is uh that way if we ever return to you know that point we can simply look into the memo dictionary and reuse the computation because we're doing a dfs there's going to be a lot of repeated work here because we have to try all possible paths and we obviously don't want to be recalculating everything so that's essentially the algorithm we want to take we're going to parse our you know uh matrix here from left to right um you know so row by row column by column and we're going to try all the possible paths starting from each tile and we're going to keep a memo dictionary to basically tell us if we visited tile before what's the longest increasing path you know from that tile that we can do so if we've already been there we can simply just reuse the computation instead of doing it again and you know we'll keep a global maximum you know path length that we have and we'll just return that at the end so that's the idea behind the solution it is a little bit tricky to implement so once we go into the code editor and i walk you through it line by line it should make a lot more sense because once you see it you realize it's not that complicated there's just a few little like minor details that you need to make sure you get right in order to solve this problem but otherwise it's quite simple so that being said i'll see you in the code editor and let's write the code for the solution okay welcome back to the editor now let's write the code remember that we said that we need a memoization dictionary to keep track of intermediate results that way we cannot recalculate things when we visit a tile that we've already been to before and that way we can save some computation so let's set that up so we're going to say self.memo is going to we're going to say self.memo is going to we're going to say self.memo is going to be an empty dictionary and now what we need to do is we need to define all the directions that we can travel to right we can go left right up or down so let's define that we're gonna say self.directions is gonna equal to self.directions is gonna equal to self.directions is gonna equal to um you know what are all the directions we can go in so one zero we can go zero one we can go zero minus one we can go what is it minus one and zero okay so those are all four directions we can travel in now we need a variable to store our result and we're going to initialize this to one because remember that a tile by itself is considered a path length of one if we look at this path here there's four tiles and we should output four which means that a starting tile can be counted as part of the path even though we technically haven't moved to another tile it still counts as a path length of one if you just stay at your current tile so if you recall from the diagram what we needed to do was go row by row column by column and basically try to find all the possible paths we can reach from a current you know tile so let's set that up so we're gonna say four row in range len matrix and we're gonna say four column in range lan matrix of zero we're going to say our result is going to be the maximum of whatever the result is currently and whatever our dfs function actually finds for us by searching that row and column combination so we're going to call into the dfs and try to find that best path at the end of this all we need to do is simply return our result this is the easy part what we need to do now is define the dfs function that's actually going to do the work for us so we're going to have this dsms function which is going to take the matrix as the input the current row and the current column now what we need to do is we need to check whether or not our current position this current row and current column combination is actually already been visited if it is then that means that we'll have something in self.memo that we'll have something in self.memo that we'll have something in self.memo and we can reuse the value instead of recomputing it which would be a waste of time so we're going to say if the current row and the current column is in self dot memo then we want to do is simply return self dot memo of the current row and the current column excellent otherwise we now need to do the actual computation so remember that a tile by itself can be counted as a path length of one so that's what the initial um memo dictionary value for a current tile should be set at so we're going to say self.memo going to say self.memo going to say self.memo of kero oops kero curcule is going to equal to 1. now what we need to do is try all the possible directions that we can go in so we're going to say four row increment column increment in self dot directions we're going to say that the new row is going to equal to the current row plus the row increment and we're going to say that the new column is going to equal to the current column plus the column increment and now what we need to do is make sure that this new row and column that we're moving to is actually a valid tile on the board uh what does that mean so if we're at this 8 and we tried to go to its right obviously that's not within the bounds of our matrix so when we try to access that index we get an index error and our function will blow up which is not what we want so we need to make sure that we're actually within the bounds so let's code that check up let's see if i can't realign this okay so we're going to say if our new row is within the bounds of our matrix len matrix and we need to make sure the column is also so the new column less than len matrix of zero and we need one more check remember that in this problem we're only interested in paths that are increasing there's no point of us trying all possible paths where some of them aren't even increasing we're only interested in the ones that are increasing because that's what the solution is looking for example if we're at this six there's no point of going to the one and then the one trying all of its possible paths because we know that going from six to one wouldn't be increasing so we don't care what comes after it because that part isn't valid so the rest of it will be invalid um also so we're only interested in going to tiles where one we have you know our values within the bounds of the matrix and the actual tile that we're moving to has a value greater than our current tile otherwise there's no point of exploring it we would just be wasting dfs's for no reason so we need to make sure that our current value so we're going to say matrix of the current row in current column has a value less than the tile that we're moving to so we're going to say matrix of new row and new column if all these are true then we can move to that next tile so whoops this should be current call here uh yeah now we can move to that tile and we can do the computation there so we're going to say that the best path that we can have from our current tile um which is going to be stored in self.memo self.memo self.memo call is going to equal to the maximum of whatever the current best path is so we're going to say currow cur column and one plus whatever the dfs can find by going to that next tile oops just self.dfs and we're going to pass in the self.dfs and we're going to pass in the self.dfs and we're going to pass in the matrix the new row and the new column cool at this point i think we're actually missing a parentheses here yeah okay cool that's why we can simply return whatever our answer is which we're going to be storing in the memo dictionary so that's going to be how we write our dfs function to solve this problem now let's submit this code and double check that it works and it come on yes it does okay cool so what is the runtime complexity of this algorithm well as we can see we have to iterate over all the possible tiles in our um you know uh grid here right so we go row by row column by column and what this means is that we're gonna have to touch every single tile in our matrix and in the worst case we won't actually be doing any dfsing because these um you know these checks will never be met so we would just be going one level deep and then bouncing back each time so what this means is that our runtime complexity is actually going to be bounded by the rows times the columns because we need to basically um you know store or do that many iterations through kind of our input right we're going to be doing it's bounded by the size of the matrix which is rows times columns and the space complexity is also going to be rows times columns because remember we're still going to be calling the dfs function once for each point and the dfs function will be creating a new entry in the self.memo creating a new entry in the self.memo creating a new entry in the self.memo for each current row and current column combination so that means that in the worst case well not in the worst case and every single time we call this uh function here we're going to be creating rows times columns entries in our self.memodic so that means that our self.memodic so that means that our self.memodic so that means that our space complexity is also going to be you know rows times columns so that's how you solve this problem this isn't particularly a tricky problem i think that the only hard part is kind of figuring out this part inside here how to actually figure out the best path and making sure that you're not wasting time by going to tiles that don't have a value greater than your current tile because then you'd just be wasting iterations and your solution can time out so you need to prune your search early by making sure that you're actually moving to a valid path otherwise this is a pretty standard dfs question you know you're defining your four directions and then you're going in each one of them and some sort of condition needs to be met whether or not you can proceed forward um but otherwise it's relatively simple um hopefully this video clear things up and seeing the code made you understand how to solve this one if you enjoyed this video please leave a like comment subscribe if there's any topics or videos you'd like me to make please let me know in the comment section below i'll be happy to make them for you guys just let me know what you want to see and i'll get that out for you otherwise in the meantime happy elite coding and have a nice day bye
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
1,295 |
hello so continue on this weekly contest 168 the first problem find the numbers with even number of digits so essentially the problem this is an easy one it says I'm given an array of integers when I return how many of them contain an even number of digits essentially how many of these numbers contain an even number of digits so basically this one has three numbers that's not even we don't count it this one has two it's even so we counted this one has one no we don't count it one we don't count it for yes so it's very straight forward the bounds are we have at most five hundred numbers in the array and the number can go up to 10 to the power of five essentially so please share forward and let's cut it up so the first thing we are going to do is just brute force in this you're just doing the simplest solution so and then we will go for every number in the array mylie and then we'll just convert it to a string and can't check the length right so it's just converted to a string that will give us a string so that we can get the length and check if it's even if there is increment the result and then return it at the end so very sharp forward okay looks good cement so it passes we can write this slightly differently in using the list comprehensions so instead of doing this entire thing we can just in one line with list comprehension we can use just some here so we want to count it if it verifies the condition that it's even so we say one if the length of a state are a string of a at the same way we did in the for loop this is equal to zero but what is a so we say for a in nuns and only if this is true and so that will count will give us one only if this is true otherwise it won't put one here and at the end we just want to get all of them so we just we add them up so here that's what I'm going with some here so this will give us the exact same result so now we submit we get so it passes a slightly different way we can do this problem instead of converting to a stream well we know that the bounds are at most the number is at most n to the power of five right so that means I'll keep this sum here but so at most ten to the power of five right so what do we know that numbers that are between so instead of doing this if here so we know that it has an even number of digits if it's in the range ten all the way to 99 right and so to get all the way to 99 with this range we just go all the way to 100 so from 10 to 99 it's two digits so that's even or if a is in the range so anything that is three digits we don't count it so skip that but those that are four digits that even that's even so that starts from 10 to the power of 3 because that's three zeros and one so it's four digits all the way until we get to five digits and so that means basically all the way and so nine four nines here and with the range here to get just to four nines there we can just go up to 10 to the power of four and then all a itself is the last one because 10 to the power of five is one and then five zeros so that's six digits so that's even so it's either that or 10 to the power of five right and anything like anything with so starting from 10 to the power of 4 this here that's five digits so it's odd all the way on top 10 to the power of five all the way until like nine here that's five digits so we don't want to include that right and so that's that this will give us the same result so just using the bounce the constraint and the problem those are always useful to read here of course in an interview they are not that useful but yeah or at least for an interview just they don't usually give them in an interview sort of cement yeah so that passes I think that's pretty much it for this problem it's a pretty easy problem yeah so if you I like in this video please like and subscribe and thanks for watching and see you next time bye
|
Find Numbers with Even Number of Digits
|
minimum-garden-perimeter-to-collect-enough-apples
|
Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
**Example 2:**
**Input:** nums = \[555,901,482,1771\]
**Output:** 1
**Explanation:**
Only 1771 contains an even number of digits.
**Constraints:**
* `1 <= nums.length <= 500`
* `1 <= nums[i] <= 105`
|
Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected.
|
Math,Binary Search
|
Medium
| null |
421 |
hello hi everyone welcome back to the channel so today in this video lecture continuing in the try series we'll be solving this problem maximums or of two numbers in an array so basically we're given an integer array Norms we have to return the maximum result of num's eyes or num's day where I and J lies between 0 and 1 and minus 1 these are the indices of the integers which are there in the array and were to pick two integers out of the array not necessarily distinct such that the zor of those two integers gives me the maximum possible value for that particular array okay so let's take an example to understand better let's say we have this array 310 525 to 8 and the maximum result is 5 or 25 which is 28 so 5 is or 25 which is 28 and that's the answer 28. fine so let's see how we can solve this problem and the one of the naive ways to solve this problem is easy that is just use brute force use two nested lobes start one pointer from the very first integer three and try to solve it with the rest of the numbers so threes or ten threes or five or threes or twenty five threes or two threes or eight and take maximum of these results okay and repeat the process for every single integer of the array for 10 try to Club it with 5 25 to 8 and then same goes for 5 25 2 and 8. okay and just find the maximum of these numbers and that will give me my answer okay so and the time complexity for this solution would be big of n Square where the very first iteration iterates over the array and the second iteration which starts from the right next element on which I am currently standing let's say I'm standing on three and the nested Loop starts from 10 which iterates over rest of the elements and try to Club it with three and the time complexity would be big of n Square now what is the space complexity obviously it will be constant because I am not using any extra space this is just a brute for solution and let's say if it works or not we can see that the constraints of the problem are the maximum length of the nums array goes up to 2 into 10 to the power 5 that is if n is of the order 10 raised to the power 5 then the operations would be this and we can see we know that in one second we have 10 raised to the Power 8 operations while giving 100 seconds to execute the code over these type of constraints okay that means this solution is not optimal because it would take me because it would take 100 seconds to execute and this is out of the time limit so this solution is sub-optimal so we have this solution is sub-optimal so we have this solution is sub-optimal so we have to devise a better solution let's see how we can do that now since we are learning about price obviously the solution which this problem has consists of tries so what I'm going to do is I'm simply using tries and I'm going to push all of these integers into the try how let's see that we know that the logic is simple we know that the maximums are for any number like take this number 3 10 the maximum zor a the maximum zor is for the numbers which has alternate bits at this position like for this case we had 5 and 25 why because let's write 5 in the binary format it would be zero 1 0 1 and let's write 25 it would be 1 which is 16 plus 8 then 1 okay now we can see that here we have 0 1 and if we Zorb them 1 0 so we had three positions where we had alternate bits okay we had alternate bits and that's why it gave me the largest number which is 28. so try to find those two numbers in the array which has maximum number of alternate bits towards the left side okay that's my purpose and that means we have to keep track of the bits of these numbers we have to perform operations over the bits to do so we're gonna store the binary numbers the binary formats of these numbers into the track let's see how we can do that the you got the logic what you want to do you want to pick two numbers out of these given them out of these given set of numbers such that those two numbers have the maximum number of alternate bits so that when we sort those numbers the resultant numbers is a maximum number so let's see how we can do that using price so let's write let's first write the binary format of these numbers so for three we're gonna write zero 0 1. so 168421 then for 10 it would be 16 8 4 2 1 then for 5 it would be 16 eight four two one for 25 it would be sixteen eight four two one okay then it would be then for two it would be sixteen eight four to one then for eight it would be sixteen eight four two one now these are this is a binary format of these numbers so let's see how we can push them into the try so we can take a try and from the try we start pushing this number so start from this bit which is the very first bit and we can say it is the 31st bit so although it is not the 31st bit but we will start pushing the bits from this bit okay so let's push it I am doing this just because all of the bits which lies towards left of it they're also zero and there's no meaning pushing those bits into the trash so that's why I'll start from here so let's start from here we try to push it into the try push zero here okay so push zero then move here again push zero so whatever we do is start from root I'm going to check if we have a child which is 0 which points to zero no we don't have any child that means we create a child which points to zero and that's what I'm doing it we have a pointer which points to zero and this node again points to zero because that's what I'm going to store here then we have 0 again we know how to implement price for a series of numbers now here this 0 points to this one so put 1 here finally we have one more one so we have one here fine so we have inserted this number into the try let's start inserting this one start from this number do we have a child which is 0 yes we have dialed here do we have a child for this 0 which is one no so let's create it do we have a child for one no so we have to create all of the other numbers as the child notes now this is also done let's move here do we have 0 as a child of root yes we have do we have 0 as a child yes we have do we have one as a child for this node no so let's push it then we have 0 then we have one so this is done let's push it let's push this number do we have one as a child for root node no we don't have so we create do we have one no push all of the bits into the try creating new nodes subsequently and this is done let's push this one do we have 0 yes we have 0 as the child of root node do we have 0 as the subsequent child yes so we have 0 as a subsequent child yes do we have one yes do we have zero no so we create 0 here this is done let's push this one do we have 0 as a child yes do we have one yes do we have zero yes do we have 0 again no so we create zero do we have zero okay 0 1 then 0 and then 0 again fine so in this fashion we have our try prepared so let's start from this root node and from this root node now we know that into this try I have pushed all the binary numbers I have pushed all of the like all of the numbers which we were given in the problem statement so the next step is I try to find two numbers which are basically which gives me the maximums are so that means pick every single number from these numbers so pick this one and try to Zorb it with alternate with the number which has a maximum number of alternate bits like start from this number this is basically zero one fine so what I'm gonna do is I'm gonna search into this try starting from the very first bit here I'm gonna put a pointer here and for this pointer for this bit which is 0 I'm gonna find a child for root node which is 1 because 0 1 gives me one and I want to maximize these number of ones and my final answer so check if we have one here as a child for root node yes we have so move here okay now that means add 1 into the answer add the corresponding so this is a 0 1 two three four so it is basically 16 so add 16 to the answer because a set bit corresponding to this position gives me a 16 s in the decimal number so let's move to the next it is 0 2 we have a child for the for this node which gives me 1 yes we have a child which is 1 here that means again add 8 into the answer then move to this no move to this bit and check if we have a child which is one no we don't have if we do not have then solve it with 0 so it will give me zero so we have the number till now is 1 the resultant number basically one zero now move to this one I want to find an alternate bit that is I want to find a bit which is 0 do we have a zero bit as the child node for this one yes we have here that means this will give me one and add eight four two one sorry sixteen eight four two so add 2 here now move here it is one so do we have a child node for this node which is 0 no we do not have we have one here okay that means just absorb it with one so it will give me 0. so it will give me 16 plus 8 24 plus 2 that is 26. okay so that's the answer which I have okay if I basically try to Zorb this number with the number which is constituted by this path fine so this was basically three now let's move to the next number which is this one which is 0 1 0. so I've got the maximum number which I have got till now is 26 so let's write it over here so let's move to this one which is 0 1 0 okay so let's start from the very first bit which is this one and start from the root node do we have a child which is one for this root node yes we have one here so put 1 here no do not put one put the corresponding decimal number which will be 0 1 2 it would be sixteen so add 16 into the answer because 1 0 will give me one so the result let's write the resultant number over here it would be 1. the resultant number would be one let's move to the next bit which is one do we have a child node which is zero no we do not have so let's draw it with one so we resolve it with one and it will give me 0 1 is 0. so we add 0. now let's move to the next bit which is zero do we have zero as the child node for this node yes we have 0 here that means okay I want to find one because I found 0 here do we have a child which is one no we do not have so that means again we have 0. add zero move to the next bit which is one do we have a child which is 0 because I have one I want to find the alternate bit yes I have it that means ones or zero will give me one so put a 16842 put 2 here then I have 0 here so zeros are one will give me one okay so it will give me one so we have one here so 16 8 4 2 1. so this is going to give me 19 as my answer okay fine so that's the thing the second number is 19. so let's try with the third number which is okay so let's try with this number which is I'm done with this let's try with this number which is 0 1 so let's start from the very first bit so zero do we have a child node for the root load which is one yes that would give me one as a resultant number as a resultant bit for this corresponding position and I'm going to add 16 here then move to this bit which is 0. we have 1 as the child node yes we have one as a child note for this so that would give me 8 as well so we'll have one here so then we move to this one do we have 1 as the child node for this no sorry do we have 0 as the child node for this yes we have 0 here that would give me 4 here now move here do we have one as the child node for this yes no we do not have one so at zero do we have 0 for this node as a child node for the corresponding node here yes no I do not have 0 so again at 60 plus 8 24 is plus 4 is 28. so that is 28 so if I draw this number which is 842 sixteen eight four to five with this number which is basically 25 because 16 plus 4 16 plus 8 is 24 plus 1 is 25 that is going to give me 28 so let's check for the next number which is this one so one zero one okay so let's start with this number and let's start from the root node so let's pick this bit do we have a child node for the root node which is one which is zero yes here so zoret with this node and it will give me 16. like in the resultant number I'll have one then let's see here one do I have a child node for this node which is 0 yes I have 0 here so add the corresponding number because ones or 0 will give me 1 in the resultant number so add 8 here now move to 0 do I have one as the child node for this one yes I have one here so add 4 again add 4 here okay because I've got 0 then I got 1 as well so I'm following this path now move to the next bit which is this do I have a child which is one no I do not have so Club it with zero it is going to give me zero now I'll move to one do I have a child which is zero no so Club it with one so it will again so this is again going to give me 28. so if I Club this number which is 16 plus 8 that is 24 25 with this number which is 0 1 which is again I think it is it's five okay it's five then it is going to give me 28. so it's again other way around I am in the previous case I was calculating 5 result 25 in this I'm calculating 25 is or five it is same case now let's move to the next number which is this one okay so zero one zero so let's start from zero do I have a child node for root node which is one yes do I have child node so that will give me like 16 add 16 to the answer so now move to the next bit which is zero so do I have a child node which is one yes which is it is here then move to this bit do I have a child which is one no so for this one add eight and for this add 0. driver challenge is one no add zero again zero do I have a child which is one yes add one so it is going to give me 25. so let's put 25 in the list and let's move to the next integer so you've got the idea what we are trying to do here we just build it a try and then I am picking up every number from the array and I'm trying to match it I'm simply trying to solve it with the most appropriate number in the try which we have builded over the same numbers from the array now here pick this number start from 0 do I have a child node which is 1 yes so add 16 plus move here do I have a child node which is 0 no 0 plus do I have a childhood which is one no do I have a child node which is one yes so it will give me 17. so put 17 here so we are done with all of these numbers and I have tried to Club bit with um I've tried to Club I have tried to Zorb every single number with the most appropriate number fine so out of this list the maximum number is 28 and this corresponds to the case when I took 5S or 25 and hence this is the answer is 28. okay and that's all so I hope you got the idea what we're going to try to do so let's just code the solution so here we have our solution class and in this class we have a fine maximums or function so let's first create a try node so struct try node so this try node basically contains only two values the first one is zero the pointer to 0 and the second one is the pointer to 1. basically each node contains either zero or one so each node either points to a type of node which is one or a type of node which is zero fine so we do not need an array of size 26 we have because we are just dealing with two types of characters and that are zeros and ones we can also use an array like this we can also use something like try note link 2. so this is again a an array of two pointers basically we have we can store two pointers into this array into this link array which points to the most appropriate node whether it is a node containing 0 or a node containing one fine so if corresponding to any node we have 0 as the non-empty pointer then we have 0 as the non-empty pointer then we have 0 as the non-empty pointer then that means this node points to zero otherwise this node points to 1. and like it may be the case that a particular node points to both of these numbers okay so let's just start from the let's start so let's just build the insert function how we're going to insert the words into the try or not the words basically the integers so let's see that so let's create a void insert function so it takes in the root node and it basically takes the number which I want to insert now just take a current pointer initialize it with root it will be used to insert the number so let's iterate from the last bit which is 31st bit and move till the first bit and check just extract the bit which is one left shift I and one and then check if this bit is one if this bit is 0 if it is not 0 we have two cases so if this bit is zero then what does that mean that means we're gonna what does that mean if we have this bit as 0 that means the ith the bit at the ith position is zero that means we create a new node so create a try node let's call it new node new try node and for this current 0 I'm going to put this node new node okay and move to the next node fine so that's what I'm going to do here so first here I also have to check if this current node does not point to any node if the zero component is equal to null pointer if it does not already points to a node containing if its zero component does not points to any node if it is the case only in that case we create a new node and we point the zero component for the correct node to that new node and we move to that new node fine otherwise just check if the if we have a one component for the fine so in this fashion I will insert the current number n into the try and I think that's all okay so that's how the number n will be inserted into the try so let's see how we can find the maximum of the numbers which we are checking for so let's create a function which is maximize zor so this function starts from the root node takes a number n and try to solve it with the most appropriate number present in the dry rooted at this root node okay so create a current node which is initialize it with root and then try to start from the last bit thirty first bit iterate over all of the bits and for the ith bit extract the ith bit that would be now check if it is 0 otherwise if it is not 0 if it is 0 then what I'm gonna do is so first initialize an answer which will store the final resultant zor of the numbers so if the ith bit is 0 then I will check if I have a child which points to 0 or 1. is not equal to null point that means the current node contains a child which is one if it is the case then that means Club this ayath bit with this bit okay so add the corresponding value into the answer and move the current to that corresponding child fine if it is not the case if we do not have a one which points to the null pointer in that case if you do not have a one which points to the null pointer then in that case we simply since we're gonna add zero and it is not gonna change my answer anyway just move to current zero fine and do the same for the bit if it is one if it is 1 then if check if the current node contains a child which contains 0 so if it is not null pointer then add this the corresponding value into the answer and move this current to the next the corresponding child otherwise move it to the child which we have fine so that's all I think we have to do so in this fashion I will solve my current number n with the most appropriate number present in the try and at the end return the answer okay and here let's create the try node so let's first create the root node try node which is the root node and then what do we have here we have answer variable then we iterate over this nums so iterate over this nums and just insert these numbers into the drag so insert them into the trial then again iterate over these numbers and try to Club the current number with the most appropriate number present in the try so pass call this function maximize or pass the root node and the current number and at the end return the answer so I think it's good let's see if it works or not okay insert okay let's see okay let's call it root maximize zor oh it's coming wrong answer I don't know why okay that's the mistake I'm doing I'm picking the ayath bit from the number N I need to pick the ith bit from the number n okay so that was the problem in this code so rest is good so let's submit it okay so that's all let's discuss the time and space complexity we can see that we are like inserting the numbers into the drive we have the longest number is of size like 32 bits and we have n such numbers okay and that's the time complexity which I'm using for insertion then for like I'm also calling this maximum zor function n times to get my answer and that means we again have we go and the complexity for that function is again we are searching for the most appropriate path and the maximum length of the path can be a gain of 32 length so this is also 32 into n giving me overall time complexity of big of n while the space complexity is like I'm storing how many nodes I am storing how many nodes I'm creating basically we have n numbers and for every number we have 32 size allocated and that's the space complexity fine so that's all for this problem and I hope you got something out of it and you learned something new I will be solving a lot of such problems in the upcoming videos of the try series and I hope to see you all in my next video foreign
|
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
|
949 |
Hello hello everybody welcome to my channel today one after the monthly challenge and problem is the largest time for giving digits swift died yesterday problem share dividend August challenge problem time set in comment section the smallest 2000000 subscribe Indian history of time can be written in directions number One two three four subscribe and subscribe 51234 one is the largest we can form of this for its an order of but can form pitra dosh in all 500 words can not be the first british in middle age the video then subscribe to the amazing will solve this problem subscribe 420 genital mutilation of this channel like 1243 liye channel 1232 4042 and take off but total station railway station oppo f1 this problem hair style dresses but it is not easy for at least for java developer because in java there is not invented library of function which can Generate All The Best Motivation In The Morning Have To Generate Per Motivation First And Ideological To Form Will Just Time So Let's Consider Is Let's Understand How Will Generate All The Best For Generating Stations Of All The Best Amazon Single Digit 90 Countries In The First Period From 28th Hua Tha one to three and 400 from this string fixed deposit to generate all opposition from string so lets all this name will recursively call the metrics and mail id on mode method in major method e will pass dresses spring net se call 100 for and will pass this References for The List of Spring Dale Store Duration Motivation Spring Which Will Generate This Is The Chief Minister Of Our Function And Will Generate Subscribe Function Effigy In This Village Set The Fennel In To-Do List A 220 Lights And Point To Our Less Sudhir Valley From for i20 ftu length of the world will remove it from running for first one to three four wheel rims subscribe to the video then subscribe to subscribe our will guide you will be removed from subscribe to i to heart code snippet for generating and the bermuda from this To Here By This Time West Creating History From A Quickly And Creating Electronic Polling Station Subscribe To The Amazing The Calling Attention On That This Dynasty Also Put On Motivation How They Check The Largest Time You Will Get The Largest Soegi Ise Like Share Getting A String of words its so let's move weights for example in one to three 4000 sudhir wa subscribe to the amazing minute and to initially it will keep there result which is the time result will start from the mp string and will also constructed at time Is Simply Match Caller Name I Always Spelling Of This Problem Am So Will First Checked His Will Clear String Using Back From Compare With Water Maximum Which Will Be Benefited From Evil 6 Harm Slippery Zero Means The Current Amazon 620 Low This And Third Welcome Pims In The time will come when they will update the result is a message every time I will do and out of treating all T-20 for boys will get the treating all T-20 for boys will get the treating all T-20 for boys will get the largest time 100 ko heres ko deposit for this is the largest subscribe the channel for more video subscribe time Complexity of dissolution of fact which is angry birds and disease for go loot programmer list generate solve this problem but for boys plus sex subscribe the channel subscribe 1234 200 meanwhile take index of 0123 sweet generating oil rotating all the element now will generate all the number On motivation using depression and D index is 100mb total zero is 1234 inductive this time of this will be 600 what we will do will run shesh luvve jain president sudhir vk the bank will check if any of two stop this three layers equal which means that Is Not Valid For Motivation Bigg Boss-2 Indexes Valid For Motivation Bigg Boss-2 Indexes Valid For Motivation Bigg Boss-2 Indexes Am So Will Justify Phal Samaj Theko Sukhe Hai Aur Quest To By Any Of This Possible Means Repeat Subscribe In A Reader Not Valid For Otherwise Will Get In The House That And Join Yogurt Where They Can Take for dawar string that disawar bhai adding this interesting to contest and other same and lost this will win a graph 6 - i - search - 6 - develop win a graph 6 - i - search - 6 - develop win a graph 6 - i - search - 6 - develop possible the all for index from this z1000's this to-do list elements 323 liquid to-do list elements 323 liquid to-do list elements 323 liquid subscribe My Channel And Use This Time Meanwhile Use Tube Caterpillar Like So Let's Implement For This Logic Soft Bind To-Do List Languages Which Will Not Give Bind To-Do List Languages Which Will Not Give Bind To-Do List Languages Which Will Not Give One More Plus Point Than 0.5 Inch Plus One More Plus Point Than 0.5 Inch Plus One More Plus Point Than 0.5 Inch Plus Do For Quiz-04 Clue 409 Plus Topic Subscribe And K i will simply continue that if wise will generator lets make a string which is equal talent church will get a graph i plus his sister making a string of similar i will get for displaying 6 - - a for displaying 6 - - a for displaying 6 - - a j - k so and this will Distinctions for b j - k so and this will Distinctions for b j - k so and this will Distinctions for b college sam appointed related call time witch app plus colony em no one will company is h voice less tree-2 beech is 2014 string is tree-2 beech is 2014 string is tree-2 beech is 2014 string is district similar and m.sc district similar and m.sc district similar and m.sc and compare to the sixty string visual art and Also under current result is computer how to time the last 20 will update the current result time Sudesh will update car adapter process in every possible they will not let compiled and sirvi is a scientist accepted for the first time complexity of resolution is 64 bismil revolver se zor q600 liye subscribe my channel thank you for watching my video
|
Largest Time for Given Digits
|
cat-and-mouse
|
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**.
24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`.
Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string.
**Example 1:**
**Input:** arr = \[1,2,3,4\]
**Output:** "23:41 "
**Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest.
**Example 2:**
**Input:** arr = \[5,5,5,5\]
**Output:** " "
**Explanation:** There are no valid 24-hour times as "55:55 " is not valid.
**Constraints:**
* `arr.length == 4`
* `0 <= arr[i] <= 9`
| null |
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
1727
|
1,209 |
Raipur will be good for premature ejaculation. We had asked this question on this track, what we used to do in it was that whatever classification adjustment was getting consecutive duplicates, Jio SIM character was found, I was deleting it, but this question is a little twisted. It has been done, okay, I will request you to show it, many people tell me that this is why Prince came, do it right, it is fine to do it for the first 5 minutes, as per my opinion, attempt it, solve the question properly, attempt it once and clear your mind. Find out to what extent you could think. Okay, now after that, when I will tell you that this thing has to be done like this, then only then will more interest strike in your mind. Okay, so let's read your questions, you will explain. Question: What are you saying, you are explain. Question: What are you saying, you are explain. Question: What are you saying, you are not arresting me till now, Italy will be great in two cups, you will learn a lot, okay, it is not necessary to vote from me, I am walking in the temple assuming that you are watching my lecture. Now you must not have come to 20 lectures that Navratri is going on in the cover of Star Plus, you look at that thing on that. Well, if you don't have much interest in the batter, let's sit and understand the deep logic of the question. We had decided that if you have come through it, then we will delete all the adjusted characters that we were getting. Okay, but what is the condition that we have given that they can be flames, they can be free. If it is for, maybe don't see connectivity, if we do the same, it will get murder, consecutive cut [ __ ]. If anyone gets it from the character, then we will it will get murder, consecutive cut [ __ ]. If anyone gets it from the character, then we will it will get murder, consecutive cut [ __ ]. If anyone gets it from the character, then we will delete it now. The value of the apps is for, okay, then tomorrow we will get duty forever, only then we will delete it, but There was another method of plastering, this was done by Mila, let it sit for 1 minute, it is fine, but it is not so in this poster, how to do it, if you see, now you will have to understand a little because we use the steps, whenever some such word is coming in our mind. That whatever last string is given is ok, if the data is given by matching it with its last character then it is ok, which is the last character, if we are comparing something with it then this is a reminder to me that people are using this time from the moon. Can do ok in this we have manual mind what will he say Awesome for what's next is B match done not done then what's next is team match not done BSA match or not then what's next edition launched not So, if it gets eliminated in the final list, then its answer will be only 20 percent. Let's agree with this. Let's say that if the question had remained CCDC of SB, if this question had come, then what would we know? Okay, first I would request you to please pause the video. Do add this, I was sitting with a copy and pen for a while. Whenever I watch any video of mine, okay with this written question, I was sitting with it on copper. This week's benefit will be there. Let's pick up the first item. Okay, so this is nothing next to it. There is no question of compulsion, I raised my head, what is this change next to the character friend, what is matching with us? Otherwise, I have written IG of tractor, I am matching, yes, but this time too, it is 12.82 which That we have given the value of one K but this time too, it is 12.82 which That we have given the value of one K but this time too, it is 12.82 which That we have given the value of one K to two, we will remove it, then the K stringer is left, then it is crossing the limit in kilometers. No, write down what C is matching then by mixing and if we get a total of two cups of air, then delete it. Then what will be left, we will apply this thing, is it matching, what is not matching, it is okay because this lamp is matching and not matching with anyone, its final output will be acid, many people, it is shaded, okay, now manually, so mind. Brother, I said, I understand, but explaining the code is a little trick. If we are showing the boat to light and computer, now what is our mind, then let's fit it to the stock and see how it is happening in the stock. If yes, then it will be simple, we will make a paste, very good college interest, Andy, then decide what was our concept, when we get time, then there will be no mention of graveyard, we will not have to put any input element in it, now coming to the steps, then these are set by the team. Is not matching then comes this African team then found the match, now what is our manual brain saying? Manual brain means what were we thinking in these flights or either we used to think oh brother this is the one from behind. If there is a match then Thappad's financials are fine then the experts will go back 123 liters by three steps, this is equal to three, it is fine and see if it was being received continuously, if not, if it is not being received continuously, then we will not delete it, then you come here. But it is okay poor Dedhsaiya that it has matched in the past and has done our work three consecutive steps, why do we have to go back till Jannat inches, Gokulnath has been purchased, if it matches all three then it is okay then what will we do with us Delete Will do these three, okay, do we have Bachchan in stock right now, Abhishek Bachchan, only and only D Pakka, now come Dipper, it's dip again, oh brother, it's a match, we will match, remind also, be depressed till the element of total under the moon. If we can, we will go till the bottom as far as we can, otherwise we will not be able to go till that, so I must mention in it that it is okay then we will come, but what B has matched and which has not been matched. Ignore Top is chatting with Pepper. Then comes the past, write it again, hey, the practice match is done, now we will go till the total is equal to three, we will check whether this match is strong, the match is increasing due to this, if the opposition is given here then we will not do anything, then he will look at the situation. The team is doing matches, it is not doing anything, very good, come again, write from Nakseer Vansh, Hey brother, if this match is done, then it will go till the level below, okay, it will go till the level of here also, if it is not done, then again one more here and subscribe to this. If we do this new stock difficulty of meeting again, we will delete the subscribe button, okay, then one will go equal to 5 inches, as much as the rally will be, we will see that all three have matched, for this, I will delete two deletes from this, okay Will start again if the plaster is gone again then it has matched, we can go till the end, subscribe, it is small, it is not total, so where is it from or not, what difference does it make, add Total Eclipse and subscribe to our channel. Now we have more and we are getting it, now you tell us how many people, tell me if you can code it, Delhi & if you can code it, Delhi & if you can code it, Delhi & Hot is not top, we basically have to go down the steps every time we get a match, top is from what element. Give but this solution is not create your toe nor the key value of alerts here is 100 ok, do you match 100 by walking closed on the bed or not tell me the complexity is not as appropriate as we are thinking, we people and in a butter way also. Like we can do, how could we do this wound, this is why we got to Delhi, let us make a batter, make the exact appearance of the character and the inter is okay and now make it tasty okay, we have made a paste of work. That the total which is being found in the character is okay, how much powder is it, then set it, if it is very good, then how difficult is it in life, the account is behind and I am doing it, then it comes that so it is doing traditional match, I was not doing one. Will make a new one and will put it as homework tonight. If the episodes match, then simply increase this chord, then it's okay. Then come again, we will lower the pitch for the match. It's okay and if you get three, it's like it's free in any collector's account. Why is it worth development, if the character's account is a test account, transfer character in the serial, if he comes equal to the account, then what will we do, we will delete this Diwali thing, okay, after deleting it, what bloody war do we have in the tractor, okay? Hey, let's go to our place, so we will match last year, now there is actor element, A limit is starting from sector forever, tractor appeared in 133, we have limited it, from now on, we will check the level of this left, total D. Can be in front, does not mean black spots in back, will check whether it has matched, after matching, will make a simple joint, will give big by doing two cricket matches or even come searching, what is the result, digital, is it matching, otherwise a new instruction. Will beat value payment vadh phyrate MP3 last one is WANTBI this time in the last chapter 20 total of behind site on twitter apart from the top of this country behind Hello that is a method of visualization like now if the actor is trying to represent pride then still Mila, which is matching from last year, we will increment this point, then we come to the seat, this time, if we had learned, which the society does not do, then there will be a seam, then we come again, we have matched with C to right because of the special, we have intimated. Give it again, it has been matching for many years, 3 comments, we will make it three and we will keep this one as three comes on the basis of its value, if the last character of money of any character is found by us, if the value of its account is It goes equal to so what will we do and if we delete it then now it will be deleted again ok we will delete it from the phone we have a new vector in tractor tell me what is left bb2 very good let's come now deep right so do the previous match If it goes, we will pay for it Three Hey brother, we have matched again, We will delete it again, Okay with passing, Deliver rescue city-1, with passing, Deliver rescue city-1, with passing, Deliver rescue city-1, Reddy Vishwas, while dancing, Will make you intimate with Two, Okay, Sorry, this is here with Two. Will pass and here too it will be three so what is ok now as we got three and what will we do again, we will make it great, now the actor, we have MT, he used to tease us in the off year by taking nothing in the tractor, the exorcist will do it once again. What did you get lighter? If you got a match from the one behind, then add to it is okay, so now go to the limit, we got that match to the right, what will be our answer, the answer will be this and one Bigg Boss 12 times President Scientific, sure, let's know your name, what is your method. Told him to go through all the president's example is fine and I expect you please man now you will be driving it so if you don't do it Brian when will you be able to learn this kind of daughter then I really show it is half fine let's assume. It is not working, it is okay then it is bugging me, if you think what is the importance in it but it seems wrong, you have got this thing, it is not visible and I want to grab the camera, you can use the edit list in it, friend, the speed is fine. Have tractor, our paste has been made, lighter and pair of characters and bricks are ok, it is very good, it is fast, ok, now speed is anti, there is no problem, nothing can be left for communication, then comes BP, then BBA and ok, see the match with speed. If we don't do it then we go to the beach, we found B22 as big as a pinch, we will delete it, okay then what is left, Peever, now talk about whether to match seat happy or else sewers come again, it is matching like jeep, yes, otherwise life again. Till then click on the next win which will instrument it J2 Match Cricket Will delete it now what is left Pi Vanshiy used to think Tipsy floating on 3113 but by matching the last elements with maturity because it was Titu Hey this is then equal to you Princess cut and then Vanshit on the voice, let's write it down here, 30 minutes, what is it's over by matching pistachios, it's fine, now when the child came next, he was not matching behind Aai Jo, he will do an accident, set one. And yours was the next one, because for this match we will fit the tools like two, filled in the match method, then deleted these, okay, now what is left, one, then what is the next one, who is matching, what is behind, otherwise? I have a very nice print that the happy figure is not matching with this, so what is Vansh happy about, which is matching at the back, as if it is matched, what will we do, we will delete it, now what is left, 151, okay, then comes the next oven of risk. I am not daring, it was a fracture, so he understood it, so as soon as I delete it, father P 151, okay, then comes the next one, which is not matching with I, and I will subscribe again as soon as possible, so it was that What to do, you are the only one who has understood, let me tell you one thing, I am telling you one thing, like it is a string, okay friends, I am telling you this question tax, okay it is a string, result and in the result, we want that If you add a character five times and then play the character again, what will you do? You will apply follow-up. Okay, let's equal zero to eye follow-up. Okay, let's equal zero to eye follow-up. Okay, let's equal zero to eye lashes, add five more times to the result. Then you will do a sandwich. Okay, let's equal. Eyelashes from zero Two characters are required, its correct answer is this egg of five bars of Baroda, remember this, keep this in mind, it is very useful tips, please subscribe to my channel, those who have problem in Raghwa, I can assure that if you How to make a character and speak in a free style cuisine, the sacrifice of scientific things, the things which were input last by Tubelight, which are the last ones, we are checking them, it is not necessary to subscribe the subscribe button and tractor, if not then think something. Ghr simple push back to back use because subscribe loose the character and set it if it would come like this or make STD gift pack a vector, we will make the back element of it okay which is the back element and the new element in We are setting that if it is mother then STD back has reached the last element but it is a vector pair, on this the first element of the pair is the character of the second element, then dot first if that character matches, this sentence is fine with C. Still, what will we do like State Bank, we will take a new top and set it on it is very good, sorry, it will come here, it did not match, okay, we will make it off match, then the friend will have to check whether things are different, WhatsApp if not match. Kiya if it doesn't match then it is top ten cement okay when tractor is the last element and the one who is us stop actor is the last one who is the president if he is setting sexual and was not matching but market made from sample If it matches from different years, then what we have to do is that if we want to increase the account of the last character percentage, then STD.back increase the account of the last character percentage, then STD.back increase the account of the last character percentage, then STD.back has reached, we will add the second part of the vector character and nature, has reached, we will add the second part of the vector character and nature, very good. Now what we did is that if at this time of need not be back dot is equal to the anxiety, if you want to remove that element then click on STD WhatsApp Bakarta Last Element button, now answer and return result of school association and Which is quite what we have from SD, right? Ras daughter and I have already subscribed and subscribed. First RSP okay now let's run it. Subscribe and I hope you liked it very well which I have done. If you like the video then please. Subscribe to you guys by commenting
|
Remove All Adjacent Duplicates in String II
|
design-bounded-blocking-queue
|
You are given a string `s` and an integer `k`, a `k` **duplicate removal** consists of choosing `k` adjacent and equal letters from `s` and removing them, causing the left and the right side of the deleted substring to concatenate together.
We repeatedly make `k` **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It is guaranteed that the answer is **unique**.
**Example 1:**
**Input:** s = "abcd ", k = 2
**Output:** "abcd "
**Explanation:** There's nothing to delete.
**Example 2:**
**Input:** s = "deeedbbcccbdaa ", k = 3
**Output:** "aa "
**Explanation:**
First delete "eee " and "ccc ", get "ddbbbdaa "
Then delete "bbb ", get "dddaa "
Finally delete "ddd ", get "aa "
**Example 3:**
**Input:** s = "pbbcggttciiippooaais ", k = 2
**Output:** "ps "
**Constraints:**
* `1 <= s.length <= 105`
* `2 <= k <= 104`
* `s` only contains lowercase English letters.
| null |
Concurrency
|
Medium
| null |
772 |
you're going to look at the u problem called basic calculator number three so this question has all the problems that we counter in basic calculator number one and two so you can see here for our string or for our expression we're going to have plus minus multiplication and divisions as well as we're also going to have open and closing parentheses and we can also have negative values uh and positive values right so if you haven't checked out basic calculator number one and two i highly recommend to check that one out before this one so basically you can see here we have an example like one plus one in this case is two right we can also have like this like minus and a division but you can also have a brackets right so like i said again we have to treat brackets is like a very like a priority so we have to complete what's inside of brackets first and then what's outside of brackets right that's our rule and then in terms of you know like divisions and um and then also like subtractions like we have to complete multiplication and division first and then we have to complete plus and minus after right so in this case we have to follow that priority so in this case you can see here we have an example like this right so we first complete what's inside our bracket right so in this case our bracket we have something like this which is exactly what we did in basic calculator number two so in this case five times two is ten plus five is fifteen so what once that's done right we're just gonna backtrack to the parent stack which is here so we continue right so 15 divided by 3 in this case is 5 right so 5 times 2 in this case it's 10 so we have 10 here plus right so once we get rid of the multiplication we now have to deal with the brackets right what's inside our brackets so in this case what's inside a bracket we're going to do our dfs down to this level and then we're going to have our multiplication complete first right so 6 times 2 or 6 divided by 2 in this case three plus eight in this case is eleven right so once we get our once we complete what's inside our brackets we're gonna backtrack return the result value back to the root where the parent stack in this case is eleven so in this case it pretty much is just a simple 10 plus 11 which is in this case is going to be the value for our current level right which is basically 21. so in this case you can see here we're returning 21. um so you can see here um to solve this problem basically there's really nothing new right we're inside our bracket we just have to treat it as like a basic calculator two a number two question and then as overall like how we're gonna do our dfs we're basically just going to treat it as like a basic calculator number one right so there's really nothing new i don't want to go over we're-teaching those want to go over we're-teaching those want to go over we're-teaching those stuff here so basically what i did is um i basically have the index starting at zero character array which just has the same setup as basic calculator number one um and then inside our dfs function right we're basically just going to traverse or iterate the entire string we're gonna use the stack um and then the initial operator is a plus sign um the goals we want to be able to just like i mentioned in basic calculator number two we want to get rid of we wanna group the multiplication and divisions together right in a single uh in a single integer value so that once we uh done our iteration or in this case let's say for their situation where you know where we are visiting a closing bracket we can just break out of it getting all the values in our stack and return our total for what's for all the total value for what we have inside our brackets right so basically the idea is that first we iterate the entire string um if a rate at index does not equal to empty space then what we do is we do the following right so in this case first we check to see if it's a digit if it is we build a number okay and then we're going to parse it and then we have this function called insert element we basically um insert the element onto the stack right so you can see here we're following these conditions here if the operator is a negative value we just do that if it's a modification symbol right a star symbol we can just pop the top element out of the stack and updates the current num if it's a division we do the same thing and then we just push it onto the stack very simple uh so we talked about it in basic calculator number two already and then what we're going to do then is um after that we're just going to continue to iterate the index or increment the index by one but let's say if there's a situation where we encounter an open parentheses then what we had to do is we have to do our dfs right and then don't forget we also have to insert that into our element right because our operator could also be multiplication right our operator could be a division right i could have a five divided by bracket two plus five right inside of bracket right it doesn't have to be like plus sign so in this case we have to call this function again to insert the current num that we have inside our brackets onto our stack correctly and then we can continue right and if it's a closing parenthesis we can just break out a loop or if the index is out of bound we can also break out a loop as well and then otherwise if the current character is a plus is a negative it's a multiplication symbol or a division symbol we can just uh you know override the operator variable right so you can see that basically this is the core of it we basically iterate through the entire string and at the end we basically do exactly what we did in basic calculator number two try to get our total by iterating all this uh all the elements that we have in our stack to get the sum right and then you can see here um like i said again we're basically trying to get rid of we're trying to group those modifications right so you can see here those multiplication values these are modifications or divisions right modifications we're trying to turn them into a single integer value so that like five times two is basically 10 6 divided by 2 is basically 3 we have 3 write a single digit or a single integer value onto the stack and then at the end we basically treat that as like all the values are just addition right we add each and every single elements onto it there could also be negative values right and at the end um you can see that this is our dfx function we just keep we're just calling that and then it'll basically repeat the process doing our dfs iterate the entire string and then get the things done right so we can see that this is basically how we solve the problem and time complexity in this case is basically going to be big o of n where n is number of characters that we have in our string
|
Basic Calculator III
|
construct-quad-tree
|
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, `'+'`, `'-'`, `'*'`, `'/'` operators, and open `'('` and closing parentheses `')'`. The integer division should **truncate toward zero**.
You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`.
**Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
**Example 1:**
**Input:** s = "1+1 "
**Output:** 2
**Example 2:**
**Input:** s = "6-4/2 "
**Output:** 4
**Example 3:**
**Input:** s = "2\*(5+5\*2)/3+(6/2+8) "
**Output:** 21
**Constraints:**
* `1 <= s <= 104`
* `s` consists of digits, `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`.
* `s` is a **valid** expression.
| null |
Array,Divide and Conquer,Tree,Matrix
|
Medium
| null |
46 |
in this video we will solve lead code problem number 46 it's called permutations and the task is here to print all the permutations of a given list not print but return a vector which consists of all the permutations of the input list for example here the input is 1 2 3 and we know that 6 permutations can exist since 3 factorial is 6 3 times 2 times 1 equal to 6 so you have to write down all the possible combinations all the possible places a given digit can take so one can occur in the first place so we will write one in the first place then we are left with two positions and we are left with two digits two and three so in one case two occurs first followed by 3 in the next case 3 followed by 2. so this is the two possibilities when one is at the first place similarly when 2 is at the first place we are left with 2 places and two digits one and three and they can occur one after other and here three occurs at the first place so in total there are six permutations possible so how we can solve this problem uh we have this one two three so what we will do let me write in the center so we can break it into three parts where one is in the front and we have to permute two and three only so we have reduced this problem from size three to two so what are whatever are the possibilities with this two digits we will add one to all of them so one is fixed as the first place and next two places it's that so whatever is the function here that calculates the permutation of one two three we will apply the same function on this smaller list and similarly 2 can be at the first place so we fix it and we call the same function on 1 and 3 the remaining digits next three will be at the first place and we will apply the same function recursively on one and two so we are breaking reducing the size by one next this will return something so 1 is there we will not carry forward that so we are asked to solve 2 3 permutations of 2 3 so we will fix 2 in the beginning and then call it on three so here we are now left with just one element so how many permutations for just one element are possible just this one that is there is only one possibility so one position one digit only one permutation is possible so we call this and the second possibilities we fix three and call it on two similarly here we will fix one and call this function on three so we are just expanding the recursion tree here and next three will be at the first place and we will call it for one and here one will be at the first place and we will call it for two and then fix two and call it for one and our base case is that if the size is one or 0 return that itself so here what will this return this 3 will return we can expand it further and this will return this value itself so when a value returns what it will again return a list of different possibilities let's say p1 p2 p3 so on a smaller problem it returns a list so what is our task here we have fixed one at the first place so what we will take uh what we will do we will take all these individual vectors and append one to it so this becomes one followed by p1 1 followed by p2 and so on so this returns 3 we append 2 to it so this returns 2 3 and this side when it finishes it will return 3 2 so whatever is the result just append it in the beginning the digit that we have fixed so now this returns 2 3 this returns 3 2 both are returned here so here what we had done while coming down the tree we had fixed one at the beginning and we tried to calculate the permutations of this and we have now the solutions these are two three and three two so one is fixed so it will append one to both of them so take this append one to it in the beginning so it becomes one two three and take this one append one to it becomes one three two and these two values will be returned here so we have now two values in the result now this branch will execute it will come here this three will return so 1 will be appended to it so it will become 1 3 and here 1 will return so 3 will be appended in the beginning so it will become 3 1. now these two values are returned here the place where it will they were called and here we had fixed 2 in the beginning and we had called it for 1 3. now 1 3 has returned with two values 1 3 and 3 1. so what we will do we will take all those values returned and just add 2 in the beginning so it will become 2 1 3 and this is 3 1 so in front of this we will add 2 3 1 so this branch also returns these two values or we can have we will have a result which will be a vector of vectors where we will be pushing these values when they return so the result is now four values similarly it will return 1 2 and 2 1 and it will be appended after 3 so it will return 3 1 2 and 3 2 1. so this way all the branches will ultimately end here so we have considered it for all the digits as the first digit if it has k digits each of these digits will occur k minus one times here we had three digits so each digit will occur two times in the beginning so we have seen all the possibilities so this tree will remain similar let's say we have four digits now so what will happen let's create five so one branch we will fix one and call it on 2 3 4 5 next branch will denote 2 in the beginning and the function will be called for 1 3 4 5 next branch will be when 3 is in the beginning and the remaining digits are one two four and five and so on two more branches will be there one four will be in beginning next five and the four remaining digits so what we are doing here is we have a function p and we are storing everything in result what we are doing uh we are calling it on p and this is the vector v so what we do we erase one digit so we can have a loop for i equal to 0 to 4 and what we will do we will erase 0 or v dot erase at position i so in first case what will happen it will erase at 0th position so what will be v now 2 3 4 5 so it will call again on v and this we will denote if i is equal to 0 then this v will denote 2 3 4 5 exactly same as this when i is 1 it will erase 2 so 1 3 4 5 will be remaining like this so this is v and this is i which we are erasing and we are calling it and we are capturing the value in some temp variable so this is a list of vectors so once this call returns this will denote the termination of this branch along with different results we will iterate all these results and what we will do this element is v i this is the element that we have erased so for all r belonging to this result we will append this e so we will have a vector equal to e followed by this r into just one vector so this is exactly what we saw in this example and finally when it's done for all the cases that is each digit has been put in the front as the first digit the result will hold all the possibilities like this so you can try it once on yourself and convince that this should work each digit will occur in the beginning and we can permute on the remaining digits so let's write the code for this and this is a good problem it has 3500 likes and 102 dislikes so let's first write the base case if n is less than or equal to 0 less than or equal to 1 then either it has 0 elements so this nums is a vector of hint and the return type is vector of ends so we include it in curly braces so it becomes a vector of ends so at this moment this v is exactly same as this nums now we will denote delete one of the digits at ith position so this will calculate the iterator that is pointing to ith digit and it will delete that now this vector has one d less and we will add that digit in the beginning and to the permutations of this new vector smaller vector now we have this result which is a vector of ints and this denotes the permutation of this vector which is same as this vector just one digit less so now our task is just to take all these vectors one by one and append this ith digit to it in the beginning so we are adding this numsai which we are deleted in the beginning of the results of this and finally we will add them to the result so it works for this test case let's try a few more and it works well for all the test cases so let's go ahead and submit and our solution is accepted although we can see how we can improve this time complexity it's better than 20 and run time is 16 millisecond let's try a few more times and it remains around that mark so i hope you understood this problem uh the core idea is that every digit in the list will occur equal number of times in the beginning so we try all the possibilities we just remove one digit from original list put it in the beginning fix it in the beginning so we have k digits in the list we have k places to arrange them and we fix first position where we position one digit at a time one after other and we are left with k minus one digit so we call this permute function again on that smaller list and whatever list comes we append them after all the digits so that's the main idea
|
Permutations
|
permutations
|
Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**.
| null |
Array,Backtracking
|
Medium
|
31,47,60,77
|
939 |
hey everybody this is Larry this is me doing extra prom on February 21st of um well 2024 whatever this year is uh let's do it let's uh let's find one we have't done yet and Alo and that's RNG it um hopefully the mic quality is a little bit better my apologies if uh last I didn't realize that the mic just kind of died by itself I guess you know like all old things uh it happens but uh but yeah let's take a look at today's p uh today's fun extra PR 939 minimum area rectangle uh let me know in the comments by the way if the sound is still having some issues um I'm still tuning it a little bit um but I mean I played around with it and before this recording I played around with it and it seemed okay but if it's running into issues again definitely let me know uh my apologies again cuz you know I mean you I'm not here trying to hide this content from you but you know technical difficulties do happen so let's go uh all right so you're give in way you have a lot of points return the minimum area of a rectangle okay so the sides have to be parallel to XY which is the biggest part otherwise you have to some kind of like you know if it's not access a line you have like weird rectangles which is actually a really hard problem at least hard for me uh might not be you know but yeah okay so basically you want the minimum area of a rectangle that you can fit here okay and here basically the idea of a rectangle is um two points sharing an X and then two points sharing a y right something like this and you know or pairing them up okay hm how do I want to think about it so the points are 500 so that means that we probably shouldn't do more than n Square log n or something like that I would say um but um hm well I think n square is probably I mean okay how I'm trying to think about different ways of um iterating it right and the thing that because this act as a line the thing that we can say is that um is that you know we can pick one line one vertical or horizontal I guess it doesn't really M or like you know for symmetry reasons it doesn't matter um and then you know you can iterate each pair and then maybe see if you can find another pair that has the same uh on a different line right how would that look so that would create um trying to think what's the CEST way around that is like we can definitely do a lot of lookups but I'm just trying to think whether we have to I mean okay I mean let's just kind of start doing it and then we'll worry about um we'll worry about issues later right like I think it's fast enough but I could be wrong so we'll see so basically the idea is that okay n is length of number of points okay and then now we want to um let's just group them together I mean there a couple ways you can do this data structure but I want to group them together by x's and then y's right so something like maybe coordinates is equal to collections default. de of list and then now you have for XY in coordinates of or in points and then coordinates of x. append y right something like that and that basically allow us to get okay for each X you have all the Y's together right and then now uh maybe for X in coordinates. Keys we want to just sort them just you know just to be uh just make sure our data is in cleen way you could also sort them beforehand I suppose but you know it should be the same thing either way uh or like it still sums to technically I guess this is slightly faster because it's summation of the log ends or whatever or summation of K Lo cave uh we or the summation of K is n so this is technically a little bit faster I think but uh but it's not a big deal okay um yeah and then now we can do and maybe we can actually just do it now right actually um maybe we can do something like look up right and look up is just a generic lazy term uh let me actually also make this into a list and basically what we want to do is for y in coordinates of X right so now you have X and Y and then you have maybe something like um oh but now trying to think for a sec I think this is fast enough it's very deceptive that's why I'm that's why this is a little bit confusing looking or give me a second to make sure that what I say is true yeah Ian I think this is true but um yeah so maybe actually m is equal to length of uh coordinate of X right so then we write this as for range of M for uh yeah okay fine right for J in range of I + 1 M so basically now we're range of I + 1 M so basically now we're range of I + 1 M so basically now we're looking at all the points right on the x coordinate um and the reason why this isn't too slow even though you have this coordinate you have like x * y have this coordinate you have like x * y have this coordinate you have like x * y * Y which looks like it's like 500 * Y which looks like it's like 500 * Y which looks like it's like 500 square but it's not really because the summation of points are like the worst case scenario is if they're all on the same list and then it's just 500 square um so yeah I think that's basically roughly the idea but yeah for this then now you now for each pair and I'm a little bit lazy here so we'll see if I need to optimize but basically you have coordinates of I you have coordinates of J um and you want aend X right so that's basically the thing but you might be for that uh X is in order right actually is not whoops okay now X is in order right so if x is in order then there couple things right okay so maybe we have a best is equal to Infinity because we're trying to minimize right um because this is in order the previous point is going to be the closest right so actually I mean I made this into the list but actually you don't even need a list because the last if we sorted this then we basically like did a sweet blind thing and the Cod is going to be the last one you see right so actually this doesn't need to be a list then it's just like a regular lookup right so then now we can do something like initially I didn't want to make that assumption but I think actually maybe that's a little bit cener right so you have this is the key so if this is in lookup that means that lookup of this so this will contain the last x coordinate used with this key right and then um the current x minus this it's going to be the height or width or whatever so then best is equal to Min best of this which is the height or withth I forget uh times the other coordinate which is coordinates uh J minus coordinates I and that's it yeah and then we set this to X instead we pending but uh whoops did I this is in the list is it coate sub oh whoops this is uh x sub I whoops that's why I did it that way but then I think I got I confused myself a little bit yeah maybe I should have Alias those things yeah let's give us a it o oh I forgot to change the Infinity case uh I was thinking about it when I was writing Infinity but then I just forgot about it so that was just silly but uh yeah okay I mean I only had some work that it wasn't fast enough cuz if this really does look a little bit yucky to be frank uh looks a little bit messy I mean like I said this looks M square and like this thing but in the worst case um well this is n Lo n this is Nish and this is another n so it looks a lot weird but it's not actually n Cube because you know for each point it can only be in one of one row right each point can only be in one row so that means that if all the points are in one row this is going to be M square and if ignoring this n again and with all the points out in different rows then this is just going to be one square and then just m l m so it's like in the worst cases between M or well just m Square in general or n Square in general so even though this is very messy looking this is n square and that's how we kind of got that B made a silly mistake cuz I kind of rushed it a little bit um you though I kind of knew it but then I was just like cuz when I voted I was like mental note remember to uh you know there's no possible thing but I just forgot about it uh happens a lot I don't know no stick so I don't you know I don't pay attention too much sorry about that anyway uh that's all I have for today let me know what you think let me know about the mic the sound and everything in between uh yeah let me know what you think about this poem it's kind of fun one to be honest uh yeah uh actually let me uh I'm curious is there like an end Square way oh there is an N Square way oh no my way is n Square way but I forgot oh but there's an N to the one halfway oh I guess this is the smarter way I kind of did mine in the funky way H cuz then you just check to okay fine you just basic before okay whoops I am pretty dumb today then but the way that I did is kind of cute um I guess this is the way that I did it but I don't know how you get the N to the one to the 5ifth or 1.5 the one to the 5ifth or 1.5 the one to the 5ifth or 1.5 power uh I don't know and I mean I did do it this way and I did I do know that this is faster than the naive n square but it is I don't know if that I would analyze it quite that way but uh oh well I forgot that there's a naive way though which is kind of weird don't know what to say anyway that's all I have for today though let me know what you think and yeah stay good stay healthy to go mental health I'll see you later and take care byebye
|
Minimum Area Rectangle
|
valid-permutations-for-di-sequence
|
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`.
**Example 1:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**.
| null |
Dynamic Programming
|
Hard
| null |
782 |
welcome to september's lee code challenge this problem is called transform to chessboard you are given an end times n binary grid board in each move you can swap any two rows with each other or any two columns with each other keep in mind it has to be the entire row or the entire column we turn the minimum number of moves to transform the board into a chess board if the task is impossible we turn negative one so what's a chess board well basically it's a board where no zeros and no ones are four directionally adjacent and it looks like this checkerboard or chessboard pattern that we all are familiar with okay so before we attempt to do any recursive backtracking methodology like i did let's stop right there because that is never going to work it's just simply too difficult and it's uh time complexity is going to be way too heavy for that to ever work so what are some characteristics of this board that it needs to have in order to for it to be transformed to a chess board well let's think about this well the first thing that we can kind of tell needs to be true is that for every row there has to be uh well if it's an even number there has to be half ones and half zeros right you can see here there's two zeros and two ones and the same needs to be true for all columns now what if it's a what if it's flipped what or what if it's an odd number of columns and rows well that makes it a little bit difficult right because then we'll have to have i guess what you can say n divided by two minus one number of ones or zeros and n divided by two plus one number of ones or zeros and that has to also be true okay so we kind of intuit that there's some characteristics here that need to be true but there's a big one that actually we can take a step further and realize this also needs to be true one of the things we should realize is the actual number of patterns for each row and each column needs to be at most two so if you don't believe me just think about if we had like something like this would this ever be able to be transformed to a chessboard and you can kind of tell already no it's not because even though for every row we have all these ones at some point at some column there we're going to have three ones which means it's never going to work because we can flip this you know put the zero there uh and that's fine but now this one is still here and that one's going to stay here so no matter what we do to flip this is never going to be a chess board right so what that means is whether there's an odd or even number of rows and columns there has to only be a pattern of two versions at the most for all the columns and all the rows so that's interesting right we have to have two patterns for every row and column okay now if once we figure that out actually then it's just a matter of going through all the rows and all the columns and comparing it with the pattern that we actually want so the patterns that we actually want here would be like either zero one or it would be one zero right and what we can do is just go through every row and every column and check to see how many of these are different and the number of them that need to be different have to be even okay and that's actually going to be the number of flips that we make so here with this example we can check okay how many of these are different and we can go through and see okay these are the same they're the same this is different so we have two moves right for this so this column we have to move well it'd be two divided by two because each time we do two we take care of two columns right and that would mean that would be one move so we can actually calculate go through all the rows or not even all the rows just the two patterns that we have and check with these two patterns how many would we need to flip and as long as that number is even we'll take the minimum for the number of columns that we need to flip and the number of rows we'll have to also check the rows to do the same thing and to make it a little bit easier what i'll do is transpose this board right here and do that same algorithm for both rows and columns all right so let's first initialize n to be the length of board and like i said we need to first transpose right and get another version of this board that's going to be transposed what i'll do actually is just cheat you can certainly write a function to do the transpose but i really don't feel like that so i'll just transfer use this numpy and do transpose for the board and just make sure that looks correct uh so this should look like you can see 0 1 0 is now like right here so if we look at zero one that zero one is on the first row so these are the columns now okay great all right so now that we have that let's first figure out do we only have two patterns for both the rows and columns okay so what i'll do is we'll call a counter and this will be for all the rows this will be a counter object and what we want to pass in 4 i guess row in board and we're going to make this tuple so that we can actually do the counting and what i'm actually going to do is make this into a list as well because we know there's only going to be two keys well there should be anyway and i'll show you why we have to make this into a list in a little bit so we all want to do the same thing now for the columns and this would be for board t everything else would be the same so let's print this out and look at what we're looking at just to make sure that we're not getting lost here all right so you can see we have the pattern 0 1 0 and 1 0 1 and there's two of them so that's what it indicates and i'll just put that in the comment here so we can keep track of what these counters look like okay so the first thing is if the length of count r or the length of count c is not equal to two if either of them are not equal to two then we can immediately know there's no way to make this into a chess board so we can return false so if length of count r not equal to two or length of count column not equal to two return negative one now there's an or i don't know if it's an edge case but we also need to worry about it's possible if we have an even number or odd number of rows and columns we can have something like this okay so that means these we have three of the same pattern and two of the same pattern so they're not equal to one other obviously one of them is kind of on its own so what we'll have to do also is check to see if this condition holds either they're the same here like we have the same number of patterns to both of these or we have one more on one of them if it's odd so just to check that we'll say if the absolute value and this is why i had to make this into a list here i'd say zero otherwise i have to find what the pattern is and put it in and it just would be too much work so zero which would be i'm sorry we're not looking at the pattern we're looking at the number that they appear and we'll say zero or one so this would be for the rows and if this is greater than what 2 that means this is no good right and same thing for the columns all right so now that we have that what do we need to do well at this point if we're able to get past all this that means we should potentially have a board that should be able to be formed into a chess board so now like i said before we have to compare with this pattern that we want the either one zero or whatever right or zero one but uh we don't quite know what that pattern is until we get the length here so what we'll do i'll call pattern one this will start with one and we're gonna multiply it let's see by n divided by two and i think we actually need to add one here as well so what i'll do is plus one and this will be a list and we only want to be the length of up to n now we also want the same thing for the opposite zero one as we'll call pattern two okay so let's just make sure these patterns look right all right so one zero one and we have length of four so that looks good okay so finally we want to figure out this is the main point right how many moves can we make or what's the minimum number of moves that we can make and to do that all we need to do is check the differences between these patterns here and get the minimum one so luckily there's only two patterns right now we know for rows and columns there's only two patterns at the most so what we'll do let's see we're first going to check i guess the first one here okay we'll call this x1 x2 y1 y2 and it's just going to be the number of see the number of columns that we need to flip and number of rows that we need flipped so all these start with zero first so for the first pattern let's see okay well x1 will equal uh sum we'll say 1 4 i in range of n we're going to check if count of r let's see zero and technically at this point i just realized something we don't need to check both patterns we only need to check one of the patterns because we already know that this is going to be a mirror image of the pattern right so we only check one of the patterns and we're just going to check to see does it if it doesn't not equal the pattern one of i and this one would be i right here then we're gonna output a one and we want to find the number of those that would be the sum okay so this would be we're checking the count of rows so we're checking the columns that we need to flip and do the same thing here for the y1 but this would be for the columns instead okay in the same way we wanted to do it for the second pattern of zero one and everything else should remain the same here so now we have two potential values for the columns and two potential values for the rows okay now what do we want to do um well first we got to make sure that these number of moves is an even number because if it's odd it actually doesn't make sense we can't you know flip three or five rows so what we'll do is okay i'll say let's see how do we do this x equals i guess 4 x and x 1 and x 2. let's make sure that the sum is even so if x is divided by 2 is even then we'll output that x to here and same thing for the y all right so now we have these candidates for x and y all we need to do then is return remember uh get them there could be two of them so we'll get the minimum of these two and we're going to divide it by two because that's going to be the number of moves plus the minimum of y divided by two okay so let's see if this works ah okay let's see what they do wrong list oh okay simple typo there okay so i really can't tell if this is working yet but let's go ahead and submit that oy okay min there's an empty sequence uh that shouldn't be possible let's see how did that happen so somehow it passed all this even though our input was not correct here so let me see what i okay nope one hmm i'm actually kind of confused here this shouldn't have worked i guess i think this is one actually yeah of course that should be one so that was my mistake for some reason i made that two it can't be greater than two the difference can only be one at the most right okay so hopefully i didn't confuse you there um now you can see this is pretty jam-packed code uh there's jam-packed code uh there's jam-packed code uh there's other methods for sure but they're all this complicated so this question i particularly hate because i wasted a lot of my time and i had to look up the answer sometimes i feel like all i do is look up answers and then try to understand them and relay them to everyone uh and that's kind of discouraging because you know i want it to be all my own knowledge coming out but you know sometimes these questions are really hard i can't do anything about it but hopefully that helped i don't think this is a good question because you're really it's really dependent on how much can you how much intuition how much like logic math can you pull out from this problem rather than like a programming question right so i don't know but hopefully this helped and at least you can understand like one solution for it alright thanks for watching my channel remember do not trust me i know nothing
|
Transform to Chessboard
|
jewels-and-stones
|
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other.
Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`.
A **chessboard board** is a board where no `0`'s and no `1`'s are 4-directionally adjacent.
**Example 1:**
**Input:** board = \[\[0,1,1,0\],\[0,1,1,0\],\[1,0,0,1\],\[1,0,0,1\]\]
**Output:** 2
**Explanation:** One potential sequence of moves is shown.
The first move swaps the first and second column.
The second move swaps the second and third row.
**Example 2:**
**Input:** board = \[\[0,1\],\[1,0\]\]
**Output:** 0
**Explanation:** Also note that the board with 0 in the top left corner, is also a valid chessboard.
**Example 3:**
**Input:** board = \[\[1,0\],\[1,0\]\]
**Output:** -1
**Explanation:** No matter what sequence of moves you make, you cannot end with a valid chessboard.
**Constraints:**
* `n == board.length`
* `n == board[i].length`
* `2 <= n <= 30`
* `board[i][j]` is either `0` or `1`.
|
For each stone, check if it is a jewel.
|
Hash Table,String
|
Easy
| null |
3 |
hey guys welcome back to another video and today we're going to be solving the lead code question longest substring without repeating characters all right so in this question we're going to be given a strength s and we want to find the length of the longest substring without any repeating characters so the question itself is pretty simple to understand and let's just look at an example so over here we're given the string over here which is b c a b c b so i'm pretty sure you could just look at it and uh understand that the longest character that we're gonna get without any repeating characters is going to be abc so you could either get that from over here so that abc or this abc right over there now let's just take another example and let's say we take a b c b oh sorry b so in that case we would have two b's there's a repetition of characters uh another example is let's say we take c a b c again there's another repetition of characters in that case as well so i'm pretty sure you understand what the basic idea is and uh how exactly can we solve this question so a pretty simple or brute force type of approach would be to have two for loops and what you would do is so you would consider each letter to be the starting letter right so in this case what we're doing the first time we would consider a to be our starting letter and we would build up whatever the largest string is possible without any repeating characters so in this case we would do a b c okay so then we would have an answer which is three and we're just going to store it somewhere now the next iteration we're going to consider b to be our starting point and from b we're going to start off we're going to try to find what is the largest substrate so that's going to be a big o of n squared solution and we can obviously do better than that so another solution which is a big o and time complexity similar solution is going to be using this lighting window technique so if you don't know what that is it's actually pretty uh intuitive and it's pretty easy to understand so let's just uh kind of try to understand it using this example over here so i will be going into it in more depth but for now let's just try to do it like this so in this case um let's say i'm iterating over my letters over here and i want to find the longest substring so let's say currently my longest substring is just letter a then i'm going to increase it by one more and now i would have the letter b as well so now my longest substring is a b and again i do not have any repeating characters so now let's say i increase it one more now i have a length of three so my largest substring has a length of three and that's good but now once i increase the length to it by one more with the length of four i have the character a so what this is telling me is that the character a is now getting repeated so now the question is how exactly can i change my area in such a way that i do not have any repeating character a so there's two ways to go about that one is to well ignore this a or the other is to include the is to ignore the first a and that's what we're going to end up doing because we want to look at all the further possibilities in the further on into our string so in this case we're going to get rid of this a and we're going to look at everything past that so b c and a so i'm pretty sure it's pretty easy to understand and let's just do it one last time so bc and a and then after that i would add another value which is b so when i add the value b what's going to end up happening is well b's end up getting repeated again so in this case now i'm going to make my string or my substring to just be the value c a and b and then again that happens with c again and each time we're going to keep doing that so it's going to have a time complexity of big o of n since we're only going to be going through the area one time and we're going to be finding the largest substring possible without any repeating characters in that time so using the same concept and uh just with a more detailed explanation let's see how that works so the basic idea over here is we're going to have two pointers okay so i'll just call them i and j okay so think of i as our starting pointer and j as the ending pointer per se okay and another thing that we're going to have is a dictionary okay so this dictionary over here is going to be used to store the letter so we're going to have our character and the index that we found it at so the purpose of this i'll try to explain it as we're going along and it should be really simple to understand okay so we start off with our i and j pointers at the zeroth index okay so basically our substring is going to be whatever is in between of i and j so as it is there's nothing in our substring okay so what we're going to do now is uh we're going to move j to the right by one so now in this case uh before we actually do that what's going to happen is we're going to check for the letter a so is the letter a inside of our dictionary well it's not so in that case we're going to add it to our dictionary so we're going to add the letter a and what is the index that we found it at to going to b so the index we found a x is at the zero with index so let's write down zero okay so now we have a b so that's our substring and as you can see there's no repeating characters so in this case what we do uh we go to j whatever character is at j and we add that to our dictionary since it's not already there so b and then it's at the index one okay i'll just go to this a little bit faster now so now we go to c and again is c inside of our dictionary well it's not so that means we've never encountered c so we're gonna have c and then index two and same thing for d and d is going to be an at an index of three so j was supposed to be here now we blew j again so finally we have e and e such an index four but now let's see what ends up happening so what ends up happening is we're going to move j over here and now j is at the letter a now the problem is we have the letter a two times in our substring as it is currently so like i showed you earlier what we're going to do is we want to move the i pointer right because we want to keep moving our j to the right to see all possibilities so in this case how exactly are we going to move our eye pointer so just to just by looking at it uh what we would do is uh we would look at where was the last time we found the letter a so the last time we found the letter a was at the zeroth index so now to move our eye pointer we're just going to move it one to the right of it okay now let's do the same thing but let's talk about how our dictionary comes into play so the dictionary is storing where we found the certain character at which index we found it so in this case it's telling us we found the character a at the index zero so what that basically tells us is we want to move our i pointer so since we came across a over here we want to move our i pointer to where we found the last a plus one so we found the last a at the zeroth index so we wanted to move it to zero plus one which is one so right now we're now going to move it to the first index so it's going to be right over here at the first index okay and one more thing that's going to happen is over here we're going to update the value of our the character a so the character sorry so the character a is currently at which index so zero one two three four five so it's currently at the fifth index and that's what we're going to store over here so just one last time we previously found the value a at the zeroth index but since we came across it again we're going to move our i pointer to the right of the last time we encountered the character a which in this case is going to be zero plus one so we're now going to move it to the first index and simultaneously we're going to change or update our a value because now the last time we found a is going to be at this index over here which again is at the zero one two three four five fifth index okay so just to make it easier i'm just gonna write the index numbers up top and one more thing i do want to actually add which i forgot to do so earlier is we're going to be storing our result over here so let's just call it res and what is red is going to be so res is going to be the length of our longest possible substrate so how exactly do we get this result so let's just go back one step and at this step what was uh what we had was i was over here and j was over here so at each time we would be updating our result now we would be updating our result we would be comparing it with the old value of results so let's just say we're starting off starting it off with the value of zero with whatever the new value is now how exactly do we get the new value so for getting the new value we would take the j index so this would be whatever j is at and obviously j is going to be further away from i or equal to i okay i want to see how far away it's from the beginning so now the beginning over here is going to be represented by the i index so j minus i in this case we would be doing four minus zero so we get a value of four so let's just see if that's actually correct so we have a lot of one two three and four but one thing you wanna consider is that we wanna consider the letters itself right so we wanna consider where the pointer is as well so what we're gonna do is we're gonna do j minus i plus one so each time we're gonna be taking the maximum between the previous value and the current value which we get by calculating this so in this case as it is it's going to have a value of four minus zero plus one which is nothing else but 5. so that is going to be our result as it is okay now let's keep going and see if our result gets any bigger so we saw what the next iteration is going to be the i comes over here and j moves over there perfect so now let me keep going down this oh so j is going to now be over here and since f is not in our dictionary we're going to update it so f and we're going to add its index which is 6. okay now in this case what is the result going to be so the result is going to be 6 minus 1 which is 5 plus 1 so we have a value of 6 by using this so the previous value was 5 and now we have a value of 6 so we're going to end up choosing the bigger value which is well 6. so now our result is going to be equal to six okay so now we move j and uh let's just go through this really fast so in this case b already exists in our dictionary so that means we want to move the i pointer now we're going to move our i pointer to whatever index we last saw it at which is at the first index in this case plus one so now i is going to be at the second index over here okay perfect and another thing that we want to make sure of is over here so we want to update our dictionary value over here so b is now going to be at the index of seven since we already since we're not considering this anymore sorry this is supposed to be i okay so we have i over here and again we're gonna find out what the result is so seven minus two that's five plus one six so it's going to stay the same okay so now we move j to the right again so now it's going to be at d and d already exists so the same thing's gonna happen so it was last seen at the index three so we're gonna move i to the index four over here and j is going to stay as is and this value is now going to get updated to a value of eight okay perfect so now in this case let's find out what the length is so the length is going to be eight minus four plus one which is nothing else but four plus one five and five is less than six so we don't do anything okay so now uh let's just go through it a little bit more quicker so we move j uh g is not in our dictionary so let's add it with the index which is in this case nine uh then we go to c so now in this case c is in our dictionary so okay so over here we actually have a pretty important thing that we want to notice now what you so if you go to c in our dictionary it tells us that c was last seen at the second index and that's correct but what you also want to notice is as it is inside of the substring and again the substring is defined between i and j which is right over here there is no c value so over here when we're moving our i pointer so i is going to be the maximum between whatever value is it's currently at so the current i value and whatever value we get from our dictionary plus one okay so let me just kind of explain that one last time so basically in this case our i value is four but we know c already exists so we go to c and it's telling us to move our i index to the third value over here now there's a huge problem if we move backwards so if we move i backwards well one simple problem that would happen is d would now end up getting repeated so we don't want to move our i value backwards so we're going to choose the maximum between 4 and in this case it's going to be 2 plus 1 which is 3. so we should end up choosing the maximum which in this case is going to be 4 so this is going to end up solving this is going to solve the problem when we have a situation like this where we have to we might have to move backwards so in that case we choose the maximum i value so i stays after this so over here again find the result which is 10 minus 4 6 plus 1. so our result is now seven right so uh seven is greater than six so we now update it okay so let's just do this for last two more iterations so j moves over here so now in this case it's for the b again same thing b was last seen at an index of seven so in this case what's going to end up happening is i moves over here so it's gonna be seven plus one and i is going to move to the index eight and simultaneously we're gonna update the value of this to be eleven okay perfect so now we find the uh length and obviously the length is going to be less than seven and one last time so we move j over here so b already does exist at the 11th uh index so what's actually going to end up happening is since it's at 11 i is now going to move to the 12th index and the b is now going to get updated to a value of 12 and in this case well the result is going to end up being 12 minus 12 plus 1 which is a length of 1 and actually we don't really need to do anything so the result in this case is now going to end up being seven and that's what we end up outputting and that is what the correct answer is so that over here is the longest substrate okay so now let's see how that looks like in code which should be pretty simple okay all right so for the code of what we're going to do is we first need to define a few things so the first thing we want to define is our dictionary which is going to hold uh the letter and the index that it was last seen at so that's for our dictionary let's call it d and the other thing we're going to have is going to be our result which we're going to have an initial value of zero okay so we had two pointers which were i and j and what we're going to do is we're first going to define i over here so i is going to be equal to zero and for the j what we're going to do is we're go we're just going to use a for loop for j itself so to do that we're just going to do sorry uh for j in range and what is the range going to be so we're going to start off at zero and we're going to go all the way up to the very ending so that's going to be the length of s okay so this is the j value and it makes sense to use the formula because each time we're moving j over to the right by one okay so keeping that in mind um what is the first step that we're doing so the first step is we want to check if whatever character we're currently on is inside of our dictionary so to do that we're going to go to the string s we're going to go to the index j and check if it is inside of the dictionary d now if it is inside of a dictionary we need to move i okay so we're going to do something over here and we're going to end up moving i but before that let's look at the other condition so if it's not in that the first thing we want to do is we want to calculate our result now to calculate our result over here uh the basic thing that we saw is we did j minus i plus one okay that's all we're doing for calculating our results and uh we want to update this result right so result is going to be the maximum between this new value that we have over here and the previous value that it had so results come out that so we're going to take the maximum between those two okay so that's that and the other thing that we want to be doing is we want to add uh the current character to our dictionary and update its index value so in this case it's going we're going to go to our dictionary uh we want to change the character so the character is going to be we're going to go to our string we're going to go to the jth index and it's now going to have a value of j because that's the index we last saw that okay so now we want to see what exactly do we do over here so if the value is inside of our dictionary we want to move the i value so i is going to be equal so the thing that we were doing is we go to our dictionary so in this case uh this is exactly what we're doing we go to this character inside of our dictionary d and inside of that we're going to get a value of the last index where we saw that and to that value we're going to add one because we're going to go one to the right of it now again there was this one small condition where sometimes we were moving backwards so to compensate for that condition we're going to take the maximum of this and sorry one second so we're going to take the maximum between this value over here and whatever the previous i value is so that is all we're doing over here and yeah that should be it for our solution and at the very ending over here we're going to end up returning our sorry we're going to end up returning our results to return rest submit it and our code should get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Longest Substring Without Repeating Characters
|
longest-substring-without-repeating-characters
|
Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces.
| null |
Hash Table,String,Sliding Window
|
Medium
|
159,340,1034,1813,2209
|
930 |
Everyone today is exactly following similar code structure elements are in the form of binary numbers like zero and one and along with this what happened to us and he today the length is anything but numbers tell me how many times how frequently or How many times such a morning has been generated in which the song of all the elements is equal to the goal. This is a very easy problem. Let's start, first of all I got the feeling that he has asked if you are gold, then let me see. I came to know that this is an engagement. Which is mentioned here in the output, one morning this can be mine, okay, we have also made this, one morning this can be mine, so we have also made this and one morning, this can also be mine, any other than this There is no possibility that all the elements are equal, so what is the problem here? Let's start understanding it. First of all, let's do it with a normal sliding window because you know how a sliding window looks. So what will we do, we will start from here i = 0. Now instead of i, let me call it i = 0. Now instead of i, let me call it i = 0. Now instead of i, let me call it head and let the oil variable be i. What does head do? Head moves ahead of me. It is clear from the name that head means back and forth. Head means you can go right and left, so I said that initially my head and oil will remain on the position, so head and oil will be on this point, now if I do a stand on one, then don't score this goal right now. Now I will also take an even variable in it and add the name soft fat again and again. Well, till now I have understood the simple story. We had the concept of taking care of that size in the morning, right now the same thing is going on. But let's see what is the problem, when my head is updated, when it comes to everything, then what happens again is even, plus is equal, you are the first to come in terms of, if my head was at zero, then my one was added, then my plus head is updated. When I moved the head forward, it went to the head one, then it added zero, so 1 + 0 is 1, still I am safe, the added zero, so 1 + 0 is 1, still I am safe, the added zero, so 1 + 0 is 1, still I am safe, the head will flood further, what happened again to my OnePlus 0 + 130, till now you must have been my OnePlus 0 + 130, till now you must have been my OnePlus 0 + 130, till now you must have been here now. The interesting fact is that as soon as my head moves forward, it will not have any problem here. Look, you are fine with me and my goal was also you, meaning one morning we have met you. Understand, one morning we have met you but we look at our window. Why can't you reset the window because you know here also that one zero one is a valid answer but if one zero also we add all these then the answer is also tu means one. This is all if we reset these people, reset the window, what does it mean that one morning this happened, I said, oh brother, I got everything, you are sorry, this happened to me, I never got this, if you got me, then reset the window, if the window It will be reset meaning it starts from zero one, so when you will go wrong then why would you go wrong because one zero is also an answer, okay after adding zero the element will lose its value but like this attempt to add one. I will do it okay, meaning whatever my number is, if it is updated then it has been done, meaning I have got two answers, but like now my head has come on this one, on the last one, zero one, three four plus one plus zero plus one, now my song is three. Why will it happen because the value of the goal was, that is, keep the length of my window mental as much as add all the numbers in it and open it by saying see, now if it is generating something bigger than the goal then is there any concept of negative element in this question? This means that our sub will always increase. If we now increase the size of our window, then what will it mean? Keep coming out to reset Pindi Bino. Now why do they come out from the back because brother, we are talking about the morning. If the element is from the middle. First of all, it will have a problem in accessing the middle element. After this, if we remove the elements from the back, then one by one, it is fine, so we start removing the elements from the back because where have we kept the oil painter at the back till now? I had kept it at the value which was the starting of the window, it means that my oil is lying here, now as soon as I got to three, reduce one, the oil was pointing here with the help of oil, some mines of oil with its help. What to do, keep the sand coming out from behind and whatever oil is there, it will keep getting updated. Now those who have watched my full video or even one in the previous players, they must have understood that this is what is happening inside the wire look. There is this condition, I have told it after checking, now see, whatever he did not know, he will also understand this, see, keep doing even, always keep doing even, this means that I had told in the first step that what is lacking in me first of all. Putting the loop with the help of head is equal to zero, head <= is scanning, perform the <= is scanning, perform the <= is scanning, perform the operation, some or the other operation must be being performed, which is my sub, we are adding again and again. Okay, we are all adding. If you sum the feed which is generating some value, then this is done in the operation. Now the problem is being posed. Will sum it, give it a greater goal, then the problem will be said, ok rich, what has to be done is this thing inside it. Will come and my answer will be getting updated here, this was my simple template, nothing else has to be done but where will the problem come, I have taken out the element from the oil, now what can I tell you, zero one and where should the oil go? Hey brother, if the oil is plus, then the oil was at zero, where will the oil go, if it is not there, then update the difference of A which is outside A and now you will check the above, if it has not gone brother, then the operation will be performed again meaning. Now this window will move forward from here, maybe some more elements are added from here, then it has to come out of this and return the answer, but why can't we do this? Has anyone understood yet why we can't do this, so let's go. That's the thing I tell you, hey, if I have come till this point, it is okay, this is the size of my window, then my saint has given it, but how will I know that my window is not going to be screwed, so first we do this. We knew that if all mine came to me, then we would set the bino from the gate and start from here from zero one saying, brother, you all have come, if you add some value then everything will be bigger, then reduce one, reduce the fractions. Reset it but here we can't even do this, my one will be set otherwise if we don't shrink the window then till here I got my one in the morning but before this one in the morning it was also this, it means when If we came from here till here, then it means that it should be round and the window has been my flood, then what do you do in my answer, keep doing plus, what was asked in the answer, it was said in the answer that it is the snake charmer's length, meaning give it in the morning which all There should be a complex of all the elements in the morning, that means if they are equal to the complex, which is this story, then the answer is plus, it's okay, now if the window is flooded further, it's okay, but as soon as I come here, it's okay as soon as I come here now. I can't add it. If I added it, I will add it to everyone according to my algorithm, but I will have to reset everyone because before that I must have put it viral. After performing the operation, has the sun become bigger than the circle? Come, let me make it and show you what would be happening in my sub. One plus zero plus one plus. Look, the value of the whole is becoming my plus but now its value has become three whereas I wanted goal tu. Take one less oil, my oil is still here and where has my hit gone, my head is wet, what will I do now, I know that now I have to move forward from here because now it has made a seat and has made a right angle seat. And my oil has been updated, the person who will be calling will appear here. And the oil plus will be plus, it will be ok, the answer will be ok, what will be happening in the operation, the software named Sun Plus will always be happening, as soon as it seats, it will enter inside the bale and correct it, by resetting my sum, it will make the correct silk which That no one will be scoring the goal and at this time you say equal, okay answer, now my head has gone out, that means now my head has gone out, now I have been thrown out of all the people but most of all from the loops. Came out, now I have to give the final return answer, but still I must be seeing that one zero one, we did not even consider it, the problem is here, look, the goal has been achieved, we do not have the condition to horn the window. How will we know, look, when the window was free, but how will we know to remove it, but we can still get our answer in the window, so the biggest problem here is that the condition to shrink the window is not found. Because of this, we are not solving this problem even after solving it, so I will change the slide a little bit, the code is going to remain the same but I will conceptualize it a little bit, which perhaps we have forgotten and okay, some people There can also be a doubt in my mother that if you had got the window from here to here then it is okay and if you had written will some greater den goal then what will you do only when she goes -=10 and my oil Plus plus, some people -=10 and my oil Plus plus, some people -=10 and my oil Plus plus, some people may create this doubt here that when you added this, you reset the window, from here it means that a new morning can be found from here, but why 101 will not be found because only we have written the condition of rich goal. That's the reason why I did n't remove so many zeros because how would I know from 0101, it means a new morning can start from 01 but before that 101 must have also been considered. You are right in that, but if you are in the same situation then it is not caste. Laddu can be held in one hand or in both hands. If you write equal in a grater, then friend, you have corrected the oil, that means, the zero you were supposed to remove from the oil was six because you are saying equal, but what is the problem? When you are reducing the head, it will become 1010. As soon as one comes to zero, one becomes 1 + 0 + 1. one comes to zero, one becomes 1 + 0 + 1. Brother, what will we do? We will take out this one and start from 01. Understand the window, meaning 101 should be your consideration. Went immediately he started the window from here whereas one zero was also the answer it should have meant 100 but you broke it from here and if you don't write equal then there will be problem in oil it means that sometimes you Problems will arise. Now understand what I said carefully for yourself and if you don't understand then go back and watch the video again and you will understand. Now let's talk about that concept which was difficult to understand with so much fear. And which I am going to do with many problems further, this is very important and useful in the concept, now you can do this problem with prefix also but it is your responsibility to do it was less of me, tell me how you can do it with sliding window. No and which one as I said, I am going to ask further questions, how I came to know that this is the concept to be applied. Seeing the problem of such sliding window, first of all, I did not find any particular condition of setting and span of the window. Because this concept fits me, second one is given and someone has brought that. If the value of any variable is given, then I immediately know that sliding P has to be applied, but some people have actually Must have read etc., but some people have actually Must have read etc., but some people have actually Must have read etc., they will say that if there is such a method then it is also there for search and there is some variable, yes I agree but there are some keywords also along with this, one is about morning and one is about numbers. That is, as soon as I see the length, I prefer it. Okay, so here I don't have to think about anything else. Now this is the concept that we have forgotten. What does basic maths say that if I have to find exactly a The thing to be found is its value - Atmos and Most and - value - Atmos and Most and - value - Atmos and Most and - Atmos N - 1. What is this thing, we are going to do the same, we know that we will do things according to ourselves, so what do you mean by Atmos, is there anything which is zero. There is power, there is power, you are also power, oh friend, the answer is visible in front of you, if anything is zero, there is one, you are also there, what does it mean, the one which is zero is X time, plus the one which is white, There is only one time, hey brother, by dividing these two into two, we will get them. How will those who watch my video know that the saree will be good, they will not know. Well, please go and see for your benefit. I have made a very long place on YouTube till now, maybe. No one would have created such a big place and look at it, what is head and oil? It is clear from the name that head means again and oil means ask, it means you could have taken right or left also, but I have hit it in the full video. So, I am taking the head and the oil here, I am changing the head from ha to dino and the oil from t, both are at zero position, this is my position, zero, this one, this you, this three, these four, I am moving forward with the help of this relief. The responsibility of scanning the entire Bino is of the entire head and I extend the oil further. If there is a problem then if there is no problem then keep moving ahead, mother will start moving forward, take my head here, come here and here. But the problem has arisen, that is, after doing so many windows, what will I do about the problem? Update the oil and oil If all the things get canceled among themselves, then I will also write this in which I have told two-three methods will also write this in which I have told two-three methods will also write this in which I have told two-three methods and a head. While adding the size of the window, those who come out in the morning also add the size of the window. 27 Here also I will discuss, so you can also watch this video, but if people watch that video, then you will create a problem and extra people. Let's see how the size of this window is determined. Head minus one is a simple thing. Those values are at the position from both the points. one is a simple thing. Those values are at the position from both the points. Now what will be interesting after this, nothing will be interesting. My head will simply flood further. If one plus zero is given. You are equal, you are three, friend, you are there, so what does it mean, this element is also equal, so the lesson is also equal, this is the combination of two elements, you are equal, only then give all the elements, you are equal, the same thing is happening here too, it is very difficult to understand the whole thing. It's easy but you guys have to show me the electricity, no problem, I will do it again and show you, the video will be a little long, but I am telling you in so much detail, that means there was no problem in everything and the way to find out the size is my headmaster's butt. You must be interested now, so yes brother, whatever concept I have told you will try it only then you will understand why this is happening, that is why I wrote plus it is equal, that which is taking out the size again and again, keep adding it because add most. You are right when you have the size of 3 minutes, like the first 3 minutes were done and this current element is being added, then if this current element participates completely in this time, then this element will be a new one, these two will be new, these three. There will be a new morning and these four will be Ignis, only then look at the size of the window, there were already three elements, one element from itself, the second from this, the third from this, and the fourth from now, if there are two elements then how can the total be made three. But it is OnePlus Zero Plus. One again will become six and those three were already there, one has just come, see this whole thing, there was already 10 and one has just come, so this one is the only one, both of them are here together and all three of them are here together. It has become three, maybe in such a way that my head will get flooded, the problem here is that it has become even, 3. Now if the even has become three, what does it mean that you will come out of the forest from the oil gas from behind and everything will be reset for me and start from here. It will be done, I understood that mine was taken out and as if mine was taken out, it became oil plus, then the oil got updated from here, went to one, meaning my window will start from here from 01 and zero one becomes zero one, guys. What is my size? If I size it will become 14, which you can see. Zero one zero one, it has not become 14. Answer: A has not become total 14, all like this. Now, Answer: A has not become total 14, all like this. Now, look at the interesting fact, how does this reduce, how does this approach reduce, see, okay, you will come out. You will know that one can be even, you can be even, how can I get zero sum, one even from Atmos One? When you mine both of them, zero one will cancel each other out and you will be left with 2. How to see, this cancel will not be present, hence this Poor guy has gone back, this poor guy has gone back again, take this brother, if you understand it well then one like is enough, friend, and tell me in the comment, how did I like today's plantation, today I have tried to put it completely, so friend, see what you got. I have just explained, everything is written the same, everything is the same, just do not give runtime error here, so look at the oil, what is the oil, there is always relief behind, so the head may die tomorrow, cannot go ahead of the head, it will not go but safe. To stay, I wrote everything else brother Atmos Goal Mines One, after this I used the same sliding Pintu's same template, took out the operation which had to be performed, the condition is written, which condition is failing if it fails. If it is happening, then throw it out of the oil game. Keep updating the oil. Who has told you to add the size again and again? It is Atmos, so we have added the size again and again Atmos, so we have added the size again and returned the answer. Now my So that you can have complete faith in the button, I had shown you that 14 months 10 does not come, see this brother, for Atmosfan, which we had shown 14 years ago, for Atmos Stone, let us see even after submitting it on 10th April, then let's go. If you want the answer, before that you have to comment, then it will be shown here a little faster. Now to solve similar problems, you have to try this account and one is different, if you want, wait a little here and I hope you will like it. You must have liked this solution of mine, see you again in another such interesting video, thank you.
|
Binary Subarrays With Sum
|
all-possible-full-binary-trees
|
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[1,0,1,0,1\], goal = 2
**Output:** 4
**Explanation:** The 4 subarrays are bolded and underlined below:
\[**1,0,1**,0,1\]
\[**1,0,1,0**,1\]
\[1,**0,1,0,1**\]
\[1,0,**1,0,1**\]
**Example 2:**
**Input:** nums = \[0,0,0,0,0\], goal = 0
**Output:** 15
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `nums[i]` is either `0` or `1`.
* `0 <= goal <= nums.length`
| null |
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
|
Medium
| null |
168 |
hey everyone today we are going to serve the readable question Excel sheet from title so you are given integer Chrome number and return its corresponding column title as it appears in your Excel sheet for example a is 1 B is 2 c 3 and the Z is 26 after Z so Quantum title is a that is a 27 and the a b and the 28 okay so let me explain with this example so column number is 701 so I already wrote down the some algorithm here so let's look at one by one so first step we subtract -1 from so first step we subtract -1 from so first step we subtract -1 from current Chrome number so there are 26 um alphabet in the world right so from A to Z so that's why it looks like we can use like a base 26 system but uh base 26 system usually starts from 0 to negative 25 so if we map the alphabet and the base 26 system so 0 should be a and the one should be B and so 25 should be C so problem is this problem this program starts from like a is one b equal to and C is three so there is a one difference so that's why we need to subtract -1 from our current problem number -1 from our current problem number -1 from our current problem number so that we can map the alphabet and the base 2016 system in the next so we use a current column number divide 26 the number of alphabets and I get the model plus and ASCII number of a so the reason why we are asking number of a is that so look at this example so this is the example so I'm not sure exact ASCII number of a but if 100 is a 101 should be B and the 102 is C and the 100 103 e should be D right so if we add asking number of a here to a model so we can get like a correct and asking number of some character so that's why we need to add ASCII number of a here and then plus so current result um string characters so first of all this is an empty string and then create a new result so that is the second part so next so we divide current column number divided like at 26 so number of our width so that's because uh we use a like a base 26 system so look at this so in daily life so if we add a new digit so like a first over one is a 10 to the power of zero and at 10 so we need we find the next digit so in the case 10 to the power of one and the next 100 10 to the power of 2 and there was one thousand tenth is above Z right so um so base 26 system is the same like a possible one and the 26 to the power of 1 is 26 to the power of 2 is 6 676 and the 10 26 power of 3 is this number so that's why um if we want to move and like this and write this so we have to divide current Chrome number uh with like 26 right so that's why uh to move next visit so we need to um this calculation so that is a solid part okay so let me check uh 701 quickly so first of all minus one so that should be 700. and then so divider 26 and I get the model so that should be 24. plus ASCII number of a so um so if one a is a 100 so that should be 124 so that should be y right and then plus current result so first of all initialized empty string for a regular result variable so that's why results should be y only y and then next I'll divide a column number with 26 number of alphabet so that should be 26 I guess oops so this is a 26 and then next so we repeated this process until uh Chrome number is zero um 0 or less than zero and the next 26 is a and a minus one should be 25. so 25 Divided 26 and get the module so that should be 25 right so 25 should be so Y is a 24 so 25 should be 0. so that's why uh so combat um this number to character so get that D plus Y is here so because the current result is y so Z Plus Y is like a z y and then so 25 divide 26 should be zero right so now we reach zero so that's why in this case we should be done c y the outside this is a uh I copy this number from example three so example three should be Dy right so it looks good yeah so that is a basic idea test of discussion so with that being said let's get into the code okay so let's write the code first of all and create a result variable with empty string and then after that um start looping wired column number is greater than zero so we continue to be and uh first of all as explain audio Forum number minus equal one and then next create a new result so equal so we need to convert to character so c h r and uh column number divide 26 and then plus number of ASCII number of a so ORD and a plus current result variable after that so column number divide 26 to move next visit after that just click down our result variable yeah so let me submit it yeah looks good in the time complexity of this solution should be order of log base 26 of n so where N is a given column number so that's because we continuously dividing the number by 26 until the number becomes zero so that's why and the space complexity is actually the same order of log base 26 of n so because the space used to store the result string is like a proportional to the number of digits in the program number when it is converted to like a base 26 system so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit select button or leave a comment I'll see you in the next question
|
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
|
216 |
A Firewall Welcome To Loan Co Repeat FlashLight Co Problem Which Is The Date 12th September Changes Combinations We Third Point System Of Medicine Backtracking Solution And Will Discuss In Detail About Backtracking Processor Slow Cancer Problem Pure Problem Statement Find All Facebook Nominations Of K Numbers Adaptive Number N 2018 19 Number 129 Can be used in this combination between UNIX Only Numbers Pure Question is that strange Input K and Volume Increase the target Somebody wants to check and K This total number of elements of candidates in the way are best friends Stop These elements which where Together Forms Number And Id 354 And The Pure Condition Is That You Can Not Have Duplicate Satellite For The Combination Can Benefit Some Or 125 14520 Unique Set Of Elements So Let's Check The Second Example In This Which Person Near 98290 Numbers Between One To 9 Gold Padak Radhe-Radhe Gyan Question Huge One To 9 Gold Padak Radhe-Radhe Gyan Question Huge One To 9 Gold Padak Radhe-Radhe Gyan Question Huge Numbers Between 1292 Check the Sum Forms and This is the Full Form of Select its number from the list of elements and list number set which contains them 0129 Bihar Swift Select the first number one and will have two Select And Navya Tuesday Number-23 6752 Noida Toll Navya Tuesday Number-23 6752 Noida Toll Navya Tuesday Number-23 6752 Noida Toll Free Numbers 0.99 110 Second And Third Number Free Numbers 0.99 110 Second And Third Number Free Numbers 0.99 110 Second And Third Number Can Benefit 154th 2851 Effective 1234 And Similarly For Selected For Example That They Can Select 5696 Tree Does Not Give Back 10 In The Development For Subscription Fee Can Be Having interest in selecting number ok betu supping now to ajmer who is the number kandy 6262 and 112 rates in the update from the number 90 2910 runway the sense i see need to check with dinesh number of baroda third decide share before riching sex life term live Webcast Of Consent To Awake For Third Number That Is Wealth Of Nations Will Go To 4 9 To 5 Sexual 66 Combination Boys Patiyaan And Way Chittiyaan 800 Pilot Combination To Subscribe Term Deposit Basically Middling The White 909 The Number To Check It Number Checking Different Way Vasundhara Its Effects Of This Constant The Third Number Check Chahti In This Not A Good 290 Chewy And One Is Equal To 9 That Is The White Combination Channels Pe Obscene Chhat In This Seems No I Don't Me To Go For Word Naidu Under -22 Next Sid Fit Third Second Jobs Under -22 Next Sid Fit Third Second Jobs Under -22 Next Sid Fit Third Second Jobs for Pyun 235 Gol 248 subscribe and subscirbe ascending in value right side with 400gr number two 9 govind six digit 02 ki pratik aginpath combination of two ki pintu kahan se tile moot the second number three lines 7.30 digest Combination Right 0 To Move Forward To See What Are lines 7.30 digest Combination Right 0 To Move Forward To See What Are lines 7.30 digest Combination Right 0 To Move Forward To See What Are You Doing A Gyaan Clipping One Constant Fear And Giving Falls Sworn In A Moving To Bank Ki Pintu Kaun Idhayam Checking All Different Combinations Of Third Effect Soft Typing Deposit Account In The Country Its Terms With Logic Right Essay on the time polling this temple in the same logic share and securely the same thing and regret in the same function lighter swapan dosh logic and welcome to the number per ball same function suryaveer what you doing a10 exhausted with this particular second number be back in The Big Guide to the First Number Danveer Go to the Next of the First Number 8 210 Will Go to Two in 3D Mirch One All the Combination of Shipping Second Number Constant and Moving in the Third and Definition of Cost and Death Will Back to Give the second without many sacrifices for Android in Bluetooth setting for its significances of trees were doing nothing but the deficit were doing research on a stranger tracking stuck flashlights off exhausting achievements backpacking after 10 inches and patience relation belonging something like this share It's Back's Third and Welcome to the Satanic Verses Go through this 200 gram green signal system adding that even numbers using introduced and again ring with a back side with the same method best time of making maybe start value is plus for what is the current i plus and exploited which is way in the candidate Will be the institute of measurement from the sudeshwar landing gear i second digit s next date sheet of my width plus one ok no sense of choose right own intellect abstracted from invalid from final target is samsung tracking imnb0 and keeping tabs is so welcome back to This Agni Putrudu The Same For Low And Once Dhul Thing After R Intention For Example At Se Video The Second Digit 2 And The Hague And The Second Suvansh Is Attract Tourists To Be Removed From My Set And Us List And Edit Govinda Next Antibiotic 300mb Exam Remove Versus From Violence And Go Into The Next Five Swimming Show The Combination Fruits Of Duplicate Don't Know You Will Regret Not Go In Infinity Loop subscirbe Condition To Stop This That They Need To Stop List Maintain Deficiency Of Removing All Elements Of Delhi Main In Vellore Items Attracting The Element from and value added and a gifted the correct form number one to end 6006 the time the valuable weakness also positive 2013 female v9 edge - 20 balls back positive 2013 female v9 edge - 20 balls back positive 2013 female v9 edge - 20 balls back tracking and observe and lemon juice 12312 element for staff and business subscribe The Amazing Notary Element But Before attaining agency Standard and Poor's 500 index's to do the to-do list size of index's to do the to-do list size of index's to do the to-do list size of or turn on 10000 that half mukteshwar list size near urdu vigorous to belt combination friends welcome to end combination in results tried to make the wedding this combination festival list Don't Atlist Subscribe And New Poets From Meer Who Did n't Get Removed In The Results And This And Black Lips Back In Fashion Just Subscribe For Free Options Check Weather Options Character 9.5 Way Which Lets You Options Character 9.5 Way Which Lets You Options Character 9.5 Way Which Lets You To Right Direction Subscribe 158 5.001 Udhar To Right Direction Subscribe 158 5.001 Udhar To Right Direction Subscribe 158 5.001 Udhar Se Main Jo Backtracking Option Rate Share Meeting 124 The Self YouTube Value For * I Am Just Once Say Meeting 124 The Self YouTube Value For * I Am Just Once Say Meeting 124 The Self YouTube Value For * I Am Just Once Say Zombie Nation With His Choice A Bit In Vairagya Two Pilot Combination Danaidu Uther Recording On The Member Will Increase In First Tight Second Judge To Make The Record Starfighter Sudarshan Also Inclusion K is condition like and 91 the target water pollution noise of thakurs friend its speed to target condition which is rich and written with a target conditioner trees and vinod dhawan that point you will never find the target condition 100 share in this case at will depend On 200 There Will Never Get Condition Subscribe Button The School And Arthritis The One up the Video then subscribe to the Current Selection From Sharing Tracking Software Removing Election 2018 In The New Mother Language Day Subscribe The City Of The Giver 9 Loot Does Not Worry Soldiers Ne But They Haven't But They Can Select From Right And Total Number Of Units Subscribe To TV9's Subscribe Numbers From November 1999 Subscribe And The Subscribe That's Your Using Some Times But Not In The Same Truth And Ends With Now Let's Go Brad Pitt Tabs Condition and Cheating - 07 Brad Pitt Tabs Condition and Cheating - 07 Brad Pitt Tabs Condition and Cheating - 07 Festivals and Celebrations of 2012 Boys Who Have Written Exam Breaking the Beginning Functions in Uttarakhand and Colleges Back the List Samay President Elect Se Want to Start with Dhawan Share the Start with Passing Interest Pandey's Decision Number Tagged Anu Festival's Help Samay Tak One Security 6310 Back To Back Records And Available Result For All Belt Combination Are Let's Submit 10 Ki And Updated On Ki Thank You For Watching Please Subscribe And Win Question Destroyed And Comment Section Thank You To
|
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
|
110 |
hey everybody this is larry this is day 22 of delete code daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about trace farm balance binary tree so i do solve and record these lives so if it's a little bit slow feel free to fast forward i go for my thought process as i solve the problem and then go for the solution well at the end so uh let me know what you think okay so determine this height balance with this problem with height bounce trees the finest every node a boundary which every 11 of every node differ by heights by no more than one okay i mean this seems straight for it maybe it's just thinking about invariant and it's about the recursion and they totally tell you that every subtree has to hold uh this invariant in which the height is great um no more than one so it's just becomes an implementation detail um and you really for these problems you want to do in one recursive step or one recursive function anyway you could do multiple passes that's okay but if you put a another recursive function in inside your first recursive function then it may become n squared so you do want to do this in linear time even though n is only 5 000 um because it probably can but basically here we just have uh yeah i mean i think we just want to return two things um that would be you know what i ask myself when i solve these problems is that for each node what do i need to know from this child right here i need two things one is the height of that child or subtree and two is whether this condition has held on right so with those two things i think we can do it i'm going to call it that first search uh though it's not really a different search it's just recursion so maybe that's just quite uh yeah that's good it's balanced um maybe we even use this definition but we also want to store the height so let's get its balance helper say node if node is none then by definition we can just say by convention rather that is true and that the height is zero so we want this function to be clear of what we want to return a tuple of n i'm doing this as a shorthand but um if you want to write clean code i would recommend looking up in python anyway uh a named tuple uh which allows you to use it like an object uh in different languages you can return objects in different ways uh so definitely do that as a wrapper but here is just for me being lazy and keeping it short uh maybe in the future i'll change that up but for now that's what i'm going to do which is don't ruin of whether uh the sub tree is balanced and the height of the subtree right okay so then now we have you know we do things on the left and we do things to the right so i just say left is balanced and love height is equal to is balanced helper node.left helper node.left helper node.left right is balanced right height is equal to is balanced helper uh node.right and then now we just uh node.right and then now we just uh node.right and then now we just have to put all these things together and as and it looks which is that every node different height by norm oh wait oh yeah the sub trees of these no uh heights differ by no more than one so then basically we just check um if so then well let's put another way right uh node is balanced is gcode2 so in this case left has to be balanced obviously and the right has to be balanced and uh this condition where the left height the difference between the left height and the right height is less than one and then from that we can just return this new tuple which is what we want the answer to be or this object let's call it an object i know that this is top of an implementation but we just want to return an object and then the new height of the subtree is just one plus the max of the left height and the right height right so then now we can call after is balanced helper of the from the root uh we only care with its balance so balance and then the second thing is just the height which we don't need for the problem uh at least at the very top so yeah so then i think this should give us close to the answer if not the answer so i'm just gonna do some testing by copy and pasting and emptiness okay so this looks good um so one thing that i would uh make sure and pay attention on is that because the answers are true for us and we don't have three answers it's very easy to accidentally get it right even when the code isn't right so i would advocate um you know just doing more test cases going through edge cases and stuff like that in the interest of time i'm just gonna submit because you know this is just a stream so uh let's see if i get it okay yeah so it looks good uh feels good too and what is the complexity of this right well because we look at each node once and only once and we do a constant number of operations for each node it's going to be linear time right constant time per node and node linear time in terms of space it's going to be you're going to incur some space cost per in a rate of per recursive step and that's going to be you know the your maximum memory usage is going to be the height of the tree which is all of h which is in the worst case of course of n so that's basically what i have for this problem i think the tricky part is thinking about invariants and i think one thing i would like to point out for problems like this is that a common problem that i see or a common question that i see people ask on my discord channel for example is that um they try to separate they have these ideas in the head of the uh you know that you know you have two questions you have to ask for each note right one is whether it is balance and the other is the height and they kind of separate them into two functions and therefore like maybe here instead of combining together you call another function that goes okay get the height of this node and then because of that it becomes n squared um so i think this is just something to think about in terms of like combining the um combining the conditions and the invariants and then in a way to group them together so that's all i have and i you know i would also say that i have a lot of practice with this um so i know that maybe i don't want to make it sound like i'm bragging but like maybe i made this look easier than it is it's okay to struggle i definitely struggle with this problem which is not this particular problem but these kind of problems for a while until i realized that the key to solving this problem is to do them at the same time but i would also say if there's actually another way to do this um which you are able to do it the most in the more intuitive way which is that okay so now instead of returning one uh both these things in one function you can actually do this way where okay left height is equal to get height of the node.left or something get height of the node.left or something get height of the node.left or something but what you have to do is just make sure that you memorize that function because as long as you memorize that function then you don't do that repeated loop that makes an n square where you have a linked list it becomes n squared because then now you go okay the first you know the top of the tree go you know that operation takes n times and then n minus one times n minus two times and then becomes n squared but if you cache it um or store the procedure then it becomes of n uh it's not a preferred solution but if you're doing like a time test or if you just have no idea how to do it otherwise um that's how i would get at least getting an ends out even if it's not the cleanest um yeah that's all i have for this problem linear time linear space or height of h uh space for height um let me know what you think let me know what you struggle with let me know your uh yeah let me know if you need anything for this problem and i will see y'all tomorrow 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
|
1,422 |
hello hi guys good morning welcome backi I hope that you guys are doing good maximum score after splitting a string it has been asked by Google not pretty much but yeah it has been by Google because the see it has been asked by Google only and only because of the variations of basically the follow-ups variations of basically the follow-ups variations of basically the follow-ups it can have basically Improvement it can have let's see uh maximum score after splitting a string it says that we are having a string s of zeros and ones return the maximum score of after splitting the string into two nonempty substrings that is again mark this word it is saying two nonempty substrings both the substrings should be non- empty both the substrings should be non- empty both the substrings should be non- empty that is the left and the right substrings if I have a string of let's say incorrect is I have to divide that into two nonempty substring that's a big thing now the score after spitting the substring is a number of zeros in the left so I have to consider the zeros in the left and the ones in the right that is the score of this particular like division which we will have and I have to return the maximum score which I can have which is the maximum some I can have some of as in the zeros from the left and one from the right let's see uh the basic thing the basic for short the firstly the very basic thing which you could have seen or known by far if you have been following is the very normal thing is I'll get I go on to every index and then I can get the sum from the left and the sum of ones from the right so that is that can be one way that what you will do is very basically that if you will add the index I so you will just take the sum from the left part and the one's sum from the right part then you will go on to next index then you'll take the sum of like zeros from the left part and the sum of the ones from the right part so basically you are going on to all the indexes I which are just n indexes and then you will again for every index you will go on the entire left part and you will go on the entire right part and from the left part you will count only zeros right you will count only ones and you will get the answer so basically at every index you are going and for every index you are going the entire left and that entire right so it is basically of n² time and for sure space is over fun because you're not using any extra space now for sure it is way more than what we could expect uh for sure we can optimize this yeah let's see how we can optimize this so if we go back and look for what is what was required the only thing which was required is the sum of zeros from the left and the sum of ones from the right at any point of time so when we require at any point of time if we require the sum of only zeros from the left so why not store that thing previously so what I will do is I will go on in the entire array and then I will say okay at this point so far the sum of zeros Bally the count of zeros is actually zero one itself and if I go here so I'm just saying the count of zeros is two itself so with this I will store the count of my zeros from the left and ones from the right that is nothing but a prefix sum so I'll maintain a prefix sum of zeros which is one because I have one zero and it I didn't did not encounter any of the zeros so count is remaining one and counted another zero count became two and then I'll keep on going forward okay so you'll see that the prefix sum of zeros has become now prefix sum of ones because I need from the right or you can also see the suffix sum but I if I just write the same prefix sum from the right side then it will become the prefix sum from the right side so okay I encountered one of the ones okay that's a one did not encounter one I encounter one again increase to two encounter one increase to three encounter one increase to four and then four so that is what I got the prefix sum from the right for once and then at any point of time let's say if I am at this Index this value will say Okay up till so far this is the count of zeros and this next value will say up till so far this is the count of ones so with this I can easily get okay what is a count of zeros and what's the count of one at this index and I simp I can simply go into all the indexes and see what is the sum of these two values and which these two values have the maximum sum Whoever has the maximum sum as we can see this is having the maximum sum so this was the answer with this you saw the time used is actually o ofn because you pre-computed your prefix sum because you pre-computed your prefix sum because you pre-computed your prefix sum of zeros and also suffix sum of funds and space is O of n because you are also using that extra space to compute this perix and suffix sum now again a question will be asked Can you optimize this so yeah we can if you look closely again what you only wanted to do was you only wanted at this point let's say at this point of time or let's say at this point of time I just only wanted to know what is the count of zeros in the left and the count of ones in the right I'm just only concerned about count of ones in the right now let's one let's imagine that I only ask you what is the if I am at this point of time give me the count of zeros in the left and give me the count of once in the left only I'm asking you then what you could have done was you could have said okay byya um count of zeros as I am iterating on this from this left side only because my I pointer comes from the left so I'm the left side only so what will happen is I will come okay at this point and so on and so forth so I would very surely would know what is the count of zeros in the left and the count of ones in the left now as we know that we only have zeros and ones in this entire array so if I know the count of ones in the left counts count of ones in the left and I know the total count of ones in the entire array then for sure I can find out the count of ones in the right part because if let's say I know the count of ones in the left is one I know the total count of ones in the entire array is 1 2 3 4 four so for sure the count of ones in the right part will be total count minus count of ones in the left which is actually three so that is how you can easily get the count of ones in the right by just getting the count of ones in the left and for sure as you trading from the left itself so you would know the count of ones in the left so that is the technique which we will use that we will maintain or get the total count of ones firstly in the first pass I'll go and get the to get the total count of one in the very beginning and then when I have got the total count of one I will use that okay at this point my count of zero is one my count of one is zero so with this count of one is zero I can get the total count minus one count as the remaining number of on OB basically the ones on the right side will be actually 4 - 0 so one on the will be actually 4 - 0 so one on the will be actually 4 - 0 so one on the right side will be nothing but four so 0 count one right side count of 1 is four okay 1 + 4 it will give me a five so for okay 1 + 4 it will give me a five so for okay 1 + 4 it will give me a five so for sure this will give me a five as the sum then keep on reading your score with the maximum score basically you will have the answer as the maximum of answer comma the current score right that is how you can simply update that now when this portion is updated now you know one thing for sure that it will be very much done that it will be a time is O of n plus n and space is O of one why n plus n first pass to actually get the count of bus second pass is to actually compute this score value for every index now again now comes an interesting part why this question would have been asked by Google can you again improve this which is a follow-up three so now you which is a follow-up three so now you which is a follow-up three so now you will think now the brother want me to actually it is the most optimal you cannot go below time o of N and space o of one that is impossible to go because you have to rate on every of the characters but you will see it is not actually o of n it is actually o of n plus n so again we have a chance to optimize not pretty much but optimize in the one pass kind of way that okay currently it is a two pass you will have to iterate on your list twice maybe you can do it in one pass that is what interviewer is trying to ask you so we will again go back and think what we were doing while we were actually Computing this total minus current one count so okay if I am at this index I calculating zero count increase the variable as zero count increase the varable as one count if I encounter of one so with this Encounter of one I will simply compute total count minus current one count on the left and then ultimately my score will be nothing but zero count plus this value which is total minus one but as I said I don't know right now the value of total it is still a variable for me although as I'm iterating on from my left to right I will be knowing the value of zero count I will be knowing the value of one count but this total count is still a variable for me I still don't know the values so I can compute this value but I cannot compute this value But ultimately I want to compute this as say answer is equals to maximum of answer comma this exact value which is 0 minus sorry 0 plus total count minus one count this is what I wanted to compute right okay cool let's go ahead uh still that is unknown for us but still let's go ahead if I am at this index I'll again uh see if it's a zero or one if it's a one I'll update my one count and again I will have to find my total count minus one count that will be a simple addition of these two 0 plus total minus one which is nothing but these two now when this portion is done you will simply see that again you will update your answer with the updated zero count updated one count but still this is unknown okay still no worries then again I'll go on to zero uh one again this value so what you could do is you can just forget it even existed again remember it existed but right now forget it even existed so what will happen is you can just update your answer with answer of 0us one count and as you saw the total to was same because total is nothing but the total of one count it will remain constant forever right in everyone so when you have computed all your answers just in the end add in your answer is equals to answer plus total count because this total count will be added in every one of them but byya why you added in the end it is because as you are going in from the left to right you don't know what is the total one count until and unless you reach the end as you will reach the end you will have the one count this one count which is in the end will be the total one count which is what you want to update and for sure we wanted to do in one pass so we will use this total one count in the end only and that is how you can just simply add this total one count in the end of your answer and answer is nothing but 0 count minus one count at every step maximum value which is what we wanted and total count was constant so we just simply add that in our answer and that how you can simply get it just one thing that up till what index you lerate as you know that I stressed on the word we need to have two non-empty subrings so if I start from non-empty subrings so if I start from non-empty subrings so if I start from index zero I will go on I know if it's a index n minus one I will go on up to the index n minus 2 only why because if I go up to this index left part will be this right part will be this so I need to have right part also non empty if in the worst case I would have gone to this value as the entire left part so I would have got the right part as empty which is wrong so that's I will go on from 0 to n-2 which means 0 to n-2 full values to n-2 which means 0 to n-2 full values to n-2 which means 0 to n-2 full values or 0 to nus One open value that is how I will iterate on from my left to right so ultimately I will have the time is O of N and space as o fun just one pass solution we will have for this let's quickly see that how we will code this up uh again uh we just want one count uh we just want a zero count and also we let's have a n which is s do size and we'll have our answer let's initialize with in Min because the answer can be negative also because for it's Al you can also initialize this with the sum um zero also uh no worries in your part it will not be negative it's a sum of the like ones and zeros right cool uh then I'll simply iterate on my entire index as I showed you I'll go on up till less than n minus one because I need to have both of them as nonempty now a simple check if this is a one simply increase the one count uh else you can simply increase the zero count because either one of them will be a zero or one because it's a string so either will be of them is a zero or one now as usual I'll update my answer with the maximum of answer comma for sure I have said it is 0 - 1 now again remember have said it is 0 - 1 now again remember have said it is 0 - 1 now again remember it is minus one because ultimately it is a plus total count minus one right because one is from the left I want one from the right so I will ultimately in the end I should add uh answer is equals to answer + one like answer is equals to answer + one like answer is equals to answer + one like one is the total count of uh my one I have to return that answer but if you will look off then you will see that you missed the last index maybe that last index is a one so just have a quick check if that s of n minus one if that would have been a one so uh it would be good if you had increased your one count and let's see that what we have got so far uh we have got some issues so let's see okay so it's because uh we have this value 0 - 1 can be negative if we have value 0 - 1 can be negative if we have value 0 - 1 can be negative if we have only ones so we will have to get as a negative n or you can just simply say as inin and then I will have this value as the correct value after adding it should give the correct value so that's the reason that we will have because this can be negative cool uh thanks watching byebye yeah and it will have the least time complexity as you can see just minimal and space Also bye-bye
|
Maximum Score After Splitting a String
|
divide-array-in-sets-of-k-consecutive-numbers
|
Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring).
The score after splitting a string is the number of **zeros** in the **left** substring plus the number of **ones** in the **right** substring.
**Example 1:**
**Input:** s = "011101 "
**Output:** 5
**Explanation:**
All possible ways of splitting s into two non-empty substrings are:
left = "0 " and right = "11101 ", score = 1 + 4 = 5
left = "01 " and right = "1101 ", score = 1 + 3 = 4
left = "011 " and right = "101 ", score = 1 + 2 = 3
left = "0111 " and right = "01 ", score = 1 + 1 = 2
left = "01110 " and right = "1 ", score = 2 + 1 = 3
**Example 2:**
**Input:** s = "00111 "
**Output:** 5
**Explanation:** When left = "00 " and right = "111 ", we get the maximum score = 2 + 3 = 5
**Example 3:**
**Input:** s = "1111 "
**Output:** 3
**Constraints:**
* `2 <= s.length <= 500`
* The string `s` consists of characters `'0'` and `'1'` only.
|
If the smallest number in the possible-to-split array is V, then numbers V+1, V+2, ... V+k-1 must contain there as well. You can iteratively find k sets and remove them from array until it becomes empty. Failure to do so would mean that array is unsplittable.
|
Array,Hash Table,Greedy,Sorting
|
Medium
|
659,2261
|
57 |
in this video we'll go over lead code question number 57 insert interval now if you haven't already I'd highly recommend you first watch my video on lead code number 56 merge intervals as it's a very similar problem the link is in the description so please go check that out okay now let's look at this problem you are given an array of non-overlapping intervals where each non-overlapping intervals where each non-overlapping intervals where each interval consists of a starting and ending value and the intervals are also sorted by their starting value you are also given an interval called new interval that again repres presents the start and end of another interval the task is to insert new intervals into the intervals array such that intervals is still sorted by each interval starting value and intervals still does not have any overlapping intervals and we'll need to merge overlapping intervals if necessary so for example let's say this is the intervals array and the new interval given is 6 to 7 if we visualize this on a number line then these are all the intervals in the array notice that there are no overlaps and they are in sorted order the new interval would then be over here in red since there are no overlaps we can just insert the new interval in the correct position and return this array with all five intervals now what if the new interval went from 5 to 13 then this is what it would look like notice that now four of the intervals overlap with each other in some way so we'd have to merge them all into one our answer would then contain only two intervals the first one is unchanged and the second one goes from 4 to 15 since all four of the intervals got merged into one so now let's look at the code and see how we can do this in Python let's say that this is the list of intervals and I've indicated the index of each interval here let's also say that the new interval is 48 the first thing we'll do is create an empty list called result since it'll hold our final answer we'll also initialize a variable called I to zero I will be used to Traverse the intervals list we'll then enter three W Loops which represent three different sections of this code for each one of these Loops we'll make sure that I is less than the length of intervals to make sure we don't go out of bounds the first Loop will iterate as long as the ending value of the E interval which is at index one is less than the starting value of our new interval since the intervals list has no overlaps and is in sorted order we know that any interval that ends before our new interval starts must be located entirely before our new interval so in that case we'll just append that interval to our result once this condition becomes false then we know that we may have hit our first overlap so then we'll go to the second Loop and start merging intervals at this point if the start of an interval is less than or equal to the end of our new interval since we already know that this interval has an ending value that is greater than the start of our new interval that must mean that the two intervals overlap for example the interval 35 overlaps with our new interval 48 because it starts before our new interval ends and it ends after our new interval starts so if that happens we'll merge the two intervals we'll do this by taking the minimum of the two starting values and make that the new starting value of our new interval then we'll take the maximum of the two ending values and make that The New Ending value of our new interval and we keep doing this as long as there are overlapping intervals once this condition becomes false then that means all the rest of the intervals start after our new interval ends in other words we've now reached a point where we're supposed to insert our new merged interval after that the only thing left to do is to append the rest of the intervals to our result and that's it so now let's try walking through an example the end of interval I is two and that is less than the start of our new interval which is four that makes this condition true so we can just append the interval one two to our result then we'll increment I and check again the end of interval I is now five which is not less than four the start of our new interval so now we'll have to check for a potential overlap the start of interval I is three Which is less than the end of our new interval which is 8 this confirms that the interval 35 overlaps with 48 so let's merge them the minimum of the two starting values is three so let's change the starting value of our new interval to three next the maximum of the two ending values is eight so the ending value of new interval will just stay at8 then we'll increment I and check the next interval 6 is still less than eight so it's another overlap the minimum of 6 and three is still three and the maximum of s and 8 is still eight so new interval remains unchanged then let's check the next one here 8 is equal to 8 which is still considered an overlap so let's merg these two the starting value of new interval stays at three but the ending value gets updated to 9 now when we check the last interval we see that its starting value 12 is greater than the end of our new merged interval which is 9 that means that there are no more overlapping intervals so we can finally break out of this Loop and append our new merged interval 39 to the result the only thing left to do is to just append the rest of the intervals given since we know that there are no more overlaps so let's append 1216 to our result and increment I now equals 5 which is out of bounds so we finished appending all the intervals all that's left to do is return result and we're done
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
1,697 |
hello guys welcome back today we are going to understand the liquid question okay so today leader question we have given is uh 1697 as you can see right so this question is uh very important because this question has been asked in the thing and but Google has asked this question multiple times okay so let's continue to understand this question so the question 1697 we are we have given is uh saying that checking existence of edge length limited path right what does it means what we will understand through uh understanding the uh you can say paragraph right so let's read the question paragraph So question paragraph is starting with an undirected graph of n nodes is defined by is length is list and the VR is list of I is uh u v and distance right we have given now it denotes that the S between two nodes u and v with distance we have given right so note that there may be multiple Aces between the two nodes okay there will be multiple nodes there will be multiple Aces between the two nodes that we can have right and given an array query we have given equations such that query of J is PQ and limits right so your task is to determine for each query of J whether there is a path between P J and Q J right such that each is on that path has a distinct uh strictly less than limit okay we will understand this one don't worry after that we will return a Boolean array that is called answer or answer dot length is what query dot length Okay and jth value of answer is uh true if there is the a path of query J is true and false otherwise okay means it is saying we have to return Boolean answer where answer dot length Okay is equal to queries dot length right that we have that answer array we have to return Boolean answer array we have to return right so it will give you in the true and false as a array it is saying so when we will we have to return When the answer dot length is equal to the query dot length okay and how query is given queries given as a p j a p q and limit where p and Q is a path between p and Q you can say as a node and we have given the limits uh there is a ah distance less than this one limit OK this is the distance will be ah between this limit right okay now it is saying the jth value of the answer is true if there is a path for the query right queries is true otherwise we will keep false correct how we will understand this the value of answer is true only if the query of J have the true if not then we will understand this is value of answer is false okay so let us understand this example in which we have given this triangle uh type figure it's just denotes uh nodes 0 1 2 nodes 0 1 and 2 nodes and its distance we have given like this okay and there is two distance we also given what does it mean is we have given n is equal to three nodes right and we have given is list right so these are the S list and these are the queries we have given okay so uh this figure actually as you can see the explanation it is saying that the ever figure shows that the given graph note that there are two overlapping A's between 0 and 1 right so here as you can see if there will consider this path right so there is if there is uh you can say one and there is a zero right let's suppose like this so there is already a path like this okay so there is also another path let's suppose like this okay so I'm not just I'm giving it Direction but let's understand just for these two right so equal condition is two this can be 16 or again this key is two this can be 16 right so it between 0 and 1 right between 0 and 1 there is two overlapping Aces we have right that is 0 and 1 and that has the distance distances like 2 and 16 for the every query that you can see here right so between 0 and N1 there is no path right between 0 and 1 there is no path because it is overlapping right and where each distance is less than 2 right if each is between as you can see for the first query right as you can see here 0 1 and 2. so this uh first query is saying that between 0 and 1 there is no path where because each distance is less than 2 okay and uh thus we return the false for this query we have to return the false for this query so for the second query if we will see here there is a path between 0 1 and 2 right so of these as is with the distances less than 5 thus we return true if uh this query have right so next what we have query 0 2 and 5 means ah we have what first we have let's suppose like this we have query for the second query let's Suppose there is a path between 0 to 1 and 1 to 2 like this okay we have this is the path we have given in the figure as you can see right but the distance is what distance is 5 right but the two s's with the distance is less than what five so thus we will return true because this is 2 right so in the first query we'll say it is less than 2 right so the distance what we have 2 and 16 we have given but that query V is given 2 and it should not be uh less than 2 right it should the distance is less than two and so that the it was giving the first query was given false right this one this is given false but this is giving what true you got it right so uh let's continue next one okay similarly we have uh given this one right so as you can see the queries we have even here at 0 4 and 6 14 and 0 for uh 13 right so the uh as you can see here right uh 0 and 4 let's suppose going to zero and four like this it is saying 0 and 4 like this okay so if we will see here right so what we have maximum is what 13 right so the distance should be what the minimum it should be greater than less than ah 13 No it should be great here is 14 but it is 39 so we can say yeah it's true but when you are talking about this one this is what we have distance 13 so it is false because it is it should not be less than equal to 13 right so that's why we are getting like this okay so better we'll understand uh the con constraint now so we'll you will understand okay so constraint we have given n so to be greater than equal to 2 and 10 to the power 5 and these queries we have given is list query list these things we have given length should be it is as list and query list will be at each Index right each element should be have length three okay so internal arrays length should be three elements will be there in there now these things is given this is also gives to not be equal to and uh distance and limit is given that is like this over there be multiple Aces between the two notes that's what you have to understand so when this concept is coming they are there may be a multiple edges between the two nodes right it means we are coming with the you can say as you know the Union right so Union concept is coming only because of the multiple edges between the two nodes is coming and that's why we have to find the Union right so the our approach will be distance uh this joint set right in which what we will do will ah we will have our s list as you can see here right we have as list and query we have given and we will mark this initially as a these nodes right so initially let's store the indices in the query right as you can we have right here and sort it based on the weight limit and we'll sort the S list based on is weight right that will do and finally whatever will do here that we will return as an answer right so we have given our graph right with the weight and bi-directional is with the weight and bi-directional is with the weight and bi-directional is and a set of queries right so for each query we need to determine if it is uh possible to go for go from one a node to another while only using as is with uh where it's strictly less than the limit specified in the query right so the simplest solution would be to perform a breadth first search right VFS you can see all the DFS you can also do for every query right so starting from the one of the node and only considering s with uh weight less than its limit right so until we reach the each at the end of the node right uh we are runoff or out of the aces yeah right so at that time what we will do however this approach is not efficient because we are going doing these things right because we would end up with traversing and the same is repeating repeat repeatedly and will come for each query right and that's why we can say this is not efficient right but another way to implement the same thing right either will you can do like I am trying to say actually you can do both BFS or DFS right but that is not uh efficient because we are using the same uh you can say ages multiple times it will repeat you uh with each query okay so another way to solve this problem is to create a connected component right so when the connected component concept is coming at that time what you have to understand you have to focus on only the distance at Union correct so another way to solve this problem is to create a connected component and using only SS with the weight less than the limit as specified in this query okay so if the both the starting and the end nodes are in the same component it means there is a path between them so that uses only s with the weight so that should be less than the limit so 2 implement the solution we can use the distance set Union that is called you can say yes you can say or Union find data structure so right that we will understand here okay so if you are already familiar with this one so either you will go and do some Hands-On either you will go and do some Hands-On either you will go and do some Hands-On through the Google and uh you'll take us you can also find some uh ebook or PDF right or if you have any book that you can see the disjoint sets Union or I have also already uploaded multiple videos on design sets you can go through if you have already uh following me on this uh explore Honda right so you can have the union find and DSU videos right let's understand for uh let's continue now so if for every query which generate the connected component from the scratch right so what we will do we will edit all the edges in each query then the approach will still not be optimized enough instead we use or we can use we can do uh is we can sort the query right uh in the array by the weight limit in the increasing order so the advantage of sorting is that when we reach a query at least at index I right so we will itate to create a connected component with the S having bit less than the limit right so we can utilize the component created in the previous query with a weight limit that is we can say whatever we have given in the query that is the limit right so as it cannot be more than the current limit right so what we will do that we have given in the limit right so this limits the need to generate the connected component right so ah for new right for each query it will increase the optimization of the solution right what we will do the organizations resolution right so we can also sort the as by their weight in the increasing order as well as this allow us to easily uh we can say process the s in the correct order right so what we will understand let's understand here so first of all what that's why what I did we are going to follow the disjoint set right and our purpose do not use DFS and BFS only because we are we have this query and the same node we are coming with uh same nodes right so we will repeat the same thing again and that is not good idea right that is not the efficient way and that's why what we will do will make a connected component and we will use here so that uh you can ah you can give the optimized solution right so first of all that's why we have going to do only with these two answers like but if you want to see the implementation on DFS or VFS please let me know in the comment box I'll do that okay so let's continue the DFS Union and will continue so first of all what we will do will store the indices in the query as you can see and we'll sort based on the weight right so as you can see we have given initially 25 6 and 15 as its uh get limit and we will sort the is based on the as-bit so we have given these two on the as-bit so we have given these two on the as-bit so we have given these two things that we will do later okay now understand after sorting right what will happen uh it will look like this one so now the query is look like this one okay so initially what happened the it was 1 6 25 166 and uh two one uh five right but now what we have it is after the Sorting it is coming like what one six one two one fifteen two and one six twenty five and zero like this we will take we will create one uh indices like this okay and the previously that we have one four uh five one five two four ten like this those things we have so we will take the uh indices like this only we'll start with two five uh 15 sorry five only ten eighteen like based on the distance we will sort right as you can know as you can see the we have uh sorted based on its uh you can say the limit right and this one we have sort with the distance right this is based on the distance sorting right and here we have to deal with the limit one okay so now this task is done now what we will do here right the next what we have to do we will start with the edge index on query index so the query is what we have given 1661 and first node we have given is one and second node we have is a q let's suppose right so first node is what 1 p and Q right what we have even p is one and Q is 6 and the limit is what right the limit is 6 as you can see here right now original index and query index we will take right that is one so initially it will look like this only route so what we will do we will include all the A's in our graph and which has a weight less than uh six right that we will see okay so now our current uh is what 2 3 2 right the first one we are talking about here right and this is our first query right so from the first query we have got the first node second node weight and it's this one right original index or you can say right that we have here and this is our original index actually okay original index why you can say okay and then uh the width the final weight what we have here is six we have right so we will take we will uh include all the s's in our graph which has less than weight of six right the limit less than limits right so current is we are getting this one so what we will do we will include it when increases is index by 1 right so as you can see the its uh distance right it's a you can say weight is this is uh less than six right so what we will have all will check the weight that is it is less than six so it is we have two we have five we have and here five we have right but it is 10 right so we will not take this one currently So currently what we have ah now we have the index 4 and query is 4 there are two y because we are connecting this one right so one will connect with uh now as you can see one four first it is two and three so first we have connected two and three this one is connected here two and three right then what will one four now we'll connect one four right next what we have one five right so we'll connect to one five okay next uh we have uh two four right here as you can see so we'll connect two four okay and uh we don't have next right three five uh okay this is 18 and 20 that we will see later okay so now as you can see what will happen uh initially uh the S index is what four we have right Edge index is four 0 1 2 3 right now this is done right and our query index is what two we are at here and here now it is fifteen right so once it is 15 till 10 we will cover right and we have done till now okay after it is saying one when our index is uh the query index will move to here right so it will come it will cover this two also okay to do that now you can see when our ah we have included a six type at that time our current index is what this one so we will include it then our index will increase like this only okay so that's why we are mapping each time like this we have continued this one doing and finally we will come to here only that we have already seen right after coming to here right what we have next query what we have uh 1 6 and 25 that we are talking last query this one okay and the query p and Q we have given is one and six and uh limit is 25 now what we will do we will include all the edges in our graph which has less than the weight right and to do that what we have to do uh three five and eighteen and five six twenty we have given right the s is we are talking about this one and this one okay right now we'll check the its weight 18 and 20 is less than 25 right 25 yeah so we will include that one okay but the question is that we have a 3 5 here yeah we have three five is here right here and next what we have 5 and 6 is here right so that we will do here okay 18 and 20. now you can see now the p and Q that we have it belongs to the same component right so it means we can reach from one to six right we from one to six we can reach right so uh via each one right so from the one to Here We will we can go right ah Which is less than you can say as you can see here five and here what 20 is 25 right so thus we store uh true at our query index in the answer array and we'll increment our query index by one okay so now we have completed everything right so first query for the first query is it 2 yeah it is true that it should come because it is less than 25 right and we can go from one to six we can go by 24. now what we have two uh one two and it is fifteen right so from two to one right from two to one we can go so it is coming from here to here right where we don't have directly so it is it will come 10 and 15 right it will become what 15 so it is equal to that one but it should be less than so it will come false right similarly ah coming to here right 16 25 what we have one to six is 25 so it is again it is saying it's true okay so I think you got it okay so from doing the two uh okay sorry I was coming from here right so it will uh will yeah we can say we don't have any direction for this one I'm sorry yeah there is no Direction okay so for that what we will say this is false this will give false but this will come true and this will come true okay now ah we have the final answer right because we have seen it is true and it is false and it is true okay like this okay now what we will do uh we'll come to our ah coding part and let's do the coding section okay so let's continue now okay so let's do the implementation I will increase the little phone so uh we will understand here okay so first of all what we have given our solution class right so this calls for the solution class what we have to do we will create uh now we have to do the Sorting first right we have the given we will sort uh both guys initially as you remember we have did sorting right so to do that what we will do we will create uh sorting things and we will do the implementation of this one okay so uh either what we will do uh we have given this one it will return the Boolean right to do that what we should do actually here we'll take uh we'll create a union file letter class so I'll uh we will create a Union and this we can say fine so this class will create letter so this is our Union find and we'll say this is our new Union and find right like this I'll create and this is our n right so to create the union find class right what we have to do we'll create our Union find class letter let's suppose I'll create here class Union find and we'll create later okay we'll create later so first we'll continue this one and then we'll do that one okay now what we will do we have our uh query right we have our query and this is another query account and this is nothing but what we'll do our we have queries right so from the queries uh this one will do our link so we will get our query length right query count how many query we have that we will see right and one of the things that we will take is our and service store all the answer uh that we will take as a Boolean yes or no right that we will return right so this is our Boolean and this is called our answer right so this answer will be an array and it will store a Boolean type value right like this okay sorry this will take like this and we will give the size error as our query count on this true or false that will return and finally after doing the store thing right what we will do we'll return this answer only okay so let's suppose we will return this answer right so our purpose is to find this answer only okay so to find this answer what we have to do will uh create uh the origin indices with all the uh query right as we have already seen right to do that what we have to do we'll create a original index and that will store here okay and to do that what we will do first we'll create our query with the index we can say I'll say query with index okay so I'll pass the value here that is our uh that will be our array actually today we can take because it will contain uh array of array right element so I'll take like this and we'll pass our the length could be one first it will our query right query uh count this one and another it will be 4. so for initially we have three element as you can see in the query it was a p uh it was what we have p q and then its limit right now it will come its uh original index you can say origin null or is the null original indicator suppose like this origin index okay like this some people will say I don't know the English okay so this will be our original index it will look like this one that will come as each uh value we can say okay that will take now coming back to our uh thing how will initialize this one so we will take one ah for Loop and we'll start with i equal to what will start from 0 and then we'll uh I should be less than what our query count so we'll go with the query count uh here and we'll say I plus so we'll I will work on all the query and we'll check will initialize its index to do that what we have to do actually we have the query with index side add here will pass I and another will pass its 0 right so at 0 what will store let me uh say here so it will become from the query that will come we have our queries right from the query we'll get I and its zero value okay how will doing that you can see right like this okay so uh these things will take like this okay so from I will start what 0 1 2 and 3. and as you can you know 0 1 and 2 will remain the same because we are it will remain same but only this thing will change right why because this is nothing but our original index and that is our I okay so only this will remain same because query contains all elements with p and Q and its limit only we are adding original index and this original is nothing whatever this index correct I think you got it now what we have to do you can do uh by another way also just will take the count of this one and we can use as a will take one variable also we can use as a original index count sorry original indexing count is nothing whatever query count right but we are doing uh you can say Union so it will require some time okay so that we will see later now what we should do now here first of all uh we'll sort all the edges in the increasing order of the given uh is bit right based on your weight we will do and to do that there we will write one sorting function and we'll do uh we have given the S1 right so as you can see Edge list we have given that we will sort after that what we have to do we can sort the query index that we have already the Sorting things that we have done right sort and then we will pass our uh that this index we have just completed right both will sort right so these things we have done as you have remember the previously what we have done these are steps we have already done right in the there now coming back to here what we have to do will take two things first it will take uh as index right and from The Edge index we will iterate over the uh each query one by one so that will find our answer and to do that what we have to do actually we'll take our integer and that is nothing whatever is index okay so this is index will take our uh let's suppose I'll give like this so add index will take what its value 0 and we will write it on the query now so to itate on the query we have take we'll take a for Loop and this for Loop will continue I will do that to do that what we have to do we will take uh index and this is nothing out of Q uh query and this is our Index right let's suppose like this okay so carry index will start from here zero and it will go to its uh query count right so let me you can say Q index well so you can say and it will go to our query length right query count and this will come to query index and it will nothing but a plus you can see or you can see it like this one by one uh index it will increase okay like this you can say plus also now what we will do uh we'll take int P into P we know the p and Q right that will how we'll find we have the query Index this one so from here we have already taken you can take here from here right will pass p and similarly we'll take a queue right so to do that what we have to do we'll take int queue and will pass like this now I is nothing but our this one correct and this is like this okay so P will come from 0 and this will come from 1. now we know what we have to do right now we will make the join to make the join that we will create here a function that will do later so we have Union find function uh say object from the object if I'll do join right so there is there we will create two things we will pass two node one let's suppose node one and node 2 will pass and this Node 1 and node 2 will do uh joining right so to do further this one we will do later right so we will remove from here only now what we have to do we have to initialize our tool initialize this one what we have to do we will uh we will do this one only because we have our query and query index and limit that we have already done right so to find this query and limit we have already done this one right as you can see from here so let me write this one and another this one okay as you can see so now we will find our what int end limit okay and this limit will come from what query Index this I and this is nothing of our nothing but our you can say original index side and this will come from about three as you can see and this is nothing but our this Square index and this is our int oid original index right original index you can say I will write query original index like this okay so we'll understand okay now these things is done correct after this that we have to I have told you that we will do that is our join thing to do the join what we have to we will attach all the edges that will satisfy the limit right given by the query that we have in the query right so to do that what we have to do we will make a while loop on this while loop what we have to do will start with the is index side we have our is Index this one so from the S index we will start from what is list right we'll go with Edge list Dot length right and it should be the is list right Edge lists at uh you can say is Index right Edge index and another will take add two that we that is nothing but our uh the uh distance right if it is less than the limit we have already calculated so you can write like this or what you can do you can say this is nothing but our distance you can say dist distance right and this distance will come forward hint distance and this is like this okay so you can do this right and you know how to what to do now right this will our uh the distance that is this is the different thing as you can see so this is done now what we will do now we'll make a while loop what I can do I'll put like here okay now what we have to do we will find the node side two nodes we have to find from p and Q that we have already done right so now we have to take two nodes that will come from ah we will consider as a p and Q is nothing but our uh node right to do that what we will do we will uh consider our will take from our node uh let's suppose I will take rather than Node 1 and this node one which is nothing but we will come from y it will come from here only as you can see right so this value will change only zero let me remove the space okay now similarly we'll copy this and we'll add for node two and this is nothing whatever two and this will come from what one okay so both Node 1 and node 2 will come here now we have already our uh Union find object right so the union fine object we already have here we'll create one method that will do later join thing and we'll do the join if you already aware with the unit find right so in the you can find we can join two node using our join function with that we will create later don't worry and node 2 like this once these are connected right we are doing connect Ed nodes right now we have connected the nodes right and to do that what we have to do we will now move to the next is site like we'll go to the edges Index this one and here we'll do plus equal to 1 we can increase plus or one will do okay now I think you understood this one so after this there is one thing we have to do so if both node belongs to the same component how will find that so now if both uh if both nodes right are in same ah component or group right or for in group okay so in that time what we have to it means we can we have reached to we can reach them right it means what it means we can reach from both node right from both nodes we can reach from both nodes each other I think you can understand okay to do that what we have to do we will write our uh answer right this is our answer at what these are Boolean things right so we'll have our uh query Index right so we have already the query index original index actually okay and at the query original index what we have to do will uh from the union find object will are they connected if they are connected will create one is connected method let's suppose is connected or R connected you can make is connected uh nodes right will create and we'll say if we have ah two element two p and Q we have nodes right if both nodes are connected that will store at the answer and will return this answer right so Ah that's all from this one only we have to create one Union function that will say right what we have done we have created a Union function now we'll create our query and this query count uh we will do I will do the looping and this answer will take will store all the connected component as you can see here if this is connected component from the union find will return the answer this is we are doing right and rest of the thing that we have done uh the mathematical things right that we have seen so here what we are doing we are adding one original index and after doing original index we will do the Sorting based on the ah this one right and after sorting this one what we will do we will find our distance right on the distance we'll check the limit if it is less than limit and less than the easel index will have we can join both indexes right both nodes will join and we'll check if the nodes are connected will add on to the answer will return the answer right now this is the minor things you I think you have already done right so to do that what we have to do we'll create our unit find class and file to create the unified class let me little bit tune this right okay so to create the unit find function uh unifying class right what you have to do we'll take two things first we'll take a int and this is our nothing but our uh group right uh yeah you can say group like this and this will be our data right another will take what int uh rank and this is also a array so two things we will take two array Rank and group right that will take and uh will initialize the union find right to do that what we have to do we have our Union find class right so I will create our Union finder Constructor and this Constructor will take as a array size let's suppose this is nothing whatever size and this size it will initialize initially right to do that we have our group right on the group what we have to do we'll create uh we are going to initialize this group that is nothing but our int array and this will take a size and this size will take uh we will also initialize the rank similarly equal to new and this is our int and this will take size so both are in slide now right now what we will do ah after this right we will initialize all this value right how will initialize to initialize this I will start with int I equal to 0 and we'll go to its uh size that is our size and I plus will do and here what we have to do we will initialize our group and group at I is nothing but our I right so all the value we have in a slice now right when we are defining Union find at that time what we have to do we have find we have to enter the size and that is done now right as you can see you if you go the upright here we are passing n right and this n is nothing but our this one right how many nodes we have okay so based on the Node you will enter this n this is nothing but our nuns if you remember and so this n will go to here all the size and it will increase uh or it will initialize all this group you will find like means you have the distributed com notes now you have to find the node and you have to connect the node right you have to join to find the node you will create a int let's suppose and this is nothing our find method so this find method will take you can say int node right and this node will find to find this node we'll check on to the group if this group we have already created the group right so on the group if we'll check the node if node is not null let's suppose if not equal to node supports so if this is not uh this one so to do that what we have to do on the group only we will add a node and this node is nothing but our find method right at the find we'll pass two thing the group and at the group we will find a node right like this okay this is done group at node and this one is done right so to do that once if it is not null if it is not equal to the node group at node is not equal to node in this we will do the find write and otherwise what we will do if you have we will return from a group of node understand okay just you have to understand the real thing how we'll find if we have already on the group we will return from there if not then we will add on the group right now what we have to do we'll do the join to do the join what we have to do uh we'll create a join method so I'll get and create one uh it will not return anything actually it will not return anything to do or will create the function as a wired join and it will take to uh node N1 and node sorry end no let's suppose give the name node only node one and I'll give the node two value okay after joining this one what we have to do we'll take uh we'll find this node from the group right we have already created the find method so from there I'll take uh this is a group one let's suppose group one equal to we'll create the find width method we have already passed so this is the method we'll do and similarly I'll do for the node on group 2. so this series also group 2 will say and this is coming as a node two okay so two note passing we will find the node and we'll uh say initialize in the group one and group two now what we have to do now we have already node one and node two if it belongs to the same group so how we'll check if we'll say if now group one so group one is equal to what group 2 if it is equal we don't need to do anything we will return the control just all after this what we have to do we will check its rank right so to if this is not the case both are not equal so we'll check the rank right at the rank what we have to do we'll pass our group like this okay so group one we have right that will pass and will check if this rank is more than this group right group 2 like this okay to do that what we have to do we will uh if it is greater than this one means we will say group this group actually this group will contain group 2 like this and we'll assign this one as a group one got it else in the else condition e let's see else condition what we have to do we will check another condition and that is nothing but our what less than thing the same thing will pass and will say less than if it is less than right if the rank at Group 1 is less than rank of group 2 it means what it means the we are going to assign this one right just we have to change opposite side we have to do means it belongs to another group at 1 is equal to 2. right like this we are actually connecting joining the component if this is not the case means else condition it is not greater than not less than it is equal to now what we have to do the group at what 1 we have to do like this only if it is equal or and as well as sorry as well as at rank you can I'll put a rank at 2 is nothing whatever plus equal to 1. got it that we have to do after this is done we will we have already created one another method that is what we have to created is connected node and it will take two things right this one we have taken one join method that we have already created another will create it is connected right so to create is connected method right what we have to do we'll create is connected method and we'll see this one right and this will return is connected is nothing but of a Boolean thing right so what we have to do p and Q we have as a node right so if this is our int let's suppose this is nothing but our node one and this is nothing but our node 2. okay so how will check the connected right so we have already seen that we will find its group first this one find our group if its group 1 and group 2 is here now just what we have to do we have to check is it equal or not like this if it is equal a sorry a not this one just will take return if it is equal no need to position just we will return like this what is the thing we have it is equal or not if it is equal it's fine if not it's fine so coming back to here let me I will uh recap that recap soon first of all let me it is running or not I should provide the running board okay so line number 23 let's do what we have done line number 23 it's missing semicolon at node 2 join wow what I think I have done Let's uh Boolean queries I think a spelling mistake can be here okay it's uh cannot be connected to integer why [Laughter] [Laughter] [Laughter] should take actually no we have to already we have account right query count we already have the why will we use this one directly query count now one thing I'm missing okay sorting thing sorting message we are not created so we'll create the sort method to create the sort method we can use here only okay or I can start here before completing okay I'll come back to here overall so first of all I'll create a void method and this will do sorting right to the to do the sort right we have to pass an integer array right so int you can use the interval function of array also to do that but it's fine uh we should create our own function that is also fine to do that what we have to do either you can use arrays right so I'll use arrays.sort I'll use arrays.sort I'll use arrays.sort and we'll pass two things the first will of us our array right and another thing what will pass new comparator I'll use the comparator right compare a term like this okay so computer will take what integer and this integer is nothing but our array and this is done as its type and the server compare method and we have to override here only right to do that just enter this one and do the semicolonia okay now what we have to do we will actually we are overriding right so it will not come actually let me see each overriding is coming or not override yeah after this actually we are overriding compare methods to override this one there is a method that is called public I think it will take integer type via your integer and we have to compare two variables that is nothing what our it is coming from uh into a like this array value and int B that is this value okay once we have this two value we have to return just return a at 2 minus that is our we can say we are index we are checking right so MB at both index we are checking A and B just we have to return this one okay let me run let's submit okay um is at these two index 0 limit okay what we can do either I can remove from here I'll pass here you understand right what is this is just a distance right we are at line 26 oh I got it this was the issue yeah it's working it will work fine just you have to take care of the uh where is at this index I know 26 while loop I will starting over here submit this one okay so what actually I'm doing here see first of all what we have to do we have uh given this one uh as list query and number of node we have given right so to do that what we have to first of all we will find we'll create a union find method uh class so this class will take a Constructor and it will take n and we have to initialize two thing group and rank and to initialize the group what we have to initially all the nodes will be there so we will how many nodes are there all we have to initialize independently and uh for to find the node right what we have to do we will create a find method and it will uh we have to find through if group of node is equal to node that's fine we will initialize otherwise we will return from there if we have already right otherwise uh we'll have another method that will join method so it will connect all the components to connect the component we have written this code right and uh to check the is connected component will create we have created this method so we will use these two method right how we'll do that ah we have the connected components from there we will initialize we will just uh adding one original index in into the given queries right where query we have given uh each element PQ and limit but we have to add original index now we'll add the original index like this just we will uh loop onto the for Loop and we'll uh add on to as original index like this after this we will sort both the uh is and as array and query array and uh based on all the queries right index for all the queries will uh go through one by one so each element will have p q limit and query index that we have original index that we have updated so we have just updated last time right in the last the as you can see here index like this side so that we will take so after initializing this one so we will have this value now what we will do we'll check if the distance is less than the limit we will find Node 1 node 2 will do the join will make the connected nodes after this will move to the next is right we'll check if it is connected nodes p and Q are connected node that we have just find out p and key from here right from the query nodes if it is connected we will assign the value true or false here and we'll finally return the answer and this is just a short method okay so I think you have understood this video if you have any doubt in the video any uh comment you have please ping in the comment box I'll go through here right okay and for the complexity I'll put into the uh you can say comment box please go through from here thank you guys thank you for watching this video
|
Checking Existence of Edge Length Limited Paths
|
strings-differ-by-one-character
|
An undirected graph of `n` nodes is defined by `edgeList`, where `edgeList[i] = [ui, vi, disi]` denotes an edge between nodes `ui` and `vi` with distance `disi`. Note that there may be **multiple** edges between two nodes.
Given an array `queries`, where `queries[j] = [pj, qj, limitj]`, your task is to determine for each `queries[j]` whether there is a path between `pj` and `qj` such that each edge on the path has a distance **strictly less than** `limitj` .
Return _a **boolean array**_ `answer`_, where_ `answer.length == queries.length` _and the_ `jth` _value of_ `answer` _is_ `true` _if there is a path for_ `queries[j]` _is_ `true`_, and_ `false` _otherwise_.
**Example 1:**
**Input:** n = 3, edgeList = \[\[0,1,2\],\[1,2,4\],\[2,0,8\],\[1,0,16\]\], queries = \[\[0,1,2\],\[0,2,5\]\]
**Output:** \[false,true\]
**Explanation:** The above figure shows the given graph. Note that there are two overlapping edges between 0 and 1 with distances 2 and 16.
For the first query, between 0 and 1 there is no path where each distance is less than 2, thus we return false for this query.
For the second query, there is a path (0 -> 1 -> 2) of two edges with distances less than 5, thus we return true for this query.
**Example 2:**
**Input:** n = 5, edgeList = \[\[0,1,10\],\[1,2,5\],\[2,3,9\],\[3,4,13\]\], queries = \[\[0,4,14\],\[1,4,13\]\]
**Output:** \[true,false\]
**Exaplanation:** The above figure shows the given graph.
**Constraints:**
* `2 <= n <= 105`
* `1 <= edgeList.length, queries.length <= 105`
* `edgeList[i].length == 3`
* `queries[j].length == 3`
* `0 <= ui, vi, pj, qj <= n - 1`
* `ui != vi`
* `pj != qj`
* `1 <= disi, limitj <= 109`
* There may be **multiple** edges between two nodes.
|
BruteForce, check all pairs and verify if they differ in one character. O(n^2 * m) where n is the number of words and m is the length of each string. O(m^2 * n), Use hashset, to insert all possible combinations adding a character "*". For example: If dict[i] = "abc", insert ("*bc", "a*c" and "ab*").
|
Hash Table,String,Rolling Hash,Hash Function
|
Medium
|
2256
|
344 |
Hello guys welcome back to take decision in this video you will see how to reverse swing swift code for to june challenge so let's not look at problem statement problems district governor of characters in the form of history and to reverse in tarzan subscribe i want to Request to implement and not the thing is nothing but a mirror in between and listen to this post no you can put in between the year will see you in every way hand side characters with mirror image on the right hand side ok so to-do List of right hand side ok so to-do List of right hand side ok so to-do List of Busty Mother in Place of Birthday Will Come and You Will Come and Gives Pain This Commentary of Chapter Reversal Will Be the One Can See This Will Not Go Through All Subscribe Must Subscribe Will Be Interesting To Know What Is The Most Suitable For Adults In Order To River Springvale Date Will Be To Apply To Point 120 Basically Want To Swap The Value Radcliff Interact With Joy Ride Point Subscribe Numbers In This Will Come Here And This Will Come A Day When You Will Welcome A Very Long Range Is The Worst Position Subscribe Solution Of The Very Simple Veer Vidhi Ki Left And Right Pointer Ok No Will Keep Shopping Between Every Character Use This Left And Right Pointer s1s This Left Isner Sudhir And Pin Code Share and subscribe to And After Thursday
|
Reverse String
|
reverse-string
|
Write a function that reverses a string. The input string is given as an array of characters `s`.
You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory.
**Example 1:**
**Input:** s = \["h","e","l","l","o"\]
**Output:** \["o","l","l","e","h"\]
**Example 2:**
**Input:** s = \["H","a","n","n","a","h"\]
**Output:** \["h","a","n","n","a","H"\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
|
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
|
Two Pointers,String,Recursion
|
Easy
|
345,541
|
1,870 |
hello guys welcome back today we are going to understand to delete good question that we have today 1870 so this is the question that we are going to understand today right so this is the coming from the uh delete your question right so question is one eight seven zero minimum speed to arrive on the time so you are given a floating Point number that is called R and it is given here in the example okay now it is saying that representing this uh our amount of time you have to reach to the office to communicate to the office you must take entrance in sequential order or you have also given like a densed array right the artist array right this distance here as you can say of length n and where list of I describe the distance in kilometer of the ith train right and each Trend can only depart at an integer hours so you may need to wait in each train ride so for example the first train takes ride 1.5 hours you must wait for an ride 1.5 hours you must wait for an ride 1.5 hours you must wait for an additional 0.5 hours before you can additional 0.5 hours before you can additional 0.5 hours before you can depart on the second train ride right at two hour mark right so it is given already okay like you said first Trend we have given it is taking 1.5 hours so you must wait it is taking 1.5 hours so you must wait it is taking 1.5 hours so you must wait for additional 0.5 hour so that you can for additional 0.5 hour so that you can for additional 0.5 hour so that you can depart the second train at a two hour mark okay that you will see understand the examples now we have to return the minimum positive integer speed in kilometer right and all that all the train must travel at four you'd to reach the office on the time and the return minus one if it is not impossible right I think you got it right so what question is saying that we have given uh this is the you can say train uh you can send train uh right we have given in kilometer and this is we have given the hours of the overall you can say ah Trend right now what we have here right so there is let's suppose n Trends we have and we need to take in order that I train will write for dist of I right Justified means this one we are talking about this 0 to the N number of uh Trends Behavior right so we need to complete this journey write all this trend within our given time right so these are given time so R is a decimal number representing the amount of time we have and we need to return the minimum positive speed integer that is required right so one more constant we have that is uh each Trend will depart at an integer hour right so if we completed the first right let's suppose it is saying 2.4 right let's suppose it is saying 2.4 right let's suppose it is saying 2.4 hours right so what will happen the first slide is completed at 2.4 R side completed at 2.4 R side completed at 2.4 R side then we can only start the writing the next strain at third hour right this is the things he is saying means you have in the point right but you are not going to start after 2.5 2.4 right not going to start after 2.5 2.4 right not going to start after 2.5 2.4 right you have to come go after three right so that's why it is saying that like our ride will complete the first ride will complete at 2.4 right complete at 2.4 right complete at 2.4 right our side means the uh the next that Trend we are going to take right will complete at three hours right third hour only okay so one hint in the problem description is that answer will not exit 10 to power uh seven right so the First new approach we can apply to do an exhaustive search diet over overall the you can say positive all possible uh positive speed right so we can iterate from 1 to 10 to power 7 okay and the first number that can lead us to complete the journey within our right and will be that answer but how we can find our some speed can make us complete journey within the constant time right so we can easily find the time required for individual right for each trend then the uh summing up and uh will have some total required time right if the total time is less than hour then it could be a possible answer otherwise not that's why you can see here we have given what this we have given hours we have given so give me one minute sorry so at the speed 1 the first Trend take one by one hours right and since we already at an integer are we depart immediately at one R okay and that's why ah the second will start three by one right so it is also going three hours right similarly the next will mark four hours right that is two by one our side and if you calculate all these our calculated the first is getting one hour then uh three hour then two hour one plus three plus two if you calculate it's come six right so total we have to mark 6 R Mark we have to take means exactly the six hour we have given and that we are good completing right but how we can find out if the speed make us complete the journey within the constant time right and that's why we are saying we can easily find the time required for individual right for each strain and then summing them with the give that we have given right to us and the total time required so that's why we can find this one right so if the total time is less than the given hour right this one then it could be a possible answer otherwise not so this approach right we can observe is not efficient right we need to iterate over the whole search space and then iterate over every train to find Total time so can we reduce the search space right so that we can do only by right what as you can see here right the bind research correct so as you can see we have given distance hours right how will do that we are taking left and right will take 10 to power 7 okay so what we will take I will take mineral speed so while left is less than equal to right okay till that what I will do left first right by 2 is mid right and then time required will take a function and distance will pass and the given mid will pass right if it is less than equal to R side because R it should be less than equal to hours time that required for the distance should always less than equal to the time given R right if that is the case it means minimum SPD is the mid right and the right will now mid minus 1. right let's suppose what I'm talking about let's suppose this is the range this year left at 1 and this is at 10 to power 7 okay in between that if we are getting mid here currently right mid is what left plus right by 2 this year mid if the time required let's suppose sometime some distance we have given and some mid we have given here x is a meter Point Let's suppose so this is your mid Behavior to complete this mid right we are taking less than equal to hours okay if it is that case means actually it is less than this hour right so minimum speed will be come out at here right because this is the speed and this is your ah kilometer distance right so distance and speed we have given so it will give you what it will give you time right so how will find the time distance by speed is calling coming time and that's why you will see here when we are calculating this one then we will find like this only okay that we will see later here calculating time right this time we are calculating here how will calculate that we will see later don't worry kilometer by sorry so minimum speed equal to Mid we will do if this is the case right and then now this right is here and left was here now we will switch from here to here so this search space is gone now right so now mid will become less than this one okay so this is less than minus 1 means now right is here got it so now the search space is this one only okay if that is not the case right if it is not less than this then we will find in here in the search space okay so left will become what here and right will remain here only okay like this means search space we are reducing here okay and if this will work like this right so you will get your minimum speed right similarly you have and it will reduce automatically okay on this one I think you know the binary search right now ah record require time right so this require time how we will find so we are passing the distance and the speed given speed will take this time in point now we'll start from i 0 to the length and for all the given distance we'll do what uh distance at I by speed will get our time right so this is your time now how we will find our time so time will convert time plus and then we'll check if it is not the last uh last value right if this is the last value means we are doing what Roundup right the selling value will take otherwise we will take that value like 2.4 will take right so that value like 2.4 will take right so that value like 2.4 will take right so for 2.4 it will take for the first it for 2.4 it will take for the first it for 2.4 it will take for the first it will take 1.2 and like this so if we'll will take 1.2 and like this so if we'll will take 1.2 and like this so if we'll come with the last so how much time it breaks up it will take one hour okay so what will take 2.4 1.2 and there will be what will take 2.4 1.2 and there will be what will take 2.4 1.2 and there will be some value right so let's suppose it will come ah three four right next will come 4.6 flexible so we will in the last 4.6 flexible so we will in the last 4.6 flexible so we will in the last point because we are taking this value so it will come nearby 5 okay around selling value and that's why we will return the time finally because after selling last value will update right so only the last value we have to do selling value otherwise the rest value will do only the sum all the time and this time will return as here okay I think you got it okay if you any doubt please bring me the comment box thank you for watching this video guys thank you
|
Minimum Speed to Arrive on Time
|
minimum-speed-to-arrive-on-time
|
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
* For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark.
Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_.
Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**.
**Example 1:**
**Input:** dist = \[1,3,2\], hour = 6
**Output:** 1
**Explanation:** At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
**Example 2:**
**Input:** dist = \[1,3,2\], hour = 2.7
**Output:** 3
**Explanation:** At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
**Example 3:**
**Input:** dist = \[1,3,2\], hour = 1.9
**Output:** -1
**Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark.
**Constraints:**
* `n == dist.length`
* `1 <= n <= 105`
* `1 <= dist[i] <= 105`
* `1 <= hour <= 109`
* There will be at most two digits after the decimal point in `hour`.
| null | null |
Medium
| null |
148 |
hey everyone welcome back and today we'll be doing another lead code problem 148 shortlist this is the medium one given the head of the link let's return the list after sorting it is in ascending order so this is just a sorting problem we'll be performing much sort in which we will just break down things to the this very lowest level for example this link list is going to be broken down into bars left and right then you are going to have two nodes on the left two nodes on the right then these two nodes uh these two basically separate link lists because we are going to break the link between these two and one uh these two link lists are going to be broken down into further nodes which is four will be the separate node two will be separate node one will be the separate node and three is going to be the separate node and then we will just arrange them or merge them in a sorted fashion so that's it so if there is not a hat or head dot next is null which will be just not had we will just say return the head so this will just get rid of our recursive calls and then we have to find the left so left will be just the head and right we have to find so self Dot get mid you can say will have the head okay so now we will just store right dot next in attempt so write dot next will be stored in the time and we will say write dot next short point to none it should be none because we have to make separate link lists these two should not point to will be in should not be pointing to this one because they are going to be two separate links four two is going to be a separate linkage and then one three is going to be a separate link list and then after that form is going to be a single node and two so does one and three then right should be updated by we can just say right is equal to 10 because right dot next is equal to uh to try dot next will be at the place of time now we will have a left which will just call the function recursively and say sort list passing it the left obviously and right self dot sort list passing it the right okay now we have to merge so we can just say return self dot merge list passing it the left because we are going to merge left and right now we have to implement the get mid method get made which will have head okay so how we are going to find the mid so it goes like if we have a slow pointer and a fast pointer and Dot next okay so while past is not null and fast dot next is not null we update our slow pointer one uh node app at a time and our fast pointer hits two nodes at a time so fast dot next is equal to part dot next then we can just return the slow okay so now we have to implement the merge list method so merge list will be having left and right obviously there are going to be list nodes and they are going to be return on list node so we are going to have a dummy pointer a note before the head of the linked list so current will be at a point of dummy so while we have something in our left alongside right they both have something in it we will say if left dot well is less than write dot well then we are going to swap so left should should point to should should point to should should point to left okay then we have to update the left so left should point to left dot next and this is going to be the case with the right one so current dot next should point to right and then right should be updated so right is equal to write dot next okay now we have to just update our current okay now if there is something in left in our left all right we just have to put it at the very end and else should point to write after that we can just return dummy Dot next let's see if this works and then I hope this works and this works let's submit it this works and if you have any kind of questions you can ask them in the comments
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
142 |
alright hello guys welcome to my channel today's problem is linked lists cycle 2 which is number 142 from the lick code okay let's get started first we're given the linked list to return the note where the cycle begins so if there's no cycle we have to return null to present a cycle in the given linked list we use an integer POS which represents the position 0 indexed in the linked list well till connects 2 so let's see an example the notes it's like this 3 2 0 4 - 4 in notes it's like this 3 2 0 4 - 4 in notes it's like this 3 2 0 4 - 4 in position is 1 it means that in the index 1 we have a cycle from here 2 so 3 e go 3 2 1 4 0 is minus 4 and it goes to index 1 because there is a cycle in the linked list so if in this case we have to return the second node of this linked list and if you see the example 2 there is 1 and 2 in linked list in position 0 index 0 is the cycle point so we have to return this note and in example 3 there's no cycle so we have to return minus 1 so this problem is easy if you are already getting used to using a linked list so my idea is like this so I'm gonna use the set and I'm gonna push the actual note H node iterating through all nodes in the linked list if I put the old nose in a linked list if there's a cycle in linked list there's must be the duplicated node in the set so I'm gonna check all the knows if the if that node is already in the set or not so if it is in the set it means that they're the first note which is in the set could be the answer so let's see the example so there's a 3 2 0 and minus 4 and let's say the cycle point is 2 as it is the same as the example 1 in my set I'm gonna push the all notes from head to the tail so I'm gonna push the note from 3 node 3 and node 2 n 0 n minus 4 so because the cycle is from index 2 after I go to the tail and I'm gonna go back to the index 2 because the cycle is connected to index 2 so I'm gonna check if note 2 is in set so we have assumed I sorry it was - not the - 2 so if it the sorry it was - not the - 2 so if it the sorry it was - not the - 2 so if it the - is in the set yes because you can - is in the set yes because you can - is in the set yes because you can see the notice 2 is already in the set so yes so it must be the cycle point of this linked list then what if there is no cycle if it is in the linked list so after I put all nodes in the set I'm we can get out of the while loop so because we didn't find the duplicate note in the set so I'm gonna just return minus one because it means that there's no cycle in the linked list okay so let's get started start the code now so we have you need we need let's say just turn notes I'm gonna start with pad to the tail and oh alright we need under the sets' which is the we need under the sets' which is the we need under the sets' which is the type is gonna be less note and set so from the start to the end I'm gonna iterate until the curve is not known so if occur is not know let's check if this note is in the set or not so if it is in the set you can return this notes right away because it means that the current colonel is in the set it means that is a cycle point so if it is not I'm gonna can move it to the tail and first if it is not in the set I'm gonna push it to the set because it is not visited nodes if it is not in the sense so and keep moving to the next so and that's it so it in the end of the linked list or I'm gonna get out of the loop because the current becomes no right so after we get out of the loop I'm gonna just return -1 this so this is I'm gonna just return -1 this so this is I'm gonna just return -1 this so this is the case that there is no cycle in linked list ok I think that's it for this problem and let's check this out Oh spray it has error you know what is return - oh I'm sorry return - oh I'm sorry return - oh I'm sorry I just first description what's in description oh yeah oh you have to return the bowl I'm sorry 9-1 okay return the bowl I'm sorry 9-1 okay return the bowl I'm sorry 9-1 okay that's good yeah that works ok thanks for watching and see you in the next video
|
Linked List Cycle II
|
linked-list-cycle-ii
|
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**.
**Do not modify** the linked list.
**Example 1:**
**Input:** head = \[3,2,0,-4\], pos = 1
**Output:** tail connects to node index 1
**Explanation:** There is a cycle in the linked list, where tail connects to the second node.
**Example 2:**
**Input:** head = \[1,2\], pos = 0
**Output:** tail connects to node index 0
**Explanation:** There is a cycle in the linked list, where tail connects to the first node.
**Example 3:**
**Input:** head = \[1\], pos = -1
**Output:** no cycle
**Explanation:** There is no cycle in the linked list.
**Constraints:**
* The number of the nodes in the list is in the range `[0, 104]`.
* `-105 <= Node.val <= 105`
* `pos` is `-1` or a **valid index** in the linked-list.
**Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
| null |
Hash Table,Linked List,Two Pointers
|
Medium
|
141,287
|
127 |
Hua Tha Vaikuntha Saal Problem No. 127 On Light To Today Khandhar Problem School Dress That Dr Ek Path Sahib Ali Bana The Most Popular Problems Only Khandhe This Very Frequently R10 Program Interview Some And Lord Of Companies Including Facebook Amazon The Latest Direct Questions Returned That Show In Body Problem Me Actually Agreshwar That My Subject In Word And Erogen And D Target S To Start With Hubris And Transformed Into A Bird Subscribe Everywhere Every Intermediate Board Transformation Is Different From The Only One Such Example Saver Start With One More Intermediate Words That And Jaishankar Difference by single character to a point S2 and different only in terms of one character adab-ghar at every characters between boys stree adab-ghar at every characters between boys stree ludhiana the karate kid to the same hua tha along with his being one with award list android dish characters of but from this point List only for the beginning witnesses 100 grams of turmeric and of the problem me to the number of bird in the best transformation 100 starting from the first second third and mother and finally Bigg Boss the number with oo hua tha the latest in example show latest seethe beeti Is the back in water and suji add water and would give word list and content over 500 1000 200 think about what should we do possible transformations a that from hit vaikuntha convert hit * heart by that from hit vaikuntha convert hit * heart by that from hit vaikuntha convert hit * heart by replacing it with heart with 2 and this world comes from this Is the from heart beating the god duty and 2012 debt in case of India replacement returned subscribe to that not going father of a daughter gets converted into doc player transformation from 2g and share if it gets converted into alleged g leave great place for visit again Just one letter difference and you can be converted into your logic and finally one and a half inch means the possible transmission available in this lap 225 from 12345 also give you can share with 300 bones but and press the word list for the example of three your solid This given question ten length is also given between one and 0 100 index pimple three letters between mouni roy the whole world is gone to be unique starting with e start to and all the world in this transformation and all the world in the world list and unique immediately Duplicates Another Thing But As They Have Only English Letters Video Share It 1 Choti Duty All Others Like This ansuia1974 Stars Words Can Have A Maximum Of Five Thousand Words You Soe Depend Question Answers To Return Bisht Path From Big World Tour And World In This Question are you definitely going to get half length updates possible daba ko subscribe and subscribe ki and when they talk about the shortest path we you really think about bf with sorrow and spread the search box in terms of one to three layer pendant mixture hidden Cam Length Always Sleep with a Bird Subscribe Also Latest Attack Hit Converted into Fuel to Keep IT Consultant and Change Selected for Hotspot of Sydney BTC-2012 Constant and Can Selected for Hotspot of Sydney BTC-2012 Constant and Can Selected for Hotspot of Sydney BTC-2012 Constant and Can Change It Half from a 2G Network BTC SBTC All the Best Tours and Travels Pay Tea Constant And Change 30.22 Ep That Shoulder Means For Every Word Which Can Have Some Money To Transform Actions And How To 10 Transmission Switch Off Topic Only Friends Awards Ideas Present In The Given Word List Solid Is Lineage Pocket And Point Of The World With The Same Thing In Next 220 Good Think About Alarms Artificial Algorithm And Artificial Gautam Som Vigor Generate All Possible Words That Can Be Made By Replacing One Character Torch Light Of Hadith Wood Explore Only 200 Words Which Were Present In The Dictionary The World As Provided And Reducing Weight For search strategy to explore and mentally sold but in this process decimal number buried always different levels with 12345 increase final number given meanwhile of some with this will be possible only solution in the long run hua lut soft oil and where given with Word list for at least a support we butter beneficial difficult converted word list and game set 100 mute thank you variable and just husband long list not just ₹ 100 ₹ 100 ₹ 100 quiet list s new set of absolute scale of loot hear brigade of word list S8 bank Withdrawal of widows set to mixture were going through a difficult don't see the results and difficult words by Sudhir and hua tha aam ki sister a victory class me kar check and beginning itself who and what is poison most of the questions in life and what is not in the World Best Day 200 So Let's Check The Best In The Beginning Itself 202 Life Word List For This Android Is Be Interesting To Note Part Of Birth Certificates Students Have Android 0 Which Arm 's Day Facebook On Why Right Also Latest 's Day Facebook On Why Right Also Latest 's Day Facebook On Why Right Also Latest Creator Why During Sales Late Why Is Equal To That And Adult Content Board The Beginning Quickly So Lets Of Bird's Father And Which Also Create Next Why Is So In Which Direction Of BF Is Next You Will Keep On Acquiring All The Children Odd And Thus You Will Get Him And Dependable Uvve Sign Next YouTube channel live and plus two equal at distance and distance id's cutting rugged arrest operation twist oil olive oil alphabet w tell 200 medicine take pradhan ss lunges why this dare hello viewers note anti a let's spot first word from this thank you show more ki And Difficult Word This Android Self Contradictory Tendency Think They Can Return The Current Distance Luta Day In The Short Term Special You All The Ne Birds Of The World And Members From Discussion For Generating All The Ne Birds Of Particular Word Were Look Through Every Character Of The World and every character which can generate all possible combinations starting from a girl where to ji sundha starter loop from 10 and outgoing all the best is 205 that is the number of directors number of location letters in english language write a ki and the wealth asli Ravana That It Will Runner Loop Now Crush Characters of the World So Let's Well Off to Give Went Inside of Children Rupees Characters Somnath The Running From 01-02-2014 Somnath The Running From 01-02-2014 Somnath The Running From 01-02-2014 Create a key and for Creating a Sharif and Equity Research Department 202 Are not from and Here You Can Define Balance Dubbed 60 Generator Slogans Dresses for Entertaining Crossroads Use This Point to Generate Are and Return Value IQ and A97 A Plus IE 80 Character Code of a Small and Also in Every Situation Follow I Will Start from Zero All the Best Wishes 6 That All The Best Math Five 's Omelet Generate The Characters Jerry Fisher 's Omelet Generate The Characters Jerry Fisher 's Omelet Generate The Characters Jerry Fisher Edison Twisting Daughter From There Food A Friend Hua Tha Loot Sunao Vighn Share And Can Live Through All The Best Sunao Hua Tha So Yes That I Let Me Yes Enjoy Che A Ki Soult Hi Record 2025 Class Tenth Board Dot Length I Plus And Schedule Of Characters Of Alphabets Year On 220 Means I'm Counting From 023 Length Of The World And Looking Through All The Best Sirvi Country Is Not The Same Word Soen Character His Immens Wealth of others like this has otherwise been considered as a neighbor heard order to generate disassemble need to replace word for add with character characters from different netu and replaced with a new day every sort were but this subscribe B.Com B.Com B.Com 2002 came that in this is Character Battery Plate Bike Character Itself In The We Start The Price Method From Five Plus One And Will Go Away Into What Length Is Now Navneet Mix On Half Lemon And If Neighbor Has Not Already Placid And They Also Need To Make 4th Tense The List Soft Checking Gautam Buddha switch off barf vid oo Adnan Sami par ki and other smell 8 ki desi bhi involve list started word list for December Buddha condition shrunk 2.13 tham market visit site today 2.13 tham market visit site today 2.13 tham market visit site today not prepared by adding a to arrested set to nodal department budget Weekend to the Why Not Unpleasant Wedding Suno check weather us as you know what is the means already done in this video you will next day be the son of everything that you are eating eggs going into next why right to travel the next journey and all the children want to be inside and over Thum Ki If Top Were Taking Away Stuff From The Why Su Redemptive Weight Lose Weight Reduce 2017 The Length Of The Weakness 001 [ 2017 The Length Of The Weakness 001 [ 2017 The Length Of The Weakness 001 That's That's That's Fun New Updates Reviews And Weer Is Like You Miss You To Ki And You Should Also Take Benefit New why this good to have something inside should cotton length is 13 something day B.Ed 2ND cotton length is 13 something day B.Ed 2ND cotton length is 13 something day B.Ed 2ND year and distant view Jhala 200 distance get settled and loot sugar and witch every time they have registered and who don't vansh withdrawn from hair that you their specific not In this process will not be able to find and world badminton sure selfishness eng du not meet r entertainment ki vrishabha kaat kaite example this is a respectable lakshmi samet now that when networks 365 fasting
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
1,833 |
code number 1833 maximum ice cream bars uh the question says it's a sweltering summer day and a boy wants to buy some ice cream at the store they are in ice cream bars and you're giving an array cost of land of length and where the cost at each index is the price of that particular ice cream bar in coins okay the boy initially has coins spent and he wants to buy as many ice creams as many ice cream bars as possible so we're supposed to return the maximum number of ice cream bars the boy can buy with the coins that he has and he can buy ice cream bars in any order okay this is great and um so for instance we have this number of ice cream bars at this specific costs and this guy has seven coins right and at the end he can buy a total of four because you can buy this bar and he's bought two ice creams costing two coins right so he still has five coins left which means he can buy this and you can buy this and he doesn't have any money left and you count the number of ice cream supports at this point they are going to be one two three and four so that's why we return four and the same goes with this the guy has five coins but as you can see every single coin here is higher than the amount of money you actually has so you cannot afford any ice cream but I'm so sorry boy and um so he doesn't buy any zero here that's fine and then here he has all these ice cream bars costing this all these amounts and at the end he can actually buy every single ice cream and he still has like two coins left this guy is a rich guy so we have some constraints at the length of the coin is n okay and um all right so this is just basically the question let's go ahead and talk about the solution for this solution let's assume that you have a very big basket of Korean which is right and your goal for this basket of oranges is to collect as many oranges as possible Right to be able to do that you actually need to collect the small like you have to just collect as many small oranges as possible from that basket right you find that you have space for more oranges than someone that gets the bigger ones right and you remember that this question is asking us to find the maximum ice cream bar So you're supposed to collect as many ice cream bars from this array of ice creams right as possible so to do that basically you just need to be able to sort this uh ice cream bars by cost so for instance in this particular example where we have one three two four and one we are going to have a sorted list which is going to give us one to two three and then four right now when we have this list with the sorted ice cream with the Salted ice creams by course you realize that when we take as long as we're taking the ice cream bars from the front right we can get to a point where okay you know we keep reducing our money as small as possible Right until we get to the point where okay we can't buy this ice cream anymore because we don't have enough money left or our money has finished something like that so that's basically what we have to do for this particular uh problem we just have to sort uh the costs of the ice cream and then we have to just get the cheapest ice creams until we can't get any more ice cream at the end so uh that's the solution we're going to implement all right so at first we're going to declare our variables which is just going to be uh maximum ice cream so let's just call it Max and we're going to start off as zero and our return statement is of course going to be the maximum ice cream here and like I said we're going to sort the cost of the ice cream I just need to use the normal scriptures you're not trying to be fancy here yes now I'll sorted the ice cream will just look at each of the ice creams and take the cheapest ones until we can't take them anymore Christmas I is less than Plus so I'm basically going to check in if costs are positioned I let's create that then points that's the amount of coins I have left we are going to return Max price otherwise if it isn't we're going to increase the value of marks because this will get by that particular ice cream and we're going to reduce uh the amount of points we have left and that is it that's the solution right there um let's actually run this and that's accepted and we submit and that's it uh that's our solution um all right guys don't forget to like And subscribe see you in the next one bye
|
Maximum Ice Cream Bars
|
find-the-highest-altitude
|
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108`
|
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
|
Array,Prefix Sum
|
Easy
| null |
188 |
Hello hello guys welcome back to test know this video also see the best time to buy and sell staff or problem which is best on memorization and state machine and how this process will be dynamic programming as display and all the three other video subscribe comment we video Song Topic For The Center Of The Problem Say Egg Subscribe Designer Maximum Complete Transactions The Solution Have Drawn The Graph Representation For All The Six Days This Is For Justice In Girls Talk On Different Issues Notice To Boy death minimum and salad's maximum set already explained in the previous videos will be coming let request oo to make transactions but you can listen transactions in order to get maximum you can see only will get the maximum subscribe and subscribe the channel subscribe karna without a very important Wear For The First Day They Cannot Sell Records They Have Not Be Stopped When Will Not Be Flagged Off This Will Not Be 10 Top 10 Inch Width Profit 800 to 900 Problem Solved subscribe the video then subscribe to the page if you liked the video then subscribe to subscribe our Representing The Bullet Lines The First Color Will Be Showing Gift Red Green Video Lineman Switch Toe Desktop Software Desktop subscribe our channel subscribe the video then subscribe to the page if you liked the video then sleep soon is this body Slim date will be maintaining a free state is the first is the number of transactions second stage where they have to talk or not and thoughts of birthday number for top 10 okay so just by using three dimensional debatable wikinews memorization in order to avoid using dynamic programming And they can apply reaction beautification approach will be taking off from various problems subscribe the video then subscribe to the page if you liked the video then subscribe to quite don't have any stock in hand din wicket keeping this in every day operation And Will Still Be In The State Will Not Talking And Avoid Talking Talk Subscribe Thank You All The Subscribe Otherwise One Day They Will Not Stop This Is The Pollution And Representation Of The Year 2nd Year In Which Will Be In The Most Obscure Subscribe She Will Go To Not Stopped And Fear In Both State And Give Top 10 And Will Continue To Be In The Best State For The Romantic Representation is the page if you liked the video then subscribe to the amazing She Will Not Behaving In Talking In Which Will Be Very Basic Knowledge Servi Question Vighn Maximum Total Number of Yourself Thank You to Take and Different Way in Different States of Ajay Bhai in Celebs Different States in Will Be Having a Maximum of Two States and the State Can Be Represented Something Like This Initially E Will Not Having Any Threat Looms Indicating The Bank And Airlines Will Be Settings Stock Here Subscribe Now To The Times Will Not Distract To Cigarette Thursday Not Talking And Will Continue To Do Not Talk And Will Continue To Decide To Maximum Number Jobs In Care Number Of Sales Rate Forms Will Be Having To Number And States And Obviously They Can Not For Multiple By Multiple Say Together Because The Question Is That Different Singers Who Can Celebrate Again Buy And Sell Okay Pure Combination Guys Like Buy And Sell No One Thing To Note This Transaction Only And Not The Amazing Will Cost You Cannot Endure Transaction Maximum Profit Will Win You Have Any Transaction Towards Stock Want To Make Profit Subscribe Will Always Be Stopping The Worst Position Which Is The State Of The World In Solving Problems Subscribe That Value Of Ladies 09 So And Profit Absolutely 2010 Buy Or Sell Latest This Just Having A Stock Price For A Single Day And For Will Not Be Amazed At Midnight Children And All In Notification This Post No Profit 0021 Profit Will Be Coming To Subscribe To Know And To Evolve A Stop on Nov 20, 2013 Gand a constructive and even after doing so will be having 100 subscribe thank you can only be made for increasing and decreasing will never be consider this point subscribe so 10 and will always be within increasing to be ok so will simply by adding this increasing values And Will Be Returning Details Maximum Profit For This Is To 9 Will Be Moving To General Questions Solved Stree Comes When A Boy Born Into A Sanam Saunf This Problem Minimum Profit Will Always Be Because Of All The Best Selling Your Profit 0 No Profit No Loss In The profit can go to you will be with you have to invest in order to invest these days quote will have some cost and show your current balance will go from zero to all negative this song by negative energies possible but once a linguist cannot get values 1008 a linguist cannot get values 1008 a linguist cannot get values 1008 Sri Aurobindo's Transactions Will Not Be Able To Remember All The Maximum Profit And Utilized To Solve This Problem 200 Transactions Will Again Be Falling Ok So Wherever I Have A Number Production Will Be And Will Be Display Industry 109th Minimum Volume Which Will Launch 10000 League Subscribe and Subscribe the Channel Soon How Can They Decide What is the Maximum profit well wishes for state day thursday thing and for this they will stop this is the name of the state will subscribe half the values from latest but transaction half the values from latest but transaction half the values from latest but transaction number different from which is the state of the states fennel but absolutely maximum profit on the previous state And Will Almost The Price Of The Talk With A Person Will Be Spending Money The Nov 09 2012 Option Without Doing Any Thing Subscribe Don't Want To See The Maximum Profit From The Best Middling The Price Of The Best Selling They Give Them Will Take Money From setting on subscribe the amazing growth rate is the reason behind I hope you understand this high level approach now let's move to the next point Note Next point is how to solve this problem Secretary Veer Maximum Number of Solving Problems Maximum Profit With only the first day understanding calculated to give you will find that on twitter and elements in the times when will I am ft Wizkid Davido first solving problems dig at a problem ok and they also using values from the ok and they also using values from the ok and they also using values from the previous problem enough to for the solution For The Problem Subscribe Programming For Operations For All Elements For Widening Of Complexity Of Solving Problems Subscribe Now To The Number To Cash Withdraw From The First Elements Of This Post Element Iron Land Will Start Getting For All After this eliminates all the states will all the states and first goal is to find the maximum profit affair given in just single day stock price Nov 10 2012 options and width maximum friends now school units of money in order to get the maximum minimum - - 999 minimum - - 999 minimum - - 999 Quite want to say 10 top ok din what will be the maximum profit it well being after but absolutely maximum profit from the best which is the biggest plus from this ling 10 top 10 000 will be getting a unit subscribe minus plus 3000 will not be replaced with Know it is the meaning of this Subscribe and Subscribe Minimum - The Topic Subscribe Minimum - The Topic Subscribe Minimum - The Topic Savitri 100 200 - 3 Celsius Pendant Three Savitri 100 200 - 3 Celsius Pendant Three Savitri 100 200 - 3 Celsius Pendant Three Idiots Nor Will Want To Next And Selling Not Want To Say 10 Top 10 Best Absolute Maximum Profit And Loss The - with Best Absolute Maximum Profit And Loss The - with Best Absolute Maximum Profit And Loss The - with the prize on road subscribe this all the video then subscribe to the page if you liked the video then subscribe to the page this is what body returns is different case because they know no previous value and respect 0208 will always be positive vaseline 09 2012 by Becoming President Profit Is - - - - - - - - by Becoming President Profit Is - - - - - - - - by Becoming President Profit Is - - - - - - - - - No Way To Celebrate This Day - No Way To Celebrate This Day - No Way To Celebrate This Day Is To Salary Stock Price To The West Macrame Profit Plus Minus To Will Reduce Price To Minus Plus 2012 This Is The Meaning Of The Name Of The State Will Subscribe - 2 - - - - Name Of The State Will Subscribe - 2 - - - - Name Of The State Will Subscribe - 2 - - - - the video then subscribe to my plus 2009 all transactions for the element subscribe buddh third a stark poverty price will again be moving from the first profit - the video then subscribe to profit - the video then subscribe to profit - the video then subscribe to the page if you liked the video then subscribe to my 449 again will be doing this for this is the will be for - 6 witch will be - 2nd place - 6 witch will be - 2nd place - 6 witch will be - 2nd place and values - too so much we will not change that and values - too so much we will not change that and values - too so much we will not change that no one will move to the last impression is the last again if you want to say letter this is the what is the name of the state minus plus subscribe 04 will be replaced subscribe the video then subscribe to the page if you liked the video then subscribe to the page Previous Day Witch - to the plus white sesame Previous Day Witch - to the plus white sesame Previous Day Witch - to the plus white sesame exactly 400 representative Will not benefit the video then subscribe to the page 404 - - Verb - Subscribe - 1212 subscribe the channel please subscribe this all the amazing Subscribe 0 Share Baingan Bisht 11000 - 200 Will Be Share Baingan Bisht 11000 - 200 Will Be Share Baingan Bisht 11000 - 200 Will Be Replaced Maxim-2012 2009 2013 Replaced Maxim-2012 2009 2013 Replaced Maxim-2012 2009 2013 subscribe the video then subscribe to the page if you liked the video then subscribe to the amazing profit 406 409 plus gift friday is latest no process par last phanda liye if you want to buy abs price rs.4374 setting on the guardian price rs.4374 setting on the guardian price rs.4374 setting on the guardian subscribe to the page if you liked the video then subscribe to the page if you liked the anil remedy for and difficult business profit suvichar net profit in the previous day which is point plus price under current specific 310 welcome to that 700 versus operation Thursday transactions for every element sagus president absolute blue souvenir waiting For all elements in the city will not go into which element subscribe and subscribe the amazing will not be able to understand but went and size number transactions increased to 10 complexity will be and of ok I hope you are able to understand as to locate The Self Explanatory Memorization Middle The Video Share The Only Subscribe No This is the code which has different This is the first approach in this approach will take the number of international prize subscribe's own obstacle will always be known as one to three will be the opposite of the subscribe total number of states into feeling center table do vikas the number this channel behaving in Terminal of Baroda too difficult to get values will celebrate and minimum 50 mit can go to the way will be coming values will celebrate and minimum 50 mit can go to the way will be coming values will celebrate and minimum 50 mit can go to the way will be coming into operation for every day at this point and subscribe operation was doing so will be very simple to understand and subscribe button this is the simple Code to Understand But He Defeated Logic to Actually Come Up with Rock Solid State Machine and Mr. Not Very Intuitive Who Saw a Few Verses and Solution in Different Languages Subscribe Like Share and Subscribe
|
Best Time to Buy and Sell Stock IV
|
best-time-to-buy-and-sell-stock-iv
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`.
Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times.
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** k = 2, prices = \[2,4,1\]
**Output:** 2
**Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
**Example 2:**
**Input:** k = 2, prices = \[3,2,6,5,0,3\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
**Constraints:**
* `1 <= k <= 100`
* `1 <= prices.length <= 1000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Hard
|
121,122,123
|
382 |
Hello everyone, welcome to my channel, but if you understand then it will not seem like a medium, it will seem easy, okay, we will make it with two approaches, Google asked this question and what is the input, okay, so we have given you a link, get random function, we will do that tomorrow. So you have to send a random note, it is okay, either one is one, you are three, but the probability of selecting any note is okay, then like mother takes it The first approach that comes in our mother is like I had made it, I have given the link to the link, I will size it, okay and I already know that there is a function called rand that if someone will generate a random number and give it, then what will I do, if I am taking three then I will get either zero. Either you will get one or you will get neither. Do you know this? In mathematics, it is a mathematical thing that if you take any number as a modal from something, then it is okay, just like we take mother from the modal with x. Lately, what answer can I get? Can I get numbers from zero to one or up to I can get it and the same index is my zero one, you are the one, so whatever random index I get, I will return the number with that index. Okay, so the code will also be very simple. Right, I will take a rand number, first of all, one. I will store all the link list, okay one, three, whatever was the number of the link, I stored it in it, then I came to know the size, took out the run percentage tile took out the size, took out the run percentage tile three, I got an index named X, either zero or So I said either you will get it then what will I return? Return is off date index, it will just be in off one, right? We have stored the link in, after traveling through it, off N is placed there and why is there a guarantee that my answer is correct. Will give because the function named Rand generates different numbers with equal and probability. It generates random numbers. It is not that any number is allowed. Look at the priority. It is returning okay. If it is 0 then it is one. So you will be equal to everyone, you will get the same, you don't have to take tension, our rand will reduce it, okay, so let's code it, after that we will come to the other approach, okay, so let's code it, which I have just told is a very simple approach. I will enter the numbers, okay, it will be known, random index, okay, it was simple, let's run it and see, now we come to our second approach. Okay, so now we will see the approach. We will make brooches from reserve sampling. We must have seen in the forest, we had taken one off space, right, we do n't want that, okay problem, okay you from so many n samples, you have to pick up the samples from n samples and file them on your reservoir, this is the reservoir and we will pick up the reservation and put it here. Neither should it happen with probability of all and it is said in the question also that it should happen with probability of all, so the probability is with which you choose the number, what is written, what is linked list, it is called extremely big and D. Length is unknown. If you look at it is hinting towards reservoir sampling. You may not have heard of it before. There is no problem, but reservoir sampling says that there should be a very big number, there should be a very big list. You have some of them. You have to select the number with equal, this is a very big sample, out of it you have to select k number of samples, so in this question, k = 1 is given, question, k = 1 is given, question, k = 1 is given, what is given in the question, remember that you have to return a number. Na get random, when it happens tomorrow, only one return has to be made, one random number, only one, so our i.e. random number, only one, so our i.e. random number, only one, so our i.e. reservation elements are asked to be filled, so we filled them in the game, okay, now when they have been selected, then it is obvious that equal property is now next. Which is plus one element, okay and we will replace it, okay, we will pick a random number from here, okay, lastly, okay, I am removing it, look, now I will write one thing here, pay attention to the probability that it will be selected, okay Note that this Ok, I am thinking of taking out some guy who is an ex, he should remain in the reservoir, his property should be taken out, he should remain in the reservoir, his body should be taken out, then two things, now it is also in the reservoir, which means I must have put him in the reserve sometime before. Okay, and one more thing that has to be seen that it does not get replaced, if it is the elements having K + I, not get replaced, if it is the elements having K + I, not get replaced, if it is the elements having K + I, then it is the product of the properties of both, from which property was the element being picked in probability for Chunni, because one, it is from earlier. Isn't it then k plus i now there are elements, I am talking about it k plus i minus one when this would have been there or from the sample and then there would have been plus i minus one elements then what would be its property k Brother, what is the plus sign of minus one? What is multiplying? What is the probability of which If I select the element with I, do you remember its property? I wrote K / K + I here. Here's who it is wrote K / K + I here. Here's who it is replacing. If it is replacing Will replace means heal Lo Ki and K will be cut here, okay, so see, this probability is also from, so if similarly, this was the K plus I element now, then later on, more helmets will come that K + I + 1 K + I + more helmets will come that K + I + 1 K + I + more helmets will come that K + I + 1 K + I + 2 Similarly when there are n elements then what will happen priority will be k by n Okay and remember in our case what is the value of probability meaning k then the property becomes one by n and what will be the probability of all the elements 1/n Right, because the value of our k 1/n Right, because the value of our k 1/n Right, because the value of our k is one, so you are seeing the priority of picking all the elements. I also picked the priority of this element, which is the The priority of picking an element is that it is okay to pick up an element and then what I said is that the probability of any element remaining in the reservoir is also there, I saw what I have removed, I have taken out that by K+I. What does this removed, I have taken out that by K+I. What does this removed, I have taken out that by K+I. What does this mean? Do you know that after picking any element, that too is only a sample and if any element is left in the reservoir, that too only in size, which I have just proofed here, okay, its meaning is clear from here only. That is, the probability that we have is absolutely correct, like we mean that all the elements are equally probable, the probability of all the elements being ticked and the probability of all the elements being replaced is equal to all the keys. Okay, so now let's see how we will solve it by coding it. So if you remember, I had calculated here that if any band If there are elements then it will be k by n. If there is one element then there will be two k by you. Three elements then k / 3 then this is 123. So we will take counter = 1 in the code. Okay and we will k / 3 then this is 123. So we will take counter = 1 in the code. Okay and we will keep incrementing it and what is the value of k in our how to be. Only then it will remain in Banda Reservoir. If the value gets reduced due to this, that means whatever probability you get, that is, whatever random number you are getting and after modeling and counting, the random number will come out like this. If it becomes random, then it means that this monkey should be replaced. Will it go or replace it and if it is equal to this then Banda will remain because remember what I said when I calculated the probability, this Banda will remain in reserve, its probability is that By K plus I will not remain, meaning if it gets reduced from this. Probability of this, our code will also be very simple that in the beginning we will start with account equal to one because we have only one note till now and starting from now means till then I will keep adding one element in my reservoir, okay then and I Every time I will keep checking that whatever random number I am drawing, modulo the account that I have, if it is done then it means that I will have to replace whatever my result is, I will have to update it, replace it, kiss it. Whatever is the current value, replace it with the value of my time. Okay, and if it is not so, then it is okay. We will keep adding plus to the account. New element will keep getting added and the tempo will keep going forward So let's court this also. In this way, to point our head in a global variable, let's create a new variable and sign it here, whatever my link list will appear because the elements are being added one by one, okay, the same happens in reservoir sampling, right? There is one element in the beginning and then later on the elements will increase in this result. What is going to happen to me? I will store the result in this and in the beginning I will keep a value named temp which will be pointing to the head. Okay, now people go exactly the same time when Until we reach the tap, meaning in English, till we reach the tap, we will draw a random number from the account. If we take that value, what is its value? If it is equal to that, we should have the probability of going to tap. If it is less than that, then it is obvious. The simple thing is that the dates will be replaced, they will replace the result from this current value and if this does not happen, then the account will keep on increasing, one by one the elements are getting added and the time will also move ahead. Get out of this loop bill have d answer in result variable ok random account let si level d pass which date is cases ok I think they need tu pat 1.0 so that the floating point is not wrong our let si submit this and see also Thank you
|
Linked List Random Node
|
linked-list-random-node
|
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
| null |
Linked List,Math,Reservoir Sampling,Randomized
|
Medium
|
398
|
503 |
hello everyone this is my next video today I am going to explain the code question number 503 next greater element 2. given and circular integer array Norms the next element of nums dot length minus 1 is nums of zero return that next the greater number for every element in numbers the next greater number of numbers X to Greater number to its traversing order next in the array which means you could set circularly to find the next integer number greater number if it doesn't exist written minus 1 for this number array we need to find the which is the greatest number next to it okay if it is not found we need to approach by using circular array okay if the element which is the greatest that element we are returning is minus 1 throughout the array okay I'll see in the example you can observe in numbers one two one and the output is 2 minus 1 2 how means see the first index which is the next element greater 2 yeah we are written two If You observe the circularly the two number two is only the is number so we are returning this minus one so if you take a second index it is we're returning two of a circular is representing we are getting again two which is the greatest number we are getting two in example 2 1 2 3 4 3 and it is represented as 2 3 4 minus 1 4 you can briefly understand in the Whiteboard see in the example one what they given they're given one two one okay and output is written in 2 minus one two see how means just one two one which is the greatest element in this we are approaching from left to right okay 2 is highest in this one two after circular approaching the two is only the highest which is represented as minus one see one if you approach it by circularly we are getting two as in example 2 1 2 3 4 3 which is the greatest element if you're approaching from left to right means to proper to three four three third element for four if your approaching circularly also we are getting four so we are alternating minus one for three greatest element is okay this is the approach by using two pointers we can write the logic I and J I will be pointing the first index and J will be pointing to the I plus one okay we will Traverse up to the N minus one element J will also travels up to n minus one element what we are doing we are checking our current uh J to the uh to the array of I which is greater than next of I means the greatest element of I we are writing the array of I but what is happening in this logic will take the time complexity peak of n Square okay we will need to do this is very better optimal Solution by using the stack okay that I will in show now that is a data structure okay follows leave for order so in first out which we are inserted last that we are picking out the first see for one two one if we are inserting one just we are popping out this one that is the last in first out okay by using the stack implementation we can write the log see one two one if we inserted this one starting one will be inserted we will see two is greater it will uh it will follow increasing order okay two if you are doing this just we are popping out one we are in setting two okay which is the greatest element will be here next to the same element means what we will do we are returning -1 what we will do we are returning -1 what we will do we are returning -1 which is the greatest element here 2 okay we are written in 2 minus 1 2 this is by using stack approach if we are see the coding then we can understand proper okay first I take on one variable and I stored nums either in the N variable after that I declared Vector if it is a integer type with the name we see for all the N elements I am storing the minus one initially okay after that we created stack because we using stack implementation last and passed out here we taken variable F the given n an element where taking from 2 N minus 1 we are traveling from last index to the first index okay after that we are checking the condition uh the stack is not it should be not empty and if there is a top element means then we will check the condition it should be less than or equal to nums i modulo n if this is satisfied we are popping the top element okay after that we are checking the condition I should be less than n then this statement will be executed okay then we are entering into the if condition we will check the stack should be not empty if it is not empty means what we are doing we are storing a stop in Vector of I after completion of this iterating all the elements finally we are written a vector okay uh for every uh condition checking after we are pushing the stack okay this is the code of the by using tank implementation if we add the iron code milk then proper will understand okay let's we can try run this code let's dry run the first example one two one these are index 0 1 2 okay here n is 3.3 elements starting we declare the all 3.3 elements starting we declare the all 3.3 elements starting we declare the all cellular minus 1. okay here I will starts from last index it will travel up to the zeroth index here our I will start from here two three six minus one five I will start from fifth index it will travels up to the root element okay see now we are checking it is empty or not starting it is empty there will be no top elements okay so we will not execute this function okay now we are checking the condition here I is 5 less than 3. okay this condition is false so we will not enter into inside it just we are pushing nums here I is Pi modulo n is three okay and now a pi modulo 3 will become 2 your nums two value is one just we are pushing in the stack one now I is decremented to four now we are checking the condition 4 is greater than or equals to 0 yeah it is not empty and the top is one the one should be less than or equals to this number I is here four okay four modulo three is one nouns one we need to say here nums one is two one is less than or equals to two yeah this condition is two just you are popping this one now we are checking the condition here I is this condition is false so we are not entering the inside just we are pushing uh four modulo three yeah we are getting one nums one is two now I is decremented to three is greater than or equals to zero yeah this condition is true so we are entering the while loop by Loop it is not empty and the top element is 2 2A is less than or equals to nouns here I is 3 modulo three modulo 3 0 numbers of zero is one two is less than or equals to one yeah this condition is false so we are not popping anything so okay now we are checking the condition yeah the I is 3 Less Than 3 this condition is false we are not entering into the inside if we are just pushy I modulo and we are pushing nouns of zero nums of zero one we are pushing one now our I value will be decremented to 2 is greater than or equals to zero yeah this condition is true now we are second yeah this is not empty our top element is one it should be less than or equal to nums where I is 2 modulo 3. one is less than or equals to one yeah this condition is two we are popping this one now is our stack as only two now checking the condition your I is 2 less than three yeah its condition is true yeah stack is not empty now what we are doing we are storing v c here I is 2 of top our top is two now this will be boom now our I is decremented to one is greater than or equals to zero okay uh yeah it is not empty our top element is 2 we should be less than or equals to pair nouns uh where I is 1 modulo three is nums one here nums one is two so we are popping this two okay now stack is empty now checking the condition here I is 1 less than three yeah this condition is true so we are entering into inside if yeah your stack is empty if it is empty means what we are doing we are returning minus one okay after that we are pushing nums of and I is 1 modulo 3 is nums one contains two okay now our stack is 2. now I is decremented to zero is greater than or equals to zero yeah this condition is true so now we are checking this is not empty our top is 2 is less than or equals to nums of 0 module foreign it is two if we got 2 minus 1 2 okay now we can run the code next you can understand the time complexity and space complexity of this Logic the time complexity is taking weak of n overall it is taking we go of 2N where 2N is where 2 is constant so it is taking time of week of n okay comes to the space complexity taking big of n because we are using stack it will stores n space so it is taking a space of P cos n thank you guys for watching my video
|
Next Greater Element II
|
next-greater-element-ii
|
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`.
The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[2,-1,2\]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.
**Example 2:**
**Input:** nums = \[1,2,3,4,3\]
**Output:** \[2,3,4,-1,4\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Stack,Monotonic Stack
|
Medium
|
496,556
|
201 |
hello guys today we're going to solve this L Cod question which is with wise and of numbers range and in this question we are given two integers left and right that represent the range between left and right written the between and of all the numbers in this range both this left and right are inclusive you know it is fairly uh easy problem statement to understand we're just basically giv a left and right and we just need to return the bitwise and of all the numbers between this range suppose if we are given one and five we just need to return one with twice and two and three and four and five so you might think uh you know this question is very easy right but is marked as medium so there might be something that they will be twisting right so that something is nothing but the constraints if you look at the constraint here so look at the time look at the constraints you know the left value can sorry the left value can be zero the right value can be 2^ 31 - 1 which is right value can be 2^ 31 - 1 which is right value can be 2^ 31 - 1 which is mostly equal to this thing you know if you start the loop from zero and go till 2^ 31 minus 1 you know uh this go till 2^ 31 minus 1 you know uh this go till 2^ 31 minus 1 you know uh this will be the number of times you will be iterating right but the maximum limit that we can iterate is 10 Power 8 you know this is the maximum time limit these are the number of instructions that can be executed in 1 second you know basically in the coding questions we basically given 1 second to execute our code right so in that one second we can execute a maximum of 10 Power 8 instructions but here in the worst case you know the left will be zero and the right will be 2 31 - 1 right so which will which is 21 2 31 - 1 right so which will which is 21 2 31 - 1 right so which will which is 21 times greater than the maximum time limit so you know if you use this approach like going from left to the right and doing bitwise on of each and every value the you'll get a tle right you'll get a time limit exceeded so this approach won't work so we need to think of a another approach uh so that we can solve this question in a more efficient way so before that you know we need to understand the uh okay we need to understand the property of and you know so uh suppose we have zero and one you know when we have when we do and it will be zero right and when we have one zero it will be zero again when we have one then only it will be one and when we have 0 it will again be zero right so when we only have one and one then only the bitwise and will be one right so using this property we can uh you know solve this question in a more efficient way like when we when you are going from left to right at particular point if you identify that your uh bit hand is zero there's no point in going this side right because the bitwise UN value till here is zero and even if you do un with these values it will be zero again suppose you know I'll give you an example like suppose you have one0 0 1 z0 1 0 If You observe carefully when you do bitwise un between these two values it will be zero here also it's zero right so after doing the bitwise and of these two values even though if you do bitwise and of these two values it will be zero again right so there's no point in doing uh bit un for each and every value once our bitwise and becomes zero then we can stop right suppose here our value is 0 Z and when we did bitwise and with this value our value has become zero so there's no point in doing bitwise and with these two values and you know no matter if there are some thousand values as well we if we encounter zero in between we at the end the answer will always be zero so this is what one of the optimization that we can make and uh that's it uh the first idea uh and uh that's it uh the first idea that came to my mind when I saw this question is that you know I know that you know if I have any zero uh suppose if I have you know there is a number called 11 1 and there are so many numbers in between there are so many ones let's say there are all ones each and every value is one and I encountered zero at here and all the remaining numbers are one itself when I encounter zero in a particular column then all the then no matter how many ones are there in that particular column my result will always be zero right so this will be 1 one it will remain same but the column which has zero will have zero at the end suppose if there is a zero here then there will definitely be zero here right so using this idea what I what uh what I thought was you know oh never mind uh you think de idea what I thought was initially I'll take 32 ones 2 3 4 5 6 7 8 9 so on 32 1es this will be my uh let's say some n this will be my n and you know initially I'll start from left and I'll go to the right and I go till right uh suppose my left value is and my right value is 20 so for 16 you know the last four digits will be 1 2 3 4 right so all these values will be zero itself 0 this all will be zero and for 20 the bitway will be 1 0 16 8 20 and0 0 right and all the values behind these values will be zero right so what I'll do is you know I'll start from left and I'll do normal bitwise and operations and you know and when whenever I see all my values will become zero then I'll just return zero otherwise I'll keep on doing the and operation so this is the idea that I got into my mind so let me explain this example using a small group of digits suppose if I have five ones let's say this is the n that I told you about suppose my left is 16 1 0 16 right 1 0 and I'll go till my right so my right will be 1 0 right so what I'll do is I'll do end of these two will become 0 and one right then I'll do then there will be l+ 1 right L + 1 will be 1 0 1 be l+ 1 right L + 1 will be 1 0 1 be l+ 1 right L + 1 will be 1 0 1 so I'll again do the UN between these two values then I'll again get the this value right so uh this is not a good example so I wrote a better example here so suppose my left is one and my right is six right so what I'll do is I'll take a n value which has all bits as ones so what I do is I'll do the bitwise and between these two then the answer will be 0 one right these three bits will become zero and this will be one and then I'll again do bitwise and between these two then it will become 0 1 0 if I do bitwise on between these two it will be 0 right so at this point I got a zero right then there is no point in doing bwise and with all these values right suppose the uh let's say the r will be 6 laks if it is a six lakhs there's no point in doing for all the values till six lakhs right so if I get a zero I'll just return zero I'll just zero so this is the approach that I got into my mind so I'll quickly show the code and will be integer Dot max value this n contains all ones that's why we took integer do max value so what I'll do is while yeah while my n is not equals to zero I'll do n un equals to left on the left Plus+ I'll left on the left Plus+ I'll left on the left Plus+ I'll go oh I can also do something like this right what I can do is I take a i equals to left and my I goes till right you'll increment my I if at any point my n becomes zero I just return zero or at the end I'll just return the value of my n right if I run this time limit exceeded this is because you know I'm taking this test case I know that this approach will fail for that particular D case but it will get accepted for most of the test cases I guess only one or two test cases will fail using this approach look at this um we have passed 8,266 this cases out of 69 so only three 8,266 this cases out of 69 so only three 8,266 this cases out of 69 so only three D cases are getting you know failed so we can also solve this by using long I can just use long here let's try the Sol I just need to return the in value right the WR type is in right so I need to WR name I submit now only one or two dis my God okay never mind I don't know uh so we uh for these test cases you know our code will never run with using this approach so we need to find a more efficient way the efficient way will be you know you observe carefully suppose if I have 16 and suppose if I have 32 for 16 it will be 1 0 Z right and for 32 uh it will be 5 zos 1 2 3 4 5 so till 31 so the value of 31 will be 1 one 1 right so between this all the values you know these four bits might change right these or bits might change but this one and this one will remain same right this one and this one will remain same uh then let's say this is your left and this is uh this is your right so if you even if you do un between all these values you'll be left with this one right but all these values will be zeros because you know this one has never changed in between you'll have the same one for all the values in between right so uh and if you take your left as let's say if you take your left as 1 2 3 31 32 5 and your right is you know 6 this is 32 right this is 60 this should be 63 you have something like this one will never change in between right all these values may change but this one will never change right so because of this one you'll be having one here and no you know all these values will be zeros so what we can do is we can just identify the common elements from the left suppose if you have something like 1 0 1 and for your right if you have something like 1 0 no matter uh what elements uh you have in the middle you know let's say these three values are same for all the values this will become zero right 1 and Z will be zero 0 and 1 will be Z 1 and0 will be zero so these values are same right so we'll get one z so we just need to identify the common bits between the left and the right starting from the left so if we identify these values we can put the rest of the values as zeros because these values will are changing right when the bits change the value will become zero right we just need to identify the common values uh let's take an example I have something like 1 0 this is my left I have my right as 1 0 suppose if I have something like this will become zero this will in between this will change right from in between left and right this one will definitely will there will be one element which has zero at this position so this will also be zero this will also be Z this will also be zero but these three will remain intact right in between these three there cannot be zeros right there cannot be zeros in the sense we're assuming that all these elements will have one here we're just assuming that at this point you know we are having 11 one here and we can fill these values with zeros so we just need to identify how many bits are same in left and right starting from the left and how can we do that means initially our left is 1 0 right so what I do on my right is 1 0 I'll check whether my left and right are equal or not these two are not equal right because the bits are getting Chang so I left I'll right shift our bits by one position so these two values will be removed and we'll get zero and zero here right so I'll again check the are these two values are same or not because of these bits they are not same so I'll remove these two again and we'll get Zer and zero at the left right again I'll check the left and right are equal or not they are not equal because of we have zero here one here zero here so I'll remove these two and again I'll remove this two after removing these all elements you know we'll have three bits which are equal right so this value will be seven this will value is also 7even right so at the end we'll have 1 one and we just need to put zeros at this position how can we say how can we put zeros at this position we can just count the number of bits we have right shifted and we can left shift the answer with those number of bits we have right shifted with 1 2 3 4 5 right so we can left shift with five bits to get the answer so what is the time complexity means okay the time complexity is order of login right or we can also say that it is order of 32 since we are just doing right shift of a maximum of 32 bits and a maximum of 3 32 bits of left shift right so it will be order of 32 plus order of 32 it can then be order of 64 which will be order of one right so our time complexity is order of one and our space complexity is also order of one so let's see how are we going to do that I'll just use a while loop while my left is not equals to right I'll just right shift my left with one potion and I'll right shft my right with one position when in the meantime I'll keep track of the count of number of bits that I have right Shi count plus equal to and at the end I'll just return my left or right by left Shifting the number of bits right that's it run this yeah look at these yeah it's running fine guys I know it's real uh I know I haven't explained it very well but it's a difficult problem to explain thank you guys for watching the video and if you find the video useful and you know if you understand the topic that I have t just give a like thank you
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
966 |
welcome to march's leeco challenge today's problem is vowel spell checker given this word list we want to implement a spell checker that converts a query word into a correct word for a given query word the spell checker handles two categories of spelling mistakes capitalization if the query matches a word in the word list case insensitive then the query word is returned with the same case as the case in the word list so for instance if we had the word yellow and we want to see if we could just lowercase everything and that's going to be in the word list we're going to return the first word that matches so this is going to be yellow here now vowel errors if after replacing the vowels a e i o u of the query word with any in the vowel individually it matches a word in the word list case insensitive then the query word is returned with the same case as the match in the word list so if we had the query word yolo right here we could replace o with e and o with a capital o and we should return the first word that appears here it's going to be yellow with this kind of weird capitalization here all right so in addition the spell checker operates under the following precedent rules and this is important if the query matches the word exactly we should return the same word back okay so that's easy when the query matches a word up to capitalization so case sense case insensitive then you should return the first such match in the word list same thing with the vowel errors you should return the first such match if none of those matches then we just return an empty string so we're given a word list a list of queries of words and then we're going to return output of list with the correct word returned all right so the logic to this problem is not that difficult it's just very annoying and cumbersome to write but let's begin by thinking about what data structures we need to be able to accomplish this remember that we have to return the first word so that at first makes you think we should do it inside of a loop but that's not necessarily the case if we just had a hash and created the key to be the lower case like for instance here we should just match the very first word inside of our word list to be the value and we can just skip anything else that matches the same key because we don't care about anything second we only care about the first word that matches uh whatever whether it's capitalization or whether it's these foul errors uh so let's go with a couple hashes here and then we'll iterate down our query list and try to match uh inside of our hashes if we can't match anything then we'll just return empty list all right so the i think the hardest part here is creating some sort of logic for the vowels but let's begin by creating a couple hash maps the first thing i'll have is uh word list i'll call it pure and this is just a direct match right so we'll just make this a set of the word list the second thing is for case what we'll do is lowercase everything and make the very first match be the value for that key okay and we'll do the same thing with the vowels with vowels though i'm going to have to create a helper method to help out here but let's start by populating our word case wordless case so for w in word list let's lower keys everything and say if w dot lower not in our word list case then we'll say word list case w dot lower is going to be equal to that word now you can imagine that there's going to be other words that match here but we're going to skip those if we already have the key inside of here so we'll only get that first value now for the vowels we got to do the same thing but we need to create some sort of way to replace all the vowels with some sort of replacement character so what i'll do is create a helper function this is gonna accept a word and i'll have to have some sort of look up for the vowels i'll say a e i o u uh remember that this is also case insensitive so what we'll do then let's say for w in word and make that lower we'll say if w i actually call it c say if c character in vowels then what i'll do is i'm going to create a temp list here and say okay just add to our temp list let's say the star character now otherwise we will append to our temp list the actual character and at the very end we'll return a string join with this temp list okay so now we're going to populate our word list vowel and what we'll do is it's very similar but we'll just have to call this helper function call our help function for the word and if that's not inside word list vowel we will populate it with vowel and call our helper function again like this all right so now we have all the data that we need now it's just a matter of iterating down our queries so for q in queries remember that there's four match um four cases here and also to create an output list okay so there's four cases right there's the exact match there is the case there's the vowels and then there's nothing so the first match if q is in word list pure then let's just append to our output the word q and that's it now else if q dot lower is in word list case then we will output append to our output from our word list case dictionary q.lower here remember this is going to q.lower here remember this is going to q.lower here remember this is going to add that first one that we talked about before now vowels else if we will call our help function helper q um in word list vowel we'll do the same thing but we'll also call our helper function instead of this floor q uh let's make some typos here and finally if we weren't able to find anything then let's just append to our output an empty string okay so let's see here if i got everything i believe we did so let's return our output and this should work let's see if i missed anything all right so kite looks like it's working so let's go and submit that so there we go accepted um so as you can see the logic to this problem isn't that complex it's just very annoying to write um and i suppose the biggest difficulty here is writing this helper function now what is this in terms of time complexity i believe it's going to be well i believe it's going to be of n times the length but that's going to be only a length of 7 here so i guess it's seven times n so overall it's going to be o of n time complexity and of n space complexity okay all right hope that helps uh thanks for watching my channel and remember do not trust me i know nothing
|
Vowel Spellchecker
|
binary-subarrays-with-sum
|
Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters.
| null |
Array,Hash Table,Sliding Window,Prefix Sum
|
Medium
| null |
35 |
in this video we'll go over lead code question number 35 search insert position given a sorted array of distinct integers called nums and a Target value we have to return the index of the Target in the array if it doesn't exist then we'll have to return the index that it would be at if it were inserted in order now there's one other major restriction our algorithm must run in over log end time that makes things difficult because now we can't just Traverse the array one by one until we find the target if the length of the array is n then in the worst case we'd have to look at n elements so the algorithm runs in O of n time instead we can take advantage of the fact that the array is sorted and use binary search here's a quick overview if you're unfamiliar in binary search we maintain two endpoints that start at the beginning and the end of the array at each step we calculate the midpoint of the two endpoints and compare the target with the midpoint element here three things can happen if the midpoint element is equal to the Target then we're done and we can just return the midpoint index if the midpoint element is less than the target then since the array is sorted we know that the target has to be to the right of the midpoint so we'll update the left bound to be one element past the midpoint lastly if the midpoint element is greater than the target then by the same logic we know that the target has to be to the left of the midpoint so we'll update the right bound to be one element before the midpoint then we'll keep repeating this until we either find the Target or if the target doesn't exist in the array then the two bounds will converge and eventually pass each other meaning that the target was not found with each iteration we eliminate around half of the array so now the question is how many iterations does it take to converge on the target well another way to think of it is how many times do we need to divide n by 2 until we reach one let's say k is the number of times we need to divide n by 2 to reach one then the equation is n over 2 to the K power equals one and we need to solve for K let's move 2 to the K power over to the right side and we can isolate K by using logarithms meaning that we can rearrange this to be log of n with a base of 2 equals K so now we know that it takes log base 2 of n steps to complete the algorithm but in Big O analysis we drop the base so we say that this algorithm runs in all of log n time now let's look at the code and see how we can do this in Python let's say this is the nums array and our Target is 7. first we'll establish the left and right endpoints so L will equal zero and R will be the length of the array minus one so five then we'll enter the loop which will continue running until the left and right endpoints Converge on a single number this condition here needs to be less than or equal to not just less than because all we know is that the target is somewhere between those two endpoints including the endpoints themselves so if they're equal to each other we still need to do one last check to see if the element at that index is the target so first we will calculate the midpoint by taking the average of the endpoints and rounding down to get a whole number so zero plus five is five divided by 2 is 2.5 then rounded down is two so mid 2.5 then rounded down is two so mid 2.5 then rounded down is two so mid equals two then we'll compare the element at index 2 to the Target and figure out which one of the three scenarios we're in it's either less than the target greater than the Target or if neither of those are true then it must be equal to the Target so the element at index 2 is 4 Which is less than seven so we know that the target has to be to the right of the midpoint so we'll update L to be mid plus one so three since we know that the target is not at the midpoint and it must be to the right of it then we'll loop again three plus five is eight divided by two is four so mid is four the element at index four is seven and we see that we found the Target that means we enter the else block and just return four the index of seven and we're done but what happens if the element doesn't exist in the array let's try this again but this time we'll make the target three we'll start the same way by establishing the left and right bounds and calculating the mid index which is two then we compare four with a Target and we see that four is greater than three so we'll enter this e lift block and update R to be mid minus one so it's one next the new midpoint is zero plus one divided by two which is one half then rounded down is zero the element at index zero is one which is less than three so we'll update L to be zero plus one so one now notice that L is the same index as R but we still need a loop one more time because we haven't checked the element at index one yet which is two is less than three so we'll update L again but now L becomes one plus one which is two now when we check the loop condition 2 is greater than 1 so we know that we've checked everything and 3 doesn't exist in the array so now the question is at which index would 3 be at if it were inserted in sorted order you can see that the answer is just to return the left index L but let me explain why so if we're at this point where the left index is greater than the right index one of two things had to have happened the first possibility is that they converge on a single number and that number happened to be less than the target so the left pointer got moved up this is what happened in the example that we were just doing the second possibility is that they converge on a single number and that number happened to be greater than the target so the right pointer got moved down either way you can see that the left and right pointers end up in the same position where the target 3 should be inserted between the left and right pointers so which index do we insert 3 into well going back to our example if we inserted 3 at the right index so that it becomes the element at index one that's actually one space behind the correct spot so instead we insert it at the left index at index two and now we see that the 3 is in the correct spot so that's why here if the element is not found we can just return the left index L and we're done
|
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
|
659 |
hey what's up guys John here again actually I want to talk about this like problem number 659 one more time because I think in my in the previously videos we introduced like a very brilliant idea which is the o n time if you guys didn't know about that solutions you can check the other ones basically for the other solutions and that solutions we basically loop through this video look through this arrays and then for each of the numbers here we check if this number can be a can either be a previously can either be the add to the previously isolated a sub array or it can be a if we can then if it cannot then we try to start a new sub array from this current number now if none of those scenarios applies working that we simply return false you know that's some that's I idea fybel Eve for most people's not a lot of them at least for me I didn't come up is that problem that solutions so this time I'm gonna try to introduce like more intuitive ways but that instead of and instead of end time this one's gonna be and login okay so how does this solution work so basically we're gonna have like a dictionary right basically for each of the dictionary here we're gonna have a like an ends dictionary here and so ugly here and dictionary right and the key will be the number how about the value will be the list of length basically yeah the key will be the number and the value will be the least of length which ends at this number and every time when we see a new numbers right if this new number I'm sorry if the new number plus a minus one right if the new number minus one is inside this and dictionary then we know okay we can append the current number to one of the lens here right the one of the lens but which length right so that's what we will use the priority queue to store this lens this list of lands basically every time we always try to append the current number to the smallest length of the current of the updation minor num minus 1 that will make sure we try our best to make sure any of the lengths ending this number will be a greater or equal than three right and then in the end we just check we just loop through the end and all of this dictionary here if any of the lens in the sanam is more than three right then we know there it's not a valid it's not a very scenario okay so that's the basic idea basically and sub-array sorry and basically and sub-array sorry and basically and sub-array sorry and dictionary and the value will be the list of length but instead of using like a Dracula list which will be a n right so the number will be n right and then so when we loop through the number will be n and times what times the if it's a regular list and so the search of this list from for the minimum number small December will be another end but whether it's a priority queue we can improve this end to login right so then the total number will be a and login okay let's try to implement this and so we're gonna have like an end dictionary right so this one I'm gonna have a default right at least since the sorry default dictionary and the value will be the list right that's how we use the that how we need stores out all the length right okay and so now which loops through the numbers here right for num in numbers right so first we track right if this number minus 1 is in the noms right what do we do then so sorry let's turn if it's not in nums yeah to make it easy let's split the conditions here first if this if the current Nam cannot be append to any of the previously sub arrays right so that's one that's what this check if state if tried to write if the previous number is not any does not have any endings right then we do what we'd simply it to end dot Nam right that's app and yeah what is that pant actually know what so that's the let's see if it's not in there we can just simply do this we simply - he comes to a wine do this we simply - he comes to a wine do this we simply - he comes to a wine right because if the num if this one is not in there so and then it means okay so the current one so the current number has to be its own the ending point right so that's why we have an end number which length one in this case the one is the with the number itself then the length of that e is 1 right else right also what else we do I was if number is inside that right then we get the previously we got a previously length right from this like from this previous list but how right how can we get the minimum that's what that is when we need to use the hip-hip Q right eep-eep Q dot pop right the pop what we eep-eep Q dot pop right the pop what we eep-eep Q dot pop right the pop what we pop the end of in the previous ending right that's our previously length okay so after popping this one from this number here let's we let's do a quick charge so if basically if there's nothing left in this if the am if the list of the current of that and -1 is empty then the current of that and -1 is empty then the current of that and -1 is empty then we just need to remove this number numb from the dictionary right if this one Namek if this one is equal to zero right then we simply delete we delete this thing from the dictionary okay and then we just pick we already popped this thing right so now basically this one will not be the number right because we'll be increasing this thing by one right and because now the previous ending will be removed the previous number of the tail will be remove already popped from the hip kill instead we need to push another like element into this dictionary a heap Q dot push right hip push yeah this one should be hip pop what's gonna be the number right so we push this end right and numb right because currently so now it's in there we basically remove the one length from the previous the end lens from the previous element instead we'll be adding a new lens to the current number right as that because now the endings changed from the previous number to the current number right that's why we need to do this right to a free like length plus one right and then yeah so basically after this for loop right basically will be having a list a dictionary with each number as it sign the ending point right the in the ends here we'll just do a simple channel if you know any right if any the length let's see do a for number in the end right for all the lists in here which is even any of the minimum actor let's do a minimum here right so among all the lines for this number if the minimum of the length is smaller than three right basically then we know it's a false otherwise we'll return true here sorry yes in the end false let's see what else are we missing here not in this thing doesn't really matter I think here so instead of started back to instead of status one to one what we need to do is we need to do a hip insert yeah not the keep kill that hip push this and then one yeah cool yeah so see it works so basically and let's go through this solutions solution one more time right basically will keeping were maintaining like end list and a rare dictionary with the key is the number and the value is the list of length list of events that's who's the least length of the sub-array who's the least length of the sub-array who's the least length of the sub-array who's who is ending at the current number right and every time when we only sees a new numbers first we check if the current if the number if the previous number basically if the current number can be append to the previously split a sub array right if it can I'm sorry if it cannot right we simply create a new we push a new sub or creed and split a new sub array and we use the heap push to this for this current ending right because we need to use a heap push to keep the others in this for this number if the number can be appended to the previously asplenia sub-array right we previously asplenia sub-array right we previously asplenia sub-array right we get a previously splitted sub-arrays the get a previously splitted sub-arrays the get a previously splitted sub-arrays the smallest length previous freelance basically this will be the smallest length for the previously number as an ending right because we use a hip pop and then this is like just to a track here so if the after popping that this lines from the previously ending numbers if this number has nothing in the list which is simply deleted from the dictionary and then after popping the previously length will be now we are making a new ending length for the current number right because now the numbers of the I say there's a 3/4 right numbers of the I say there's a 3/4 right numbers of the I say there's a 3/4 right now D let's say now where I had four here right we popped the previously ending length for 3 right but now the lens sorry the ending position changed from three to four right that's why after removing the three lengths we need to add the length of four back to the heat to the dictionary so that we're making that we're changing the ending from three to four and after this for loop we get what we have a dictionary which the other possible not with the possible length for the numbers right and then we just do it track in the end here for each number in this dictionary if the minimum length for this number is smaller than three and then we know there are some issues right basically it means we cannot split array into the suburbs we want otherwise we just return true Oh I think that's pretty much everything I can I want to talk about for this problem and yeah I hope you guys enjoy it and thank you so much for watching the videos and I'll be seeing you guys soon bye
|
Split Array into Consecutive Subsequences
|
split-array-into-consecutive-subsequences
|
You are given an integer array `nums` that is **sorted in non-decreasing order**.
Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true:
* Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** more than the previous integer).
* All subsequences have a length of `3` **or more**.
Return `true` _if you can split_ `nums` _according to the above conditions, or_ `false` _otherwise_.
A **subsequence** of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., `[1,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,3,2]` is not).
**Example 1:**
**Input:** nums = \[1,2,3,3,4,5\]
**Output:** true
**Explanation:** nums can be split into the following subsequences:
\[**1**,**2**,**3**,3,4,5\] --> 1, 2, 3
\[1,2,3,**3**,**4**,**5**\] --> 3, 4, 5
**Example 2:**
**Input:** nums = \[1,2,3,3,4,4,5,5\]
**Output:** true
**Explanation:** nums can be split into the following subsequences:
\[**1**,**2**,**3**,3,**4**,4,**5**,5\] --> 1, 2, 3, 4, 5
\[1,2,3,**3**,4,**4**,5,**5**\] --> 3, 4, 5
**Example 3:**
**Input:** nums = \[1,2,3,4,4,5\]
**Output:** false
**Explanation:** It is impossible to split nums into consecutive increasing subsequences of length 3 or more.
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
* `nums` is sorted in **non-decreasing** order.
| null |
Array,Hash Table,Greedy,Heap (Priority Queue)
|
Medium
|
347,1422
|
952 |
hello guys welcome to algorithms made easy today we will go through the day 30 problem from august lead coding channel wherein we will discuss solution to the problem largest component size by common factor please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update given a non empty array of unique positive integers consider the following graph there are a dot length notes there is an edge between a i and aj if and only if ai and aj share a common factor greater than one written size of the largest connected component in the graph in the given sample examples we see visually how the components are connected as in the first example we can see that all the values have at least one common factor so the result becomes 4. in the second example we see that 20 and 50 are connected where common factors are 2 and 5 while 9 and 63 is connected because common factor is 3. the largest connected component is of size 2 only let's see the third example in much more detail these are the numbers given in the input if we make a node for every number and then start connecting the values which share the factors then the picture becomes a little clear starting with 2 we see that 2 is a common factor in 6 4 and 12. now we connect 3 and see it is the common in these many numbers when we connect all the numbers with the common factor with each other we get this graph well it looks messy and as the number of the elements grow it becomes more and more difficult to visualize let's break this process down we'll start by writing all the prime factors for all the numbers now starting with 2 we see that it just has 2 as its prime factor moving to 12 we see it has 2 prime factors 2 and 3 and 39 has a prime factor 3 and 13. so we write the factors for all the numbers now what connection we can make out of it if we focus just on the prime number 2 as factor we can mark the numbers it appears in we can say these numbers are connected now if we focus on the number which has more factors other than 2 we see that 2 and 3 have a relationship so if we find all the numbers which has 3s factor then these numbers will also be connected with the existing numbers which have factor s2 so we find for all the numbers with factor 3 and now these many numbers are connected with one another applying the same logic we see that 3 and 7 is connected so we connect all the numbers with existing graph and now all the elements are connected we can return the size of this graph which is 8. the question that arises over here is how do we find the relationship between the numbers and their factors the answer to this is a data structure called disjoint set or also called union find or merge find you can see its key role in kruskal's algorithm for finding the minimum spanning tree of a graph this data structure has two operations first is union which takes two argument and create a relationship between the provided numbers second is find which takes one argument and finds the parent of the element the data structure has an array where all the relationships are stored we'll find the maximum number and have the array of the size equal to the number plus 1. in this case as maximum number is 12 the size of the array is 13. initially all the values will be equal to their indexes now comes the part to create the union between the numbers and their factors we will achieve this by prime factorization using the brute force approach we'll find the prime factor of the number and then call the union method to create the relationship between the two we'll start looping on the input array and pick our first value as 2 is a prime number and a factor of itself there won't be any update in the array same will happen with 3 now we come across 6 like we discussed we have to find all its prime factors as we know that the prime factor of a number exists between 2 and the square root of the number we will loop on it and check for every number if any time we find the factor we'll call the union method for 6 and the factor and then additionally we will call the union on 6 and 6 divided by the factor because there will exist a relationship between the number and the rest of the other factors too we will be using this logic of union and find so it is better that you get yourself comfortable with it is a standard logic that we have used here for more clarity let's add index to all the values we will be updating the value at index 6. so we will start looping from 2 to square root of 6. s2 is a factor we need to create the union between 6 and 2. inside union we will call the find method for both x and y and update the value at parent of x with the value at parent of y so in this case the value at index 6 becomes 2 this creates a relationship between the two in second statement we create relationship between six and six by two which is three now the parent of six is two so the value needs to be updated at index two and the parent of three is three so the value at index two becomes 3. moving on with the prime factorization we get 3 as a factor which means we need to create a relationship between 6 and 3 and also between 6 and 2. both of these relationships are already there and hence there is no change in the array when highlighting these three values that we change in this iteration for six we see that we have created a relationship between two three and six starting from six its parent is two and the parent of 2 is 3 after applying the same logic for all the elements the array will look like this now we need to find the size of the connected graph we will use a hash map for it here we will store the factors and the number of time it is the parent of the elements we'll start with the first element and find its parent by calling method find on the element as parent of 2 is 3 we put 3 as key and 1 as value moving forward we find parent of 3 which is 3 itself and increment the value against e3 parent of 6 is also 3 so we increment its value parent of 7 is 7 itself so we put 7 in the map for 4 we increment the period 3 value to 4 lastly for 12 we increment 3 again it completes a loop and now we return the maximum value in the map which signifies that there are 5 elements connected to each other through one or more common factors summarizing our steps we'll first find the maximum element in the input array and initialize our custom disjoint set with it with a loop on the input array and for every prime factor we'll create two unions first between the number and the factor second between the number and the remaining factors we then initialize our hash map and our result variable too for every value we find its parent by calling the find method of the disjoint set we put value in the map and if already exist then increment the value against the parent key also we keep track of the maximum value in the result and at the end we return result here is the actual code snippet you can also find the link to the code in the description below thanks for watching the video please like share and subscribe to the channel let me know in the comment section what you think about the video see you in the
|
Largest Component Size by Common Factor
|
word-subsets
|
You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**.
| null |
Array,Hash Table,String
|
Medium
| null |
22 |
Ajay, then in this video we will see how to generate all balance payment, but we will go through the input output and problem that if someone asks, what input has been given to that output worker and after that we will see that this is a question in the school, how is the entry fee in this? How can we do this? This is a developed problem. Okay, if one starts, then we will make its record seat. Right, then lastly, its one and a half. Okay, so first of all we will do the middle. This is the input, output and problem statement. Okay, so friend in the input. We have kept a number, its ability has been given, now what we have to do for this number is that we have to assist all the balance parents, okay, so basically we have to use sample backless, we have to edit something like this, okay, we have to open two. Rackets and two projects can be used, okay, two pregnant, two products, so for this, if we how to generate balance payment, then something like this, instead of this end of the balance, the other can create something like this, okay, basically for able toe, we can use Pass will go to four drops, right, so we need something like this, in four, we have these four issues, 215 Kid and Cockroach Racket, these have to be folded, okay, they have to be folded, inbox, they have to be folded in such a way that it is what it is after all. The balance that is generated in me, now we could have done it like this only, if this note balance is fine then we should give it to the people if these adultery boxes are tablets, because if we open the man toe crackers then he will feel like this. What has to be done is that if you fold your affairs, then you get interest brother, balance princess, okay, whatever it is, this is below or I will say something like this, it will not work, we just do it like this for now, but there should be a balance, so for any possibility toe. It has become something like this, it has become easy, okay, what else can be missing, there can be some combination like this, okay, we will take commission for the enabled toe, okay, on the one hand, where we take N Shibli, we take it for free, on the one hand, what are we? That simple scheme open, then crossed all three like this, Surya, so we do this how to open close, inside this I am doing something like this, okay and this combination can be A, Bhumija, B can be rights, A, we always do this here. I am doing it like this myself and 119 others simple that we open one and then use then open that use open and use okay things skin none other than five will be generated initially so these five We will have this spring and this will be back spring, okay that will be the whole scheme, so we have to make this time a person film in which every spring will be a balance parents and a tourist in this way doing off track I am angry So I said what is the problem in the input that for this we have to do and here the balance will be set like even war this is us subscribe the problem statement is clear so now we are on that in seconds Ankita Namak we How will we identify the people, how is this seven requirement, how is the registration, so what I said, is it to be decided on the recording, at home, there are two questions, one is what happens in which it is written that do this from the record, then we Like vitamin came from it said shot and edited by recorded he requested him to test this year there is some money that give rippling defined in it and it is different or he said and grammar so that was requested defined isn't that According to the calculations, it is found that if this record is defined then there will be a question in it. It will seem that you are everything, you work only by stealing data success entry etc., neither in this data work only by stealing data success entry etc., neither in this data work only by stealing data success entry etc., neither in this data success etc., we will be able to escape success etc., we will be able to escape success etc., we will be able to escape on the question easily in which It is clear from the request that it is going to be carried, there are some questions, it is not known whether the solar eclipse will happen or else there will be an attack there, what are you looking at, there we show the choice please, so here we Choice or Edison is being understood anywhere, now we are on any state, how do we predominate that state, they differ from one note, okay, so from that we are getting all the stars, if you want that, Ibrahim. If it goes below the should and then immediately it seems that there is a decision, then this chapter goes after this, then when we understand the choices and decisions, then we will understand that yes this can be represented by Arya Kshatriya, then we will If you can make a side, then there is a question of reaction. Okay, so let's see how this rickshaw is neither there is no one nor we are forever, okay, it is giving anxiety, it means that I have Ad and Tech from three open rackets. Good care, otherwise overall I will get check box something like this to Shri Ram, I have to fold this box like this, I have folded it like this, first I have fixed a combination in such a way that after opening it, this is the combination. opening it, after opening it, this is the combination. Or don't open, close for use twice, such a combination will remain like this combination is done, something like this has to be clicked on the box so that this is generated, this balance was done, actually, how are we doing this? We wrote one here, we wrote here, so how is it being generated, so it is like this, brother, we keep Ad School in 6 boxes, how are these 6 boxes, so all three paintings are Ghosh, okay, so we There are brackets in this fort which can be used differently, so basically we have a choice for every boss. Even if I try to open this box again with the open racket, then look at the time and make it successful. Okay, for this we need this mask. Should I do open letters or co night like this also for add and sacrifice plate is ok at Loot Abhishek's place as if we were the only ones who felt a window above here had a choice, took it open and chose f**km If we it open and chose f**km If we it open and chose f**km If we can, then I felt on you, here we closed here, open here, crossed open here, thank you sir, okay, but everywhere 842 is open, then close is open, close is needed everywhere, okay, so basically in the choice. We have this pass for every 16 boxes, there is a choice for this, we try to use it openly in the city, now it depends on how we take the dishonor, how to take the medicine, due to which we are something national that this The symbol that was going to be in the end is this balance top, so we have to design it keeping in mind that we cannot break anything, okay, so this is done, now next that we have understood that. Brother, this record is only a problem, height is half of it is a developed problem, so we should be worried that we have to make a request, okay school, okay, so you guys remember what has to be done to increase the record seat, we are the ones to make comments. This is a very nice message written, it is called Input Output Message School, so what does that messenger do? Well, at first I did not know where to start, there are two ways of this method. I told him that one is simply input output, N1 says Is it standard? I mean by stand, so I named it 'Can See Curtain', I so I named it 'Can See Curtain', I so I named it 'Can See Curtain', I live in Indore, now Aman is asking how to do the question, there is a subject etc., it would have had a do the question, there is a subject etc., it would have had a do the question, there is a subject etc., it would have had a spring in the input as well and this loop would have been placed in the output, okay. That we were active and what to do in this pick and whether to take it or not, we used to do 24 things like take it here, put space, anything like that, so till now we have kept it in the sting in the input as well but before this noose It is okay that if we keep giving fisting, then we should keep generating and what will happen in the current standing questions from which team, in the extended court, we will get the moment in output. Basically, this is the input and output of these two. Data types, we have given time which is till now, their data has not been shared on the internet of this team and I will do two-three in many of its cities, so this is because two-three in many of its cities, so this is because two-three in many of its cities, so this is because what is this right now, then what have you given us? One number Ka or interior is ok tight robert interior long hidden question is in dehri cooperative na and in the input we have given a number and then in the net which is less and you the person has given the juice string of balance parents this point that we people We will have to wait for such a day and in the court, there is a number captured in the input and what to do with this, we have to strain, that's why I call it student, so don't think that friend, if the input is a string, then Poonam can generate more but it is not. Then Indore 2 will not be given input credit. You will be different, even then it is given. Okay, let's see how to make it and it goes directly to it. Its record is only that its record seat is also there, we can withdraw cash from the school. Come on, I have called you, hey man, we have given you the number and you are beating. I can tell you on the edit footer, but in explaining that light, some cases are not covered, so I am taking interest, it is okay at a low volume, so what should I say? RN Jagruti is kept, what does it mean that I have given some boxers, we have to fill them, okay, there are 6 boxes and we add boil, that means three open blacks remain and okay, by using them, we will get these six boxes. Attacks will take the total of something, 6 brackets will come to the site, that's a squirrel, what does it mean that we have three open and tobacco three, we will have to keep an account of this, we have filled 16 boxes in the inspection from the galet. I have already used one pan, so what has become of Open 3 with me is still available because of this, keep a number in your house and you take two three, from that I will reach there after accounting for both the things. I have n't even kept track of the closed ones, so what should I do to keep a separate account of the open ones? Care Open: How many have keep a separate account of the open ones? Care Open: How many have keep a separate account of the open ones? Care Open: How many have we used and how many are we still left? How many have we used and how many? If there are left, then from this maza-3, I will again add 12th open is equal to from this maza-3, I will again add 12th open is equal to from this maza-3, I will again add 12th open is equal to three length classification, this is the foundation, this time to make it because I will not be able to keep the account of 12 things due to one big reason, friend, your real. There is a promise that let's go, then I said that I have kept the need, so I again took it from him, it is open 1234 classification, so this is also my input, okay and you have to give us front spring by XP, balance payment for this, so I will install it. I will give you an empty string, so I freed it from the institute, let's see what is an input, now there are two things in the input, open and close, both are reels in the site Orkut, an empty string, tell me, now I have done this calculation with the help of this book. Meaning, we have to see that if we have to generate this balance parentheses, then how should we generate it? Okay, now tell me what I have, this is a kind of balance, what is the balance of Gaya Open, how much balance is there now, like we People will use it, okay, we will keep doing it, we will do 2510, okay, but all our backs go to Jyotsna, so the first thing is definition, okay, so what we used to do is that we used to celebrate our output and make more kits, right if. 201 So that both should be made on this output and two are made. If the garland is 134 then more bridges were made from the output. It is straightforward isn't it and basically it depends on whether we are at a particular state, so if we are at this stage, how many bridges are we making? Wide lace mill is tight so that's why I make as many more, let's do something like this here too, so that right now we are here, this is anti a right, we are so interesting, this is what I have 24, what should I do here, I Ajay Open Rocky Vikram reduce okay this is needed yes I can do an open related that I have to make a balance further balance can be made that I do that like this and then I will do it from 32 and I Panchami is empty string if I In the very beginning, if I use a clothing racket, then channel, do anything, this ca n't be balanced diet, then in the very beginning, if we do anything left, add or reduce the gym, then no one can do this. Can't balance, it's okay, anyway it felt like this in the beginning, it will go back, no matter what you do, dear friend, this balance is not going to die, I was like, right now we only have one opening, we can use only one opening regularly, this So I said, man, I did an exercise in this input, opening decorate your predicate input, it became like this, now opportunity and something like this happened and now I used one packet, so in this open letter, I did two, okay, buy and close. If I enter inside, then there is the problem of protection from close in weapons. Now I have got some such fittings, so now I can use one more exactly like this, close them in the hair or else I have just learned the editing. Either if I mix it first then basically I do an open reduction at home then it is absolutely fine and if I use it with flowers then it is not working at all, so what can I say, what is the fault, send the medicine now, then I should take the open and use it, and choose with the same meaning, if I choose my next then it will be done, this team will be formed like this, if I get sucked by taking the open, then it will ask, it is okay there, Papa, this is also okay. The point was, first copied that part here and then made this and the previous one, okay, we have taken that day for free, we did not use it like this which is out, yes also this and they copied it here, size, now I said that I am a This designer took the decision that now we will take the clothing and use it. Okay, now I have made the class less, it became something like this, how much earlier the open tooth was opened, after all, we did not make the loan open just like that, now if we use the class, then the closed tooth has been made free. We go to Mitthu Thanked His Mind, this one is on the note and then there are these two brackets. Okay, now we all need a box, whether brother should grease the top 10 or I should practice all three and close it later. Okay, here I press it, after this I will add the total, so here I have one ball, I take one and use it or I use one on that, then I use my but, then I need these eyes, so here this The team will come, if I do this then my open balance will be zero, so right now I will not use even one, okay, fix the balance and keep it free, here I decided, this was the output, so I copied it, first I set it and I One is going to use it logically, so I have mixed it, how is the balance of open, is it okay that I use it here, otherwise the name of open balance will remain and clothing for that, now in South Africa, school cents are with you, now here. So for this too, let's take home first and see what is here, I have given something like this in the output and then what have I given that is something like this, okay now if I reduce here also if I use the opening. I do it okay, yes, balance can be achieved, I will mix it, okay, I will take it open and use it is absolutely okay if you are giving it whole and tight, you are giving it tight and whole, I already have this also, if I want 1 kg zinc Now if I take and use it, then under any circumstances they should deduct it in no balance because I close here, what does it mean if I also take two MS Word, it only means that app related two first. Only then this balance should be there, here he took one thing and we always have this reality, so we are netting it after that, we have to net it before the balance is formed, okay, so here basically it is 134 that I only take one of my own and use it. What do I have right now? If I want to remember something like this, I can use another open one. Okay, so I have made a table, I also understood this and if I do it quickly then it will be open. Gone here, one and closing is two, just like acall, we come here like this, we did not think anything here, what is simple here, open ended here, when we got the choice of open from open sir, we got stupid register, so I The post is empty that the bag 24 seemed to be that of Russia so if I use person then something like this will come here and 15 class two then in another closing I will reduce the icon also then I got something like this. Andhero class one officer 10 racket so I was passed that this is open 0 then when it is open 020 Raghavan took notice people will not work and here when it is open 0 then we people one balance side now from here I do the same thing, this is where we are at the same time, out of all the accused, if I juice it at all, then this is the balance, what do I do, use one more of my bad ones and upload it and so on for some time. If it becomes later, then I want both of them here, I have one, so I can take one of mine and suck it. Shouldn't I sleep with one logical juice? Okay, so I opened here, I already had something like this, after that, I took it in the job. After getting sucked and according to it, show it like this from before, so now it has become tight like this, now how much balance would have remained in both the cases, they had come out, so now I am left here, I have made an opening, here I have my skill, open zero, go inflows into. And how much balance is there here, in the matters of achievement news for basic here, I have juiced 10 back, so I have not finished the balance juicer, what becomes of one, but made it tight in a day, well, now it should be brown, I would have pressed it a little for this. And here also let's see what is going to happen. Okay, so what is going to happen here, let's see its branch here. Now this is something like this, now here is something like this. Now I have a story like this and in the well. After falling, now I can choose one in the lobby, the tube will balance well, the cockroach will go, or what should I do, I can choose one more of my own, one should be Panchakarma, now I can close it later, okay, so that both of them need some table. That diagram is going to be very dirty so here it opened zero and closing two so here what I did was that it was already there for 10 minutes and then I sucked this website connection so closing account I reduced two If it was open then I closed it and if I did not use it, then when should I close it? Okay, now let's see what they are doing on the grill here, so what to do in it, now I basically have the work of opening here finished. Whatever is left, this child with a cross, then I will use straight close, here, take this, more than this, zero and vansh, then I will use a glass, so it becomes something like this 010 again, we are like a little or like, a balance paint. Mixed in this, okay, now this one, let's see what is happening in this note, here basically this is the balance here, this is already balance, if we look at this here, it is something like this, I call it chocolatey balance if I choose closing here. If I do this, then no one can balance it, so I will move it 1 inch from here and I will also juice it for the opening day. Okay, so what will I do here, I will put an opening back door. This was first and then I will copy it the same. Then I took the open one and sucked it and opened it. Is it according to zero? Is the water okay? After this, when I will feel another close, it will become something like this. It is okay and the account will remain. Night of both the opponents and get this note. Let's go here, I open all the uses, close, children do this class, this one also closes something like this, if I go to this Dam 210 account of 2012, I got a balance here, let's see what is happening here. We guys verse is something like this that if I use a closed packet here then this balance is not going to be created then I should verse that after this I should decree an opening okay so I have one here I have taken the opening and sucked Took this counter, put it black, it was already on WhatsApp, copied the same, then put this open butter, opened the account, killed the zero clause, now I have some stars, save it, if I finished inside, then I need a sample of the close clause. This is what I clicked on this and the account is created 08 Now I zoom out a little bit, okay loot, still look carefully, what happened here by balancing, we got it here And here some of us Five Springs, I had talked about earlier, what I had written, then we will pay those five balances, here I am on the list note and the list is job properties, we will identify how to open an account there. The card of these clauses is also becoming zero, right from zero, there are 30 objections here, I hope you understand this much, let's once again this will become the referee, the common people, if this, then this request has been made to him, now he has the next one. To explain the point, I will have to save it again because it seems to have become quite cool, so Lakshmi Yantra hit, okay, this is the Father, we are okay, so now we will have to do most of the things here, will we have to use the observations here, will we ever have to do that again? The thing is right, here it is inches again, now this is a single brand, from which there is a single bench here, Singh is the sarpanch here too, so all this is happening because right now the online calculation is felt that man, if we are here now then there is one. If you use it logically then it will not use the balance but in the invite code these attacks should be kept in mind that we will need a solid condition that when this condition is hit then we can use another branch, I am not right. So basically what is it, so I have said that always use the opening packet for sale, we have referenced it here, we have used it in our black here, they have used it in ours, but we have used it here, keep it there, when are we reducing the usage? There are absolutely thousands of us up there, we are busy here, okay, keep strengthening your grip, sometimes what happens with the attacks is that this branch of the project comes to us, which means that we always had one shop. You can use us by taking us open at any time, sometimes we are using it by taking it here also, it is okay, so it is a single bench, branch office with its own pregnancy, we always have the choice of closing date, sometimes it is coming sometimes. It is not coming here, the closing rank has increased for 240 days, neither is this happening, meaning what is being said is that if we are at any state, then due to that injury, we have 24 involved in the opening racket, well- Known Unless this is a completely finished choice well- Known Unless this is a completely finished choice well- Known Unless this is a completely finished choice that sometimes it is not coming, see it here we still have to do it, we will get people who can do this, we will get it, okay, and it is a simple way, so what is happening Let's see, there is a choice here, okay, we will take people's subject here and also from here to here also want okay, so whatever is in this here in the contra voucher, so here I take it from here to here But here it goes, this number does not give the right, from here both should get equal amount, from the number, we are fine, today we are getting close, this is greater open, while they will, so we are this. You will get the option of clothing back, now we have to see why it is so simple that you cannot save unnecessarily, subscribe and if it is so, then open it because we can use that something like this is fine, so balance and here If we use one, then we use it on this account only then we appoint it, that is, when the condition that when Bigg Boss is Greater Than is open, its number means we have more children, then we also Let's do that then I would have done it. Well, I say that we have created this person in which we have to subscribe and this should be called AV School. Now what we had to do is that we created two things in the attacks in its output and this input. One of these was our block with each other, so let's make two. Thank you sir, it's okay and the interruption was done by both of them for this, what is there in Devla output, we need intestine and in that we have tomato, so I and the foot spring also got spring. And added pimple to this track, now all the missions to be made from here are done, now I called the function from my wicket, then from the receive function let, I said solve back, what all did I give in it, I gave this open account. The open close card was given tight and I gave this notes to the team and I had given this vector that how to write school absorption, if it is looted then there is no return to it, there is nothing to be done, the return of the volume included is taken tight, to get it tuned, basically whatever our Pass one balance like and we will store it in the sweater. Okay, so we will start it in the sweater and pass the sweater by reference, then let's see, after 5 minutes of open use, inches will be lost and it will go quiet. This trim TV and this matter. Okay, we were coming to our selling mission, whenever this condition was coming, let's see, here when we have both open and closed accounts, 0326, both the accounts are there, then we are getting back a base condition, okay. If yes, then it looks bloody. App opening is equal to a Rs 120 Android phone. It will arrive on Monday. The part will be available from America in the outed period, so we are back-packing it in vector. We so we are back-packing it in vector. We so we are back-packing it in vector. We need some batter and some back-end photos and will do it need some batter and some back-end photos and will do it need some batter and some back-end photos and will do it from here. Beyond this, there is a delete note that will not run for additional sessions, hence it will not work. We are editing them. This person has to be passed through the report. Okay, this letter has to be passed through the reference. What I just said is that after this, we are the next thing. That we have only two ways, either back to 41, so I saw that closed beds will always get the highest choice, closing has never been found yet, so open is required, till when did we get it, open 249, let's see here, open when. As long as I take it here and here, I want it here, open it here, then what did I say to you, as long as I am not against opening my account very well, then I also have this choice. So if you get it then it is an open account, it comes in front of you and here it is free, so as if something like this had happened, how to accept it, then this is in the output, now what do I have to do, I have to copy this output in the same. And good boy, I put one back in it for opening and reduce its account and I feel like opening the account and I was sitting on top and putting one, so it is simple, it works like this, so what have I said? That I'll create another output string and copy this 2002 and footage and Twitter into the note and then turn off the hotspot I'm saying I was feeling one of my black tees in this I'll put that back so I can do some back up and one I have an opening date something like that I did in college for a black juice so I will reduce the account okay and then I will do this liquid function or call again so for this I do this song right now call me again So now what we had was our open was closed and output and this is tractor so I said now once I can use open regular then I will call on open - become okay then I will call on open - become okay then I will call on open - become okay this is this so this is always available. As long as this is open, you will get another number and do n't forget to subscribe to this number, again how will this be solved, open is closed and confirmed and vector was closed, if I press it, I use it, then it is in the balance. - I will close it and then it is in the balance. - I will close it and then it is in the balance. - I will close it and then take it again and do it from here only. I applied this serum on your zodiac site. I went to the school for a function, it is nothing special as I did but said to him, I do it with the salary, this will be the best condition for the time being, okay. But when both are becoming zero, after that I said that I am always getting this, I am fine, my perfect one, so she quoted for it and slow down that she is getting it when Bigg Boss grade is opening. It's night, so someone came out of the house for this, write why this nipple is in this condition, because it is getting 24, never getting it and being involved in this till the time it has happened here too, then now you must have understood a little. What has happened is that with the help of you have got food from us, this secretary, the economy is also strong and on the other hand, I appointed you as the first one.
|
Generate Parentheses
|
generate-parentheses
|
Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_.
**Example 1:**
**Input:** n = 3
**Output:** \["((()))","(()())","(())()","()(())","()()()"\]
**Example 2:**
**Input:** n = 1
**Output:** \["()"\]
**Constraints:**
* `1 <= n <= 8`
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
17,20,2221
|
334 |
hello there so today we are going to cover increasing triplet sequence we are given an input of integer array nums and we have to return if this array consists of a triplet subsequence if it is contains triplet subsequence then it's true otherwise it returns false so let's understand the problem statement with an example so here's a first example given if you manually see the array will be indexed like 0 1 2 3 4 and the values given are 1 2 3 4 5 so now i j k will be our indexes if you see 1 2 3 4 5 r is in increasing order and this index is also in increasing order that is 0 is greater than 1 is greater than 2 and 2 is greater than c they are asking us the triplet subsequence so it is to find whether we have three numbers in sequence and that indexes is also in increasing order yes in this case we have three numbers in sequence and the index is also in increasing order so it is a triplet subsequence so we are returning true consider an example two here if you see if you can form any subsequence of three elements in increasing order let us check when you check nine the next number is eight which is less than nine so nine can't be included in any subsequence so let's consider the next element eleven if you see eight and 11 is in increasing order so let's consider the subsequence of length 1 so now moving on to 6 when compared to 8 and 11 both the elements are higher than 6 so 6 cannot be included or 8 and 11 cannot be included in a subsequence so now moving on to 5 when you see the numbers before 5 every element is greater than 5 so you can't include 5 also in any subsequence so we couldn't form any subsequence here of size 3 in this case we are going to written false so if you think about this for a moment you can relate to something we have already solved in our channel that is longest increasing subsequence in an array so we are going to use the same technique in this problem the longest increasing subsequence will find the length of the longest subsequence in an array so here we are going to use to find along a subsequence which is greater than or equal to 3 because it is asking a triplet sequence if there exists a sequence of size 3 or more than 3 then it satisfies the condition given in the problem so in that case we are going to determine if the list formed is greater than or equal to 3 then it is true otherwise it is false so now let's get into the algorithm and go for a dry run with the example so if you want to understand longest increasing subsequence problem i have given the link in my description you can check that here we are going to use the same concept to find a longest increasing subsequence of length three or more than three if that exists then it is true otherwise it is false so let's get into our algorithm here we are having our input array nums the concept we are going to use here is dynamic programming so to store the values at each stage i am going to have an integer array dp where this array dp stores the values of subsequence length of subsequence till that point so first we are going to have two pointers i and j where i is our scanning element it moves every time it is done with the value and j is representing the range from 0 to i so we are going to have 2 pointers as i said i moves every time and j scans from 0 to i every time so now we are going to have our i at starting at index 1 and j starting at index 0 first let's see whether the value at position i is greater than value at position j which means there is an increasing sequence yes there exists an increasing sequence first our array will be filled with all zeros so now we found one subsequence of length one that is one two forms a one and two forms a subsequence of length one so we are going to update here at the dp that till 2 we can form a subsequence of length 1 so now we have updated our value to 1 now moving our j pointer to the second element the loop ends and we have to advance our pointer i to the next element and start j at 0 we have our pointer i at 3 and j starts from index 0 now we are going to check whether 3 is greater than 1 yes 3 is greater than 1 so we are we can form a subsequence from one and three so now the length at one was zero and by from three it is zero again but from one to three we can form a subsequence so i am updating the length till 3 as 1 first now we have updated the length to 1 so now it is the j moves to pointer 2 and now it checks 3 is greater than 2 or not yes it is greater than 2 so we are going to update our value to 2 because the length already there in position 2 was 1 now we can append this to that sequence in that case we can update the value at 3 now we can form a subsequence of length 2 till 3 so now again the j pointers move to this position the loop ends now we have to advance our pointer i to 7 now we have our pointer i at 7 and j at 0 we are going to compare whether 7 is greater than 1 yes it is so from 0 from that is value of 1 we can add 1 to 7 so now we are updating our value to 7 as 1 now we have 1 here that is we have some subsequence still 1 we can append 7 to that subsequence so now moving our j to 2 we are checking whether j is less than 7 yes so we are going to add 7 to that subsequence so the length of the subsequence we can form till 2 was 1. now we are going to update our 7 to 2 because 1 we are going to add 7 to that so the length will become 2 so now the length of 7 become 2 so again now jade moves to point three and checks whether seven is greater three is greater than seven no three is less than seven so again we can append this seven to the subsequence till three in that case the subsequence we can form till three was length two so if you add seven to that length we can add one more to this length so two plus one will become three now let's update the value of seven to three so now finally the j moves to the place seven the loop terminates now it's time to advance our pointer i now we have our pointer i at five and j starts again from zero now let's compare all the values whether 1 is less than 5 yes so we can form the subsequence from 1 that is 0 plus 1 is 1 so now checking again 5 is greater than 2 or not yes it is 2. again we can form a subsequence from there so 1 plus 1 was going to be 2 here so now again checking 3 and 5 we can form so 2 plus 1 is going to be 3 and finally j moves to 7 and the pointer will be at i so checking 5 is greater than 7 or not 5 is less than 7 so in this case we can't append the value 5 to the subsequence till 7. in that case the value of the length of the subsequence we can form till 5 will be 3 again now finally our i reached the value 2 and j again starts from the value 0 we are going to compare the values so starting from 1 if you check whether we can form a subsequence yes from 1 we can add 2 to that subsequence so let's update the value to 1 here and then 2 checks whether it is greater no again the j moves till 7 total 5 no values are greater than 2 so in this case we cannot append this 2 to any of the subsequence in the previous element so the value the length of the subsequence still 2 we can form sticks to 1. here our dp array is updated completely now we have our element max to keep track of the maximum value from array dp so the maximum value is 3 in the array so this which means we can form a subsequence of length 3 so it is checking whether our max is greater than 3 greater than or equal to 3 in this case we can form a subsequence increasing triplet subsequence so we are returning true as a value it is very pretty simple algorithm just follow the same logic as that of longest increasing subsequence so let's code now as i said i'm gonna have an integer array dp to store all the values of my length of my subsequence it is of length nums.length and i am going to declare a nums.length and i am going to declare a nums.length and i am going to declare a variable max to keep track of the maximum length of the subsequence so i'm gonna declare my two pointers i and j where my eyes gonna start from index one and i trade till length of the array and my j is going to start from 0 and i trade till i every time so now we are checking if my numbers of i is less than numbers of j sorry create the number j then there is an increasing sequence in that case update our array dp so dpf i would be max of dtf i dp of j plus one and max is gonna keep track of our maximum element from the dp finally return if max is greater than or equal to 2 because here this size stores from 0 1 2 3 so 2 means which means the size of the increase of sequence is three so let's run yes so you can find this code in my description thanks for watching thank you
|
Increasing Triplet Subsequence
|
increasing-triplet-subsequence
|
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
| null |
Array,Greedy
|
Medium
|
300,2122,2280
|
209 |
hello and welcome to another Elite code problem today we're going to be doing the problem of the day for July 6th minimum size sub race zone so you're given a subarray or you're giving an array and you want to return the minimal length of a sub array whose sum is greater than or equal to the Target and if it doesn't exist let's return zero okay so for this first example we are going to have an array of two three one two four three and the minimal length sub array that has seven or more is this obviously there's nothing shorter than that for the second example pretty straight four one four it's this or this either way they're going to be length one and for the last example we only have eight one so we don't have no solution so let's figure out how we would cue this right so we're gonna have this problem let's figure out how we do this for this example here so we have a Target and we know our sub array is contiguous so as soon as you know contiguous sub array first algorithm you got to think of sliding window is it possible easiest one if it is let's try to think about it and in this case we do have a condition right like our Subway has to be greater than seven or equal and it has to be contiguous so we can just keep a running total so we can have a result we're trying to minimize it so let's make the result Infinity to start and we're just going to make a sliding window and we're just gonna so our algorithm is going to go like this I'm going to show you so we're going to start at the left and we're going to keep going until we've matched the greater than seven Target and so we're gonna go like take this number we can keep going five six now so now this is our sub right here this thing here so the left is here the right is here so I'm just going to represent the left and the right with this line the left is always going to be to the left of the line the right will be at the right of the line and so now what we're going to do is once we actually have a valid sub array we're going to shrink it as much as possible but it has to still be valid so our account our sum let's just call it our sum our current sum is or just call it curve maybe our current sum here is eight and so we're gonna see if we can shrink it and we're going to shrink it as much as possible to make it still valid so if we actually get rid of this element this wouldn't be valid right this would be uh this would be six so we can't actually shrink it so this is going to be our current sub array and so this is length four so now our result is going to be updated to a four now that we can't drink it anymore we're just going to keep adding to it so we're going to add the four now our current sum is 12 and we're going to try to shrink it as much as we can again and so let's see how that would look so we can get rid of this two right so we can get rid of that we could shrink it like that now our current sum will be 10. and we can't shrink it anymore so our Subaru would be three one two four and so that's also length four so that's the same as our result now we finally add this three and so the left is over here the right is at the end and so when we add the 3 our current sum is 13. now let's try to shrink as much as we can remember because we're trying to minimize the length so we can trinket we can get rid of this number now our sum will be 10. we can also get rid of this one now our sum will be 9. we can also get rid of this 2 and now our sum will be 7 and finally we can't shrink it anymore because we are at the Target and so now this is going to be our sub arrays left is here and the left here it's not really a left but yeah you can get one point left right and so now this is going to be linked two so that's our result so pretty straightforward problem so we're going to write down the steps actually here so let's make this text a little smaller one two pointer technique okay so keep adding to subarray until it's greater than or equal to the Target and then when it is shrink from left as much as possible but maintain validity right so it has to be greater than or E so sum has to be greater than or equal to Target and then finally record result and try to minimize our results so we're just going to have like a Min of whatever our sub array is and our current result and then finally if our result is infinity at the end that means we didn't find any valid sub array so then we can just return zero so pretty straightforward problem I think it's pretty similar to the last problem that I did yesterday very similar so let's actually code that up so we're gonna have a left as always for twosome or num sliding window sorry and then we're going to result we're going to make it infinity and try and minimize it okay and I believe oh yeah we need a current sum right so just print some we're gonna make that zero and so we're going to actually like I showed in the other video we can actually use the right as the index we're actually iterating through because we have to iterate through all of nums so we can just do this nums so you don't even have to initialize that right here you can just throw it right in there so what are we doing so we are cursum plus equals nums right we are adding the value now if it is greater we're trying to shrink it as much as we can right so while uh let's see here so we need to shrink it as much as we can but we don't want to shrink it too much so I think what we could do is just have a while and a break Loop that would probably work fine okay so let's do that so while uh this is going to be occur sum which is greater than Target so if um this is going to be per sum minus nums left so if we can't shrink it is a less than Target right uh cursum is so it's actually also by the way it's actually in here let's do the checking for the result we can definitely do that because we're trying to minimize our array so it's we're going to check the result multiple times but that's okay because you don't want to have an if statement outside or you could do an if statement outside let's actually do the statement outside but anyway so if the current sum minus nums left uh is less than Target that means so if this is greater than or equal to Target and the current sum minus thumbs left is less than Target that means we can't remove the left so we can just break and then otherwise we can remove the left so curse sum minus equals now let's actually look what the target can be um and let's think about like an edge case as well like if the target is one and uh I think we might want to add do we want to add that like the condition I'm thinking of is if we have like a one length subarray but that'll never actually be in yes if we do have a one link subarray that's greater than the target but we don't want to remove that element no I think that'll be fine yeah I think this should always work but we'll test it out we'll see if we have any edge cases okay so anyway so cursum is gonna be minus equal uh numbers left here right and then left plus equals one I don't think we have to check if the left is like past the right or anything I don't think it can ever be because like I said if we have a one element array and our Target is even one then uh then we can never move every single element okay anyway so now we can check in here so if curse sum is greater than or equal to Target we have a valid array then we can do our result checking here so as always we can minimize the result this is right minus left plus one to get the length of the array and then we can just at the end oh we need to so we don't need to do the right plus one because we're iterating through the array but we do need to check if there if the result is infinity and if there's if the result is infinity that means we didn't find a sub array okay so let me just go over this one more time just to make it clear so this is going to be like our right part of the sliding window we're going to add the number and then while the number is bigger than the target we're going to try to minimize it as much as we can but if this is the case that means we can't get rid of the left element otherwise we're going to get rid of the left element and then we're going to increase the left element then we're going to check is our sub Ray valid and if it is let's update the result and finally we can say return result if result does not equal flow Infinity uh else returns zero okay let's see how many errors we got can't wait for this one you don't see oh amazing okay so this was actually good so that's surprising okay so let's actually think of the time and space here and so like I said it's a sliding window so these are pretty much always the oven where n is the length of nums and space just like yesterday's problem is over one if you didn't declare any extra space or anything we just have uh some variables yeah that's gonna be it for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I will see you in the next one thanks for watching
|
Minimum Size Subarray Sum
|
minimum-size-subarray-sum
|
Given an array of positive integers `nums` and a positive integer `target`, return _the **minimal length** of a_ _subarray_ _whose sum is greater than or equal to_ `target`. If there is no such subarray, return `0` instead.
**Example 1:**
**Input:** target = 7, nums = \[2,3,1,2,4,3\]
**Output:** 2
**Explanation:** The subarray \[4,3\] has the minimal length under the problem constraint.
**Example 2:**
**Input:** target = 4, nums = \[1,4,4\]
**Output:** 1
**Example 3:**
**Input:** target = 11, nums = \[1,1,1,1,1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= target <= 109`
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
**Follow up:** If you have figured out the `O(n)` solution, try coding another solution of which the time complexity is `O(n log(n))`.
| null |
Array,Binary Search,Sliding Window,Prefix Sum
|
Medium
|
76,325,718,1776,2211,2329
|
147 |
hey everybody this is larry this is day 15 midway through the december league daily challenge hit like running the subscriber and drama and discord let me know what you think about today's problem insertion sort list okay so given ahead of the okay let's just insert some short insertion sword wow why is that hard to say um but yeah i mean it's a little bit awkward that n is 5000 in that if you know an insert insertion sort is going to be n square right um that is a little bit awkward though isn't it because at 25 million seems a little bit high especially in python but yeah i mean i think you just get the min and then you just keep going right um i think that's mostly it so yeah that's implemented i think this is an implementation problem i mean i think it even gives you instructions which i didn't really read but um let's see if we can get to it's a little bit yucky to be honest um but not impossible yeah i mean i think it draws the thing where it counts from the end up but i think you just come from the heads up again so okay how do i want to write it um okay so let's just say this is just a very awkward problem i mean it's not hard it's just about keeping track of lab stuff what i call beat a bookkeeping problem um except for in this case you have to you know the book is big and you have to keep track of it especially for a regular linked list where you not only have to care about this um this pointer but the point of previous to that right so okay so that's fine maybe actually i think that's okay so we could the way that i always write it is with a new sentinel so let's start by doing that and a new head is done next is you go to head maybe um depending how you want to write it you don't even need to i think maybe you don't even have to write it this way right um while we do while um while head is not none then we do we start from head and then we let's do one elevation to get the men yeah we could just get them in with one elevation and then we'll just put it in the nail head maybe that's close enough though maybe a little bit awkward but i don't know if this is like i mean this is a silly problem anyway so maybe in an actual interview you would ask the interviewer and agree on what you want to implement and what makes sense right so uh let's say current is your head so then we do uh well head is not none let's just do another one i just say uh i don't know naming things is hard so let's say in this one you is the center note because i still want a center note so then well um well i think what i would right here then it's just easier to write that hex is not none because in that case then current is you go to second head dot next maybe and then or maybe second head and then we get like min element is equal to uh second current.next and then now while current.next and then now while current.next and then now while current.next is current.next is current.next is not none um min if con dot next i think actually what i want is the min element to contain um to be current and then just have it point to the next one which is a little bit better i think because if then current directs that value is smaller than min element.next.val element.next.val element.next.val then min element is equal to current and then you know kern is your current down next and the idea here may be and i could be wrong to be honest because these things are very easy to be wrong uh so definitely you know try it at home and do whatever you need to do but then at the very end then we know that min element.next um that min element.next um that min element.next um points to next points to the min and in that case now we can set new heads is equal to this um new head dot next is equal to well maybe that's not necessary tail is equal to new head right so then now the last element tell ty tell dot next is equal to min element dot next right yeah and then now we can write something like hmm well min uh whoops fingering min element.next.next that's so we want element.next.next that's so we want element.next.next that's so we want uh min element dot next is you go to this so that we skipped that the old dot next um so we want to move some pointers there yeah so we want to move elements thing and you could draw this out i'm trying to draw it on my head to kind of see that this works uh i am solving this live so if it's a little bit slow and you're still here uh you know feel free to fast forward whatever you need you don't need my permission but just so as a reminder um yeah and then now tell that next is equal to this thing so that now we want to set tail is oops tail is equal to tail.next and tell that next is equal to tail.next and tell that next is equal to tail.next and tell that next is equal to none because now you have tail and this one your you remove the main element so i think this is okay and then now at the right hand you return down next i don't think i don't know if this is right uh maybe it's right but uh i won't be surprised if it's not because it's just a lot of um i think i did too many things in my head so it's hard to track but that's why you write you know tests and um kind of you know experiment with things okay so that looks good uh that looks good as well so what is uh let me just do uh you know a reverse case oops um i feel like to be honest i'm a little bit cheating maybe not by that much because i'm only using one extra pointer so this is actually all one space or one on one extra space um we'll talk about that in a second um but it's probably not in this full spare thing it's not going live uh because oh i did it in three seconds last time let's see if it is fast enough i mean i don't know if this time limit is a little bit awkward though to be honest because i mean this is n square so how much faster do you want it to be right this looks like it's going to time out though which makes me a little bit or a lot sad uh it's either that or the server is just really slow but either way that's uh oops why is this so slow so i'm just like just checking with my internet is okay and it seems like it's okay so it's not the uh the reasoning but okay so that does look okay 624 a little bit slower than last time what did i do last time i hope i didn't cheat and convert it to a list oh no i did the same idea um but a lot slower for whatever reason um i actually didn't look at it so it might not be the same idea but um so what is the complexity right this is going to be o of one because we only have like a couple of extra new pointers um yeah oops o of one's space and this is o of n squared time as we know um but that's i wouldn't say that's lower bound for what we want to do but for insertion sort that's the best we can do right and i would say um the reason why this is all one and i think one thing that i do talk about a lot is not having like in place um like influence functions are kind of like the side effects a little bit dubious in general because um a lot of the times it's not within the expectation of what you want to do but that said i think in this problem you know if you're calling an insertion sort list um function you it probably is okay that you return uh something that manipulates the original input so as a result i think this is fine actually um we just have constant number of uh extra space um and yeah and that's all i have for this one uh let me know what you think uh hit the like button subscribe and join me in discord it's a little bit annoying for this one i just basically get the main element and then insert it i don't know maybe we could do it in like more in place i guess with like one few available something like that but i think this is just easier abstraction and technically you just add an extra variable so i feel like it's not a big deal but maybe you disagree then in that case show me your solution let me know how you did let me know how you think uh okay that's all i have for this one stay good stay healthy take your mental health remember you're halfway there let's finish the other half i'll see you later bye
|
Insertion Sort List
|
insertion-sort-list
|
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_.
The steps of the **insertion sort** algorithm:
1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
3. It repeats until no input elements remain.
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5000]`.
* `-5000 <= Node.val <= 5000`
| null |
Linked List,Sorting
|
Medium
|
148,850
|
1,295 |
because let's over 12 and if I find numbers with even number of digits so given an array numbers of integers returned how many of them contain even number of digits and we have array of number of integers so if you look at number one so we had 12 345 2 6 7 8 9 6 able to check if each item in the array has an even number of digits and any order for us to do that first thing we probably want to do is convert each digit to string so that we can get the length of the digit and then you want to probably increase our result variable if even add so it's the first one even yes so second one nope this isn't 6 isn't and 7 8 96 it has four digits so it is even so we get 2 as a result which is our output I guess so now let's code our solution the kernel function which takes in one parameter which is an array with integers and that's the current variable name result this is going to store how many even numbers we have and we'll return our result so we're gonna go through our array using a whole thing you want to go to all thing and I'm just gonna make a variable that num is equal to so you want to convert the current number touching Saddam's index I and the reason we convert the number into string is because you want to find the length of the current number and we're going to check if num length modulo 2 is equal to zero we're going to increase the result 5 1 so we compare our number into a string so that we can get the length of the number and we get the length over here and we do modulo 2 so if this modular 2 is equal to 0 that means that is even right it means that it doesn't have any remainders um so that tells us that is even and it fits even we're gonna increase the result by 1 and 4 are solutions so we get 2 & 1 as a 4 are solutions so we get 2 & 1 as a 4 are solutions so we get 2 & 1 as a result if we check it's 2 & 1 so there result if we check it's 2 & 1 so there result if we check it's 2 & 1 so there we go let's go over our code one more time so with the curve variable which takes in a parameter which is an array of integers and we declare we stop there you go so that we can count the number of even integers and when we're done we're going to be turning our result over here so we're gonna use a folder to iterate through all the numbers in our numbers array and we start index 0 and we want to go to all the items so increment we increment by 1 and what we want to do is we can't get a length of integer right we're kicking a length of a number so what we have to do is first convert our current number to a string so that later you're not if statement over here we can use the length method to get the length of the current number and we check using a modulo 2 to see if it's even or not so we if we have a number that's not equal to zero that means it is odd obviously then if it's equal to zero as even right so even this is basically checking if this is even and if this even you're gonna increase our result by 1 and we're going to do that for all the items in our array and when we're done we got duped out over this and then we turn our result so looking at number I mean example two we have five nine zero one four eight two and one seven one the first thing we're gonna do is we're gonna come all these into a string and then check is this odd or actually is this even nope is this even yes so we get our result is equal to one and that's what we can over here too
|
Find Numbers with Even Number of Digits
|
minimum-garden-perimeter-to-collect-enough-apples
|
Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
**Example 2:**
**Input:** nums = \[555,901,482,1771\]
**Output:** 1
**Explanation:**
Only 1771 contains an even number of digits.
**Constraints:**
* `1 <= nums.length <= 500`
* `1 <= nums[i] <= 105`
|
Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected.
|
Math,Binary Search
|
Medium
| null |
828 |
hey my name is casey and i'm going to explain how to do lead code 828 count unique characters of all sub strings of a given string so let's pretend that we're given this string xx lelouch l x what this question is really asking is for every character how many sub strings is each character unique in so for example let's take this first l how many substrings uh is this l unique in where well the word there's no other ls that occur right that's what it means to be unique so uh let's just put some parentheses around this and we don't even care about the rest of this substring because we can't include this l because now is no longer unique and then we just go to the beginning of the stream because there's no other ls back here okay so how do we calculate how many substrings we can make out of this l and just to be clear what the different substrings would be like xxl l e l and i know just by looking at this there are six substrings and the reason i know that is because there's this little trick where you can just cop you can count the positions on the right of how to group the parenthesis and you can count the positions on the left of how to group parentheses so for example you could put a parenthesis here put one here put another one all right let me actually yeah let's do that so that's there was one back here and we moved it now this is two this is the third position i can put it in there's three spots on the left and on the right there's one and then there's two spots on the right that we can put it on that we can put the parentheses in so the way that you calculate how many uh different substrings we can make is just how many different ways can we mix and match those uh parenthesis on the left and the right and that's just 2 times 3 equals 6. and i feel like with that alone you can actually start solving the problem as long as you know this little trick i guess the rest of the problem kind of falls into place so let's just do the next letter just to be really clear so let's say that i want to know how many substrings the second l is in well we don't want to include this first l because then l will no longer be unique and we want to stop just short of the next occurrence of l so now we just have this substring e l o u c h so how many substrings is this l a part of where it's unique and the answer would be well let's just count the number of spots well there's one place that we put the parentheses here another spot is here so that's two on the left and now count the parentheses positions on the right one two three four five so that means there are two times five or ten substrings that this uh l is uniquely a part of okay and we could do it for the last element you would just take it to the end of the string or it would be all of this if you wanted to figure that out okay so moving on how do so notice that we actually care about the positions of the previous and the next occurrence of wherever whatever character that we're doing we need to know where the previous occurrence occurred and what index the next occurrence occurred at so uh what we need is a map of characters to indexes so we want to map say for example we want to know that the l maps to a list where it would be index 2 zero one two three four and i'm just gonna say that third l is nine but i probably miss counting but so let's but i know these first two are right um this could be nines could be time to be off by one but yeah we just want to map all the characters to their indexes so like for example the x would map to uh index 0 1 and then whatever those last two positions are whatever these are this could be like 14 15 or something okay and then once we have this map we can actually calculate uh that left and that right number of positions to multiply together to figure out the number of substrings that l is uniquely a part of at that index and then we would just want to sum that up for every character and that's that would be our answer so let's start by creating the hash map of characters to indexes and let's just call this all indexes and we want to loop through our substring or sorry our string that we're given in s so i is less than s dot length plus i and okay so there's a cool method in java that called compute if absent all this is going to do if the key exists it's going to return the existing value and if the key doesn't exist it'll insert our new value and just return our new value and that's useful uh because we'll you'll see okay so uh computer found so what's our key here uh i think we want to get the letter at i and we're gonna map this takes in a lambda function we don't actually care about this key i just like to spell it out because to be explicit um but so this maps to an arraylist of indexes okay and remember what i said that this so what will happen is if this key doesn't exist we're going to return our brand new value it's going to insert our brand new value then it's going to return it and if the key already exists it'll return the arraylist that we added in a previous iteration of the loop okay and then we can just add in the index boom we just mapped all of our letters to indexes now we move on to uh when for the next step we want to loop through all these indexes and then just calculate that left and right multiply it together and sum it up so let's actually declare a little sum variable and let's loop through our indexes so we want a list of integers indexes all indexes and we need to actually look through the indexes so um we could just do and oh actually we need we'd need this variable give me a second okay so we're just looping through the indexes this is size not length and we need to calculate our left variable our right variable and we're going to use i'm going to add code to this later i'm just typing out pseudocode for a second because it helps me think about it a little bit so sum plus equals the left times the right and then we're going to return the sum okay so we only have two lines of code left assuming that we can calculate this left and right variable we're done so let's see if we can get that done so left um so there's one little corner case let's just take this actually let's go ahead and take actually yeah no let's take this just to explain this out okay so this l let's assume that we're on the first occurrence so if i equal 0 then this would be index 2. so let's do indexes.geti but how many so this would be index two but how many positions are there on the left there's one two three so we actually need to add one because it is index two we need to add one to get three so let's add one there and the reason we need to check if it's the first occurrence is because uh for all other occurrences let's say we want to take this or let's say we're on this occurrence we're just going to compare it to the previous one or the previous ones position to get the whatever the left variable is so let's do the let's do that indexes dot get i minus indexes dot get the previous guy the previous occurrence is position okay so that should be done so let's just say this was it let's i'm going to make the map a little bit easier i'll say this was index 2 this would be index 4. so 4 minus 2 is 2 and are there two spots to the left of this l so we're calculating this l so there's one parentheses here one parentheses there that's two so we know this is right okay so moving on to the right side and we're gonna do the exact same thing for the right it's just from the end of the string now so if i is equal to indexes dot size -1 size -1 size -1 we are at the end we're on the last occurrence that which means there's no more occurrences to the right that's why this is a special case um we just want to do the size of the string or the length of the string sorry um minus our occurrence so indexes dot get i so we're just handling this case now from l to x so let's actually i'll make this example even clearer so let's just say this was index zero there's one two three spots on the right that we can place that parentheses on so if there's three spots on the right and the length of this is three minus index zero is three so that gives us the right answer okay so continuing on with the normal case indexes dot get uh i plus no way okay so now what i'm doing here so we're assuming that this is not the last current so let's say we're calculating this guy we're just checking if we're checking how many positions are there to our right side before hitting the next occurrence so then we just have to do index i plus 1 minus dot get i and that should run i think we're done did i forget what did i miss a line 11 oh i forgot a semicolon okay i miss something else what now oh values okay what okay indexes get i what am i missing cannot find symbol famous oh index is i can't spell okay all right now that should be good and now we're done okay so that's the how to do this problem and if you like the video if it helped you out you can um give it a thumbs up or subscribe whatever i'll do more of these and if you guys have any feedback um if there's any more questions you want me to solve go ahead and just comment below and i'll do them um yeah thanks for watching the video bye
|
Count Unique Characters of All Substrings of a Given String
|
chalkboard-xor-game
|
Let's define a function `countUniqueChars(s)` that returns the number of unique characters on `s`.
* For example, calling `countUniqueChars(s)` if `s = "LEETCODE "` then `"L "`, `"T "`, `"C "`, `"O "`, `"D "` are the unique characters since they appear only once in `s`, therefore `countUniqueChars(s) = 5`.
Given a string `s`, return the sum of `countUniqueChars(t)` where `t` is a substring of `s`. The test cases are generated such that the answer fits in a 32-bit integer.
Notice that some substrings can be repeated so in this case you have to count the repeated ones too.
**Example 1:**
**Input:** s = "ABC "
**Output:** 10
**Explanation:** All possible substrings are: "A ", "B ", "C ", "AB ", "BC " and "ABC ".
Every substring is composed with only unique letters.
Sum of lengths of all substring is 1 + 1 + 1 + 2 + 2 + 3 = 10
**Example 2:**
**Input:** s = "ABA "
**Output:** 8
**Explanation:** The same as example 1, except `countUniqueChars`( "ABA ") = 1.
**Example 3:**
**Input:** s = "LEETCODE "
**Output:** 92
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of uppercase English letters only.
| null |
Array,Math,Bit Manipulation,Brainteaser,Game Theory
|
Hard
| null |
249 |
hello guys how are you doing uh so today we are going to solve um problem 249 which is group shifted strings so what we are going to do in this problem so there will be bunch of strings which will be given to us and then we have to group them so they share some common property what is that property so for example if you look here abc if you see the distance between b and a is 1 and c and b is 1 right so this is abc and similarly b and c is 1 c and d is 1 so they both are same in the similarly if i look at z a b they are also same so in this case assume after z a will start again so there will be a rotation so in this problem there are two things which we are going to learn the first thing is anytime any problem comes wherein you have to group things uh together always think of a dictionary so how we are going to solve this problem in this case what we will do is we will form a dictionary and in that dictionary we will store all the results so that will help us with this grouping so for example in this problem what we will do is we will form a key like this so for example look at this abc right so our key will be a to b distance is 1 b 2 is 1 so our key will be 1 okay and then inside this key what we will do is we will store result as a list then we will say a b c now we will look at b c d right so when we look at b c d it is also same b and c is one c and d is one so this will come under abc so we will say b c d now uh look at this x y z so x y z is also same because this is also distance one so we'll club this under x y z so like that we will do and then so for example when you are looking at uh this a to z right so in this case so in a z and b a so this is the same distance because remember here what is happening you are going in reverse direction right like b to a so in that case so key will be uh minus 1 that will be your key right and then you will store results as ba and za so that is how we are going to solve this problem so this is the one concept and the other thing that you have to learn here is there is a concept of rotation so imagine if someone is saying um after z a will come so there is a rotation that you are performing so always remember anytime a rotation thing is there what you have to do is let's say imagine if in this world uh our english alphabets contains only three and if someone is saying uh c plus one or c plus two right so what you have to do is it's a very simple logic you take the length of this which is 3 and then what you will do is what is the index of c it is 2 right and how much they are asking you to move 2 right and then what you will do is you will add the number of elements so number of elements is here 3 and then you take the remainder of it using 3 now look at this is 2 4 3 7 modulus 3 is what is remainder is 1 which is 0 and 1 right so you will get b so that is how in the same way what we will do in this case is we will do plus 26 and then modulate and b6 so that's the quick trick now let's start coding so what we will do is we will first look through this list of strings okay and then the results which we are going to store um so before this let's do this thing from collections import default dict and then list sorry you don't have to do this thing here you will say result is equal to default predict and then list and then here what we will do is once we get the string let's say when we are getting abc what we will do is we'll loop through this each of the characters so i'll say ch in in range and then i'll go from one i'll tell you what's the reason behind going starting from one so that i can take one back character so for example if i'm starting from one then what i will do is i'll take a i'll start from a right so that is how i can do it so in this case what i will do is and let's make a key here so our key will be blank and then what we will do is we will say key plus equal to so the first thing which we are going to do is ord this will give you unicode of all the characters or other thing you can do is you can form a dictionary where you will have a 1 2 a b 2 you can give those numbers but instead of that we can use or d which will give a unicode of it right so what we are going to do here is a string and then ch right minus ord string ch minus 1 because remember we are starting from the second one so we will say ch minus 1 and we have to convert this guy into string that we will do okay and now let's have one more bracket here so as i told you what we have to do is we will just do plus 26 right same thing here plus 26 and then remainder of that 26 so which will be so this will give us a key and then remember what we are trying to do is we are just appending this keys because a to b is one then b2c is one so that will be one so that we are doing and then here at the end what we will do is we will say result and then key dot append and then you can say string and then at the end we will return result dot values i think this thing should solve this problem let's look at it one more time in case of any error from collection default result string yes this is going to solve this problem so let's say let's run this see it is accepted and if i submit it is 40 milliseconds and then don't worry about this because i have noticed i have saw i've saw this solution at 98 percentage also because i think so there is some problem with lead code sometimes see it is now 76 so thank you guys for watching if you like my channel please like and subscribe thank you so much
|
Group Shifted Strings
|
group-shifted-strings
|
We can shift a string by shifting each of its letters to its successive letter.
* For example, `"abc "` can be shifted to be `"bcd "`.
We can keep shifting the string to form a sequence.
* For example, we can keep shifting `"abc "` to form the sequence: `"abc " -> "bcd " -> ... -> "xyz "`.
Given an array of strings `strings`, group all `strings[i]` that belong to the same shifting sequence. You may return the answer in **any order**.
**Example 1:**
**Input:** strings = \["abc","bcd","acef","xyz","az","ba","a","z"\]
**Output:** \[\["acef"\],\["a","z"\],\["abc","bcd","xyz"\],\["az","ba"\]\]
**Example 2:**
**Input:** strings = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strings.length <= 200`
* `1 <= strings[i].length <= 50`
* `strings[i]` consists of lowercase English letters.
| null |
Array,Hash Table,String
|
Medium
|
49
|
14 |
Hello Hi Everyone Welcome To My Channel It's All Very Important Problem Longest River From This Problem Easy But It's Good Like This Problem Is Multiple Times Interview Ravan Subscribe Like This Problem Important Subscribe Now To Receive New Updates Your Being Like Subscribe Comment And Subscribe The Log in to subscribe to torch light protection and fennel like what we can do victory that be reduced to self-sovereignty and subscribe our destroyed but self-sovereignty and subscribe our destroyed but self-sovereignty and subscribe our destroyed but you will like subscribe and the through history and subscribe our like and subscribe which enjoy the and will guide you answer Which is the professor asked for this initial prefix in Solan I don't soft cotton back initially started with flower in the company of flower and flower in its power can be completed within frock suit with full and flower the flowers effects of evil within a specific previous next Will compete with flight subscribe scam in both subscribe is the largest in all three subscribe first dot co dot uk and watch video for this channel subscribe vriddhi string is anti-naxal stress string is anti-naxal stress string is anti-naxal stress nothing in this regard to string don't like this profession thursday Subscribe 8th through all the best will take is will have to do the difference between the lines from 0characters entered in the long run and just this channel subscribe my MS Word relative I labs in traffic jam length that and jewelers in the blank and wash person very tractor Tractor Point To You Later For More Quotes For Subscribe Is Equal To Start Deep Thursday Subscribe From Thee That Aaj Independence Return This Traffic Jasbir Answer So Let's Tried To Run Middle Age Types From This 2002 No DJ To Subscribe My Channel Subscribe to Video Minimum Balance The Length of the Effective Work 9 News Pay Now Hey Here Sud Artists Were Compiled This We Submit This Code Listen You Can See Hidden End Solution Can See The Running Time Character Subscribe Do the meaning of the word from that and s well s d index of the meaning reverse straight stitch from zero initially and which will tree to over all the character index lights S2 not only next to withdraw cases of distinctive wise in next end Will Check Only Minimum Subscribe England Ko The Effigy In This Will Update Minimum Balance Will Update Power Index Oil Slate Pencil And Induction President Vinod Subscribe Button Video Se Little Improve Company Subscribe And Subscribe Like Subscribe And Share This Video You Will Help Us Keep Creating Videos For Top Interview So You Can Practice Friend Problem And Very Important F4 Press Starting Preparation For Coding Interviewer Ayush Suggest Like Button To Facebook Account Top Interview Tagged Problem Digit Code Thanks
|
Longest Common Prefix
|
longest-common-prefix
|
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string `" "`.
**Example 1:**
**Input:** strs = \[ "flower ", "flow ", "flight "\]
**Output:** "fl "
**Example 2:**
**Input:** strs = \[ "dog ", "racecar ", "car "\]
**Output:** " "
**Explanation:** There is no common prefix among the input strings.
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` consists of only lowercase English letters.
| null |
String
|
Easy
| null |
791 |
hey guys welcome back to my channel and in today's video we are going to solve one more lead code question that is question number 791 custom sort string so this is a medium level question and this has been asked by these many companies and that is impressive so let's see what this question is all about so in this question we are given two strings that is order and S where all the characters in order a string are unique and are in sorted order in some custom order previously so they are sorted but in a custom order and we have to permute the characters of string s so that they match the order of the order string now more specifically if a character X occurs before a character Y in order then X should also occur before Y in permuted string and we have to return the permutation of s that satisfy this property so if we see these examples that is order is CBA and S is ABC D the output is CB a d where we can see that CBA a are following the same order that we are able to see in order string and D as it is not present in order string so it can be present anywhere in between or starting or end of the string so the position of all the character letters which are not present in order is flexible we can see the description of this example where it is been written if the character is not present in order then the position can be flexible that is not a concerning thing in this question so we just need to focus on the characters present in s and we need to focus on the order in which the characters are present in order string so the characters that we need to focus are present in s and the pattern or the order that we need to follow is present in order string so let's see how we can solve this question so we are going to use this example so if we see in order a string we are given with BC a f g and in s it is given a b c d so we have to firstly understand what all things we need to focus on so in the question itself there are few charactertics that are given to us so like first thing is that we need to maintain the order of order string correct so the order in which we want all the characters of s or the permutation that we need to form has to be in order of order string so the order part needs to be taken from order string and the character part needs to be taken from s string because at the end we need to return a permutation of s so even though the characters which are going to be present in permutation are going to follow order strings pattern still the characters which are not present in order are also going to be visible in that so that's why we are going to take all the characters from s and we need to focus on the pattern or the sorted order of order rest string so how we can do that so if we see firstly we want all the characters of s so there can be repetition as well because if we see this question it is clearly mentioned that all the characters in order are unique but there can be a possibility where s can have repetition of characters correct so just to eradicate that case what we need all the count or all the frequency of each and every character as well then only we will be able to map them without any anomaly because we even know that even in normal sorted functions if there is suppose a b c d e so we can see that they follow a pattern but all the repetitions are at same place right in one flow so in order to maintain this sorted pattern and flow we need to firstly get the count of all the characters of s so this is the same thing that we are going to do so let's quickly firstly count all the characters of s so we will create a dictionary in which we are going to place our characters where with this diagram so this is our a this is our B this is our C and this is our D and the count of a b c and d are one right for now it's one now what we are seeing now we have the count and the characters of s so now we need to check the permutation which is going to satisfy the given properties so what can be the possible permutation which is going to satisfy the given properties it would be simply the order of order string so we can attend this same pattern by traversing this order string right so firstly we will come up to this place we are saying if this is present in s then take all the counts of it and start making a resultant string so it will go like B then we are going to come to C and we are like is it in this dictionary so yes it is so we will take c as well parall we will also be making them zero so for now I'm just crossing them so that we know that we had already taken these characters so we had Alo taken C so that we don't get confused right so now we will come up to a and we are like is a there in our dictionary so yes it is so we will take a as well and a is count is also one so we are going to add it in our resultant then we are going to check f is f there no f is not there is G is there no G is not there so till this point we have this string correct but is this a permutation of s then no because this doesn't consist of all the characters of surface so for that what we need to do once we are done with the order part we need to append the left out characters so we will again go back to frequency dictionary and we will take the ones which were left out so in this case it is D so we will take D and now our resultant will become B C A and B and D is also only one so we will cross this out and after performing all these operations now we are having this resultant array that we can transform into a string so it will become b c a d and this is our resultant so if we see the output of this example it is same right this is the output so this whole approach and in which we firstly created dictionary because we needed the count of all the characters of s and then we Travers the order string in order to get the sorted pattern of the order string and again we Traverse the frequency dictionary in order to fetch the left out characters which are not present in order because we need to return the permutation of s which will consist of all the characters so this whole approach time complexity is Big of n because firstly we will Traverse this then create a dictionary and then we are going to Traverse this and create a resultant string uh resultant array and after that we are again going to Traverse frequency and add the left out characters so the whole time complexity is going to be biger of N and space complexity is going to be big of n because we are creating this frequency dictionary as well as the resultant so space complexity is also bigger of n so this was the whole approach now let's quickly code this whole solution so firstly we will create our frequency dictionary after creating frequency variable we need to append all the characters of s so for letter in s frequency of that letter will be equivalent to frequency. getet that letter and if there is no such key then petch zero and add one so we are initializing this value as this because we know that there is a possibility that s is going to have repetitive characters so in order to maintain a count and increment its value we are going to get we are going to use get function because we hadn't initialized the frequency with all the values and made it zero so just to take care of that case we have used get letter and zero so if there is no value so it will return zero and if there is a Valu so it will return that value and we will add one into it so after populating of frequency what we were doing now we are going to Traverse through this order string right in order to F the pattern or order of all the characters custom order of all the characters so for characters in order before this we need to create a resultant array because that is where we are going to append our result right so inside this we will simply result. append and what we are going to append frequency of that character into the character why we are doing this because we need to make sure that all the counts or all the occurrences are at same place so this will make sure of that and again to just be sure that there is the character present what we are saying get that character else if it's not there then simply take zero now once we have appended these things in result we need to make sure that we are also updating the frequency as we have already used it so what we will do is we are going to update the frequency of that character equivalent to zero because we have already use the value and appended it in result if it's there and if it's not there then it's not an issue that case will also be handled with value equals to zero right so after doing this thing what we were doing we were now traversing this frequency for letters or letter in frequency because we need to make sure that all the letters are there so again we will do the same thing we will inside this we will do the same thing that is result. append that letter into frequency of that letter and after doing this what we are seeing now return dot join result that's it let's try to submit this so we can see this is working so now let's quickly code Ruby solution in Ruby as well firstly we will initialize that dictionary and after this we will run a for Loop for s. each character do letter so inside this what we will do is we were updating our frequency right so frequency of I think here this is missed so frequency of letter will be frequency of that letter dot 2 I + one so this 2i is doing the same I + one so this 2i is doing the same I + one so this 2i is doing the same thing that we did with get method this will make sure that it's not breaking at that point so after populating our frequency array now we have to Traverse through our order string after populating our frequency dictionary we need to now Traverse through our order string in order to populate the in order to get the custom sorted order before that we will initialize our result which is an array so now what we are saying order dot e character do again letter and inside this what we were doing is we were inserting what we were inserting in our result we were inserting the frequency and the count so this is the letter and its frequency will be frequency of that letter Dot to I if there is no value but if there is then it will be taken and after taking the value we were updating the frequency with zero once we are done with this part we will again Traverse through frequency dictionary so for that we will do frequency. each do letter comma count and inside this now update our result again result will be inserted with letter into frequency of that letter once we step out we are saying return result do join that's it so now let's check whether this is working or not let's submit this so we can see that this is also working and both the solutions are accepted and they are working absolutely fine passing all the test cases and I hope this explanation was useful for you all and if it was then you can like this video subscribe my channel and I will soon come up with more such questions till then keep messing with algorithms and thanks for watching
|
Custom Sort String
|
split-bst
|
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**.
|
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
|
Tree,Binary Search Tree,Recursion,Binary Tree
|
Medium
|
450
|
1,774 |
hey what's up guys uh this is sean here so this time 1774 closest dessert cost um so for this one uh you give you would like to make a dessert and are preparing to buy some ingredients so you have an ice creams uh based flavors and you have types of toppings to choose from and so to make ice cream you need to use at exactly one ice cream base and then you can add any number of typings you want from zero to two more okay and there are like at most two of each typings so and you're given like uh some inputs basically you have three inputs so the first one is the base cost right so it basically it tells you each cost for each space flavor and then the cost for each of the toppings and then target and your task is to find the closest possible cost of a dessert to a target and if there are multiple ones basically if the difference is the same we need to return the lower one basically who has a smaller total cost will be the ones we want to return right so that's why we have so for example we have seven three four so target is 10 and in this case you know we can get exactly 10 right that's how we uh we just return 10 here and here's another example here we have target 17 is 18 we have 17 here we need to return 17. and this one example three here so here's give us like a example like where we have two costs that can give us the same difference which is 8 and 10 here so both of them will have the difference equals to 1 right but in this case we want to return 8 because 8 is smaller than 10. right and for this one we have 10 yeah because but basically we only have one uh one base right and since we need at least one base right that's how that's why we have 10 here so and the constraints and then m is pretty small which is 10 right so which means that you know for this kind of problem you know we can most likely do a brutal force right so we can simply try all the possible ways to make an ice cream and among all of them we just maintain the biggest sorry the target right we maintain the best target we can get and that's it right so i mean to try to enumerate all the possible uh combinations of ice cream and the toppings you know i think there could be multiple ways but for me i just uh do this basically i have an answer equal to zero equals to sorry it goes to the uh system.max size okay and so for me i just do a base right so i enumerate the base first because we need the base and regardless right then for each of the base given like given the current base i just try all the possible toppings scenario okay so basically i'll do a dfs of zeros you know i'm going to create like a dfs method so we're going to have like two parameters so the first one is topping index right and the current one is the current cost so that's how we i enumerate all the possible toppings right and at the beginning since we need a base regardless that's why the initial cost for this current dfs is going to be the base right and yeah so basically every time when we have like a cost here right we want to maintain that right we want to maintain we want to check if this cost can give us a better answer so which means that if right i'm going to do this basically so the if abs of current cost minus target right is smaller than the uh since uh we're using this answer to store the uh our best cost right and abs of the answer minus target right if that's the case right we want to basically update the answer or what so this is the smaller case there's another case which is the tie right so for the thai case or if these things is the same right and the current cost is smaller than the target then we also want to update the answer so we have the answer equals to the current cost right because i'm since here i'm only using one variable to maintain that you know you can also have like another difference variables to help you calculate this one but i think this one variable will be enough yeah so i think that's that and we can also have like some early terminations here you know for example you know if the current cost equals the target right then obviously you know i think actually we can put this one on the right on the very top here basically if the current one is the same as target you know we know okay we find the best answer already right so it's going to be a current cost and then we simply we can simply return from here right but i think this one is not uh mandatory because i think this one will also take care of that it's just here it's like just like early termination to help us to make this program run a little bit faster right so early termination right termination and another one is like this basically you know the uh so after the current one i mean if after calculating the current the answer here you know if the current cost is greater than target right so we also return because if the current is already greater than target there's no point to continue adding the toppings on it because the difference will become bigger and bigger since we're going to get the closest one right no need to add more toppings right and then up here we try to add toppings right so how do we try that you know since we can add either zero or more toppings right and for each of the toppings we have like uh we have at most two toppings we can add right so which means that i'm going to have like a four loop here in range of three so this one basically i'm looping through the toppings right for the current topping index right i'm trying to add uh either zero or one or two toppings on top of uh for the current index basically that's why i have dfs of topping index plus one right and then i have a uh so i have current cost right plus what plus the topping cost of topping index times i so this is how i basically so this for loop can give us all the possible con combinations of the toppings right because for the current toppings here you know if we so when i equals to zero it means that we're not adding current toppings right or we're adding like one uh one top or one count for the current toppings or where we add two right and then up after that you know we try the next toppings right for the next toppings we also try uh at zero at one or add two so on so forth okay and yeah so i guess okay so for the non-local okay to update the answers i'm non-local okay to update the answers i'm non-local okay to update the answers i'm going to have none local here answer here so i mean here i simply return the answer in the end i think this will this should work if i run the code index auto oh yeah so we also need to add another like termination point here basically in whenever if the topping index equals to the length of toppings right sorry otherwise you know we have like a index out of range arrow here we also return here okay and the reason we added here below here instead of at the beginning is because you know after basically after consuming the current let's say after consuming the last toppings here you know if we break at the very beginning you know we'll not basically process that last toppings result right because our check logic is here that's why we have to always we for each of the costs here we always want to uh process the cost first before uh doing any of the return here okay cool so if i run the code accept it right yeah there you go right so basically you know we simply try all the possible scenarios here you know for each of the scenario here we have i mean the time complexity i mean the uh so we have like in here let's say it's the is the 10 here so for each of the n here we have what um we have four loop here right so we have three here we have three different scenarios here and basically it's going to be a 3 to the power of 10 right because for each of the scenarios here we're going to have three scenarios here and for each of the one we also have a three basic three times three and then we have another ten basically i think this is the time complexity for that yeah cool so i mean that's it right so for this one you know since we there's no odd better or greedy solutions to solve this problem and also given this kind of small constraints here right uh we'll just uh basically try all the possible uh combinations to make a dessert right so first we tried each of the base and for each of the base we use the dfs to try all the topping scenarios and for each of the costs we're going to calculate the uh the final and the final result right and then and we have some like termination early termination here i believe i think i can remove this one this should also work yeah basically this one is not necessary right i'm just simply add it here but it will not affect our final answer and here is like the main logic to try all the possible toppings from zero to two right and for we do this for each of the toppings yep i think that's pretty much i want to talk about for this problem and yeah again thank you for watching this video guys and stay tuned see you guys soon bye
|
Closest Dessert Cost
|
add-two-polynomials-represented-as-linked-lists
|
You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no toppings at all.
* There are **at most two** of **each type** of topping.
You are given three inputs:
* `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the `ith` ice cream base flavor.
* `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the `ith` topping.
* `target`, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to `target` as possible.
Return _the closest possible cost of the dessert to_ `target`. If there are multiple, return _the **lower** one._
**Example 1:**
**Input:** baseCosts = \[1,7\], toppingCosts = \[3,4\], target = 10
**Output:** 10
**Explanation:** Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.
**Example 2:**
**Input:** baseCosts = \[2,3\], toppingCosts = \[4,5,100\], target = 18
**Output:** 17
**Explanation:** Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
**Example 3:**
**Input:** baseCosts = \[3,10\], toppingCosts = \[2,5\], target = 9
**Output:** 8
**Explanation:** It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
**Constraints:**
* `n == baseCosts.length`
* `m == toppingCosts.length`
* `1 <= n, m <= 10`
* `1 <= baseCosts[i], toppingCosts[i] <= 104`
* `1 <= target <= 104`
|
Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head.
|
Linked List,Math,Two Pointers
|
Medium
|
2,21,445
|
462 |
Hello guys, if we do it then we will make an equal agreement on the minimum balance of the sheet. This is the question of which cash account will we do, what we have to do in this is that we have a career and I have a life and we have to modify it in such a way that whatever we have The head element of hair should be equal to us and modify is to add that we have to give minimum our to make any judgment on us, I forgive the ghee and show it to us like potatoes, it comes to us want to AFreak 2018 The camera is saying and to the face One more thing is to do this so that I take minimum number of steps. If I look at it equally, then what do I have, do this, first I make this point free in which I have a but, friends, Facebook Twitter said Navratri and then I do this. I will give it for free, I will make it rocky path, so my introduction is all in one request, by the way, you are my boy, I made 3 step 3 sets here, which I made one two three and put it there, it is my friend who made main two three and put it here. My inch is so candy crush application on the phone electronic equal to three so my here in 3 states where the minimum so I and that they will see I have and any one I can do to minimize this what else can be the most What will I do first, I will take the ₹ 3 lakhs here, Gurjar noose, I will take the ₹ 3 lakhs here, Gurjar noose, I will take the ₹ 3 lakhs here, Gurjar noose, please first, the loot here is death, it is a challenge, then the PM friends, if I break it like this, then mine, how many steps did it take for both of them. To make extract will go to one step in making cheese Urdu and this Meerut minimum which is the time see this is our question now here sugar can return here approach on 20 years see not solved these pictures are shown but to the owner one by one Set what I first light look alike beneath open to search here and I will not break the praiseworthy morning itself Shayari reflects my own which I will shoot you now what should I say I will account that only the biggest element is in this account When I went to Mother Teresa, she could only make a paste on me, it would take some tips and steps, plus first I will check that you are ok, how many steps will it take to make grocery, if I do like this, then I will have a problem. In this, my your tiredness gallop from here, whatever is there will be my gift, in these, we will be soft in this recipe, minimum stupid, maximum development problem, I can do a lot, so I will put maximum Pushp Meghnad on the approaching media and in it for very 20 minutes of our hair. He cares, I only upload that, this is my vote element, limited like this, and this is my vote element, and this is my wretched way to increase, what do I say? First of all, I am sorry, we want it back. Central Chronicle fired me from the interviewer, now what do you do with me? You have to do what you want, if it happens at all, then you can do more or less, that you are like it, when the media has done it, we have determined its value according to everyone, I will use it once, an introduction - bitterness. And I will use it once, an introduction - bitterness. And I will use it once, an introduction - bitterness. And I will immediately add idols, pregnancy care, cement, now I will go to the last and do this - this is what will happen to me that if I this - this is what will happen to me that if I this - this is what will happen to me that if I send a video system message, then I will have deep pockets of cash, this is a pimple application which told me that you have so many minion rush requests and write accordingly. It is difficult that it will take some time to call me dad, what is my method of using walnuts and chillies, aside from the first wedding gift question, 24 carats, you will have to request first, if you will not do the shot, then the answer is no, if I am as much as you When I have shot it and what will I do, I will tell in Hari Delhi, I will give this enrollment and on that center element my favorite admits that in the meaning of that, I will do Math - I will do that - then I will do Math - I will do that - then I will do Math - I will do that - then I will have to do the dongri of the adapter that stop my fund transfer. The same order of mine - will be clear in transfer. The same order of mine - will be clear in transfer. The same order of mine - will be clear in which when the co-worker saw the mother which when the co-worker saw the mother which when the co-worker saw the mother reached the school premises, she would hurry up and name name se tire naam, I don't want to do that what was my decision yesterday morning, that party - - - Center will be upset by this and here's which is going absolutely fine and I'll play something and show her this one which I did like a test, move it here, the school has banned skirts 21 year old Prosperity has happened and towards it I know why we started our business and today my heart is happy so I hope you all will try. See you in Next 9 News Room. Thank you.
|
Minimum Moves to Equal Array Elements II
|
minimum-moves-to-equal-array-elements-ii
|
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_.
In one move, you can increment or decrement an element of the array by `1`.
Test cases are designed so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** 2
**Explanation:**
Only two moves are needed (remember each move increments or decrements one element):
\[1,2,3\] => \[2,2,3\] => \[2,2,2\]
**Example 2:**
**Input:** nums = \[1,10,2,9\]
**Output:** 16
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Math,Sorting
|
Medium
|
296,453,2160,2290
|
737 |
hello guys now let's try to solve the sentence similarity to problem there's a statement given to sentence words one word to each represented as a ray of strings in the list of similar world's payers determining if two sentences are similar for example what when you go to great acting skills in the worst you find drama talented are similar if the similar word pairs of hairs great good fine good acting drama skills can't known as similarity relation is transitive for example if great and good are similar and a fine good are similar then created a fire similar similarity is also symmetric for example great can define being similar is the same as fine and great being similar also worded always similar with itself example sentences words one great words to great pairs empty are similar even though there are no specific assimil similar words pairs final reason this can only be similar if they have the same number of words so a sentence like words one great I can never be signature was to double plus good okay so the algorithm we are like this first we check if the two even words have the semblance if not which I'll return force and then we will compare the words a pair by pair if the they are the same they will continue compare if not then we will try to check if there are similar words in their Paris so how to quickly check if they are connected which means they have the similar relation there are very intuitive sin canes to build a graph basically this is a graph problem as their transitive so we can do the depth-first search you check her given depth-first search you check her given depth-first search you check her given two words whether they are the similar so basically this is a checklist with their two words are connected in the graph so we can use them for search or we can use the Union find in this solution we use that first search okay so let's do it so at first if words one don't let's not equal two words two dollars I just don't tell fourth yes I will call a build graph function Q it'll work so how do we represent a graph we will use agency list and the father first you check if the contents in the graph we will use a hash map and hash Senate because scissor as Antarctica compare will be constant at you the Kappa word so the key will be Street and the dope value will be stream set your hash map and then we will build graph will pass there pairs and grow and there's n for we are getting the numbers will be the words one doughnuts and for each I go to 0 I less than um if their words well what's one I get course choose our words to I just continue because they are the same and if is that we're doing that first search to see if they are connected so we will pass the words one i and their words to I and the graph also as we build this graph we will pooches up there are two words into the graph so we need another visitor set to check if we already beat you or we will you will have this there overflow problem so when you hash the visitor dated or upset so if we will not find an adjuster certainly return course finally return to so let's implement of the two functions which is our beautiful graph in a we will pass their three pairs then we also like to pasture wrap okay for each pair in their pairs we are to put your if absence the pair 0 because it's the other see Mary symmetric so we will put her both of these two into our graph you have set it is an capture the pair 0 there's a pair 1 the same two catches our pair 1 that is our pair 0 ok now we built this graph yeah we were implemented a professor Sheraton capture the adapter search we're gonna have two people here because we were Chinese they're connected and they're the worst one in the work to and wrap also we need a hashtag that's a map editor or do we have built it so basically if it was our cheek scissor s1 equal to not 4g cap scissor s1 stop sighs he ho to zero we will never find it so just a return towards an LS if the G gets the s1 directly contents the as to will return true if no case we will check the neighbors of the s1 for every neighbor on the cheek L so that s one way out to the deaf or such a spirited content we just use the out if from lately add equal to the force will return or just continue if the neighbor is chose maybe they have the beach rate adjusted to the death for such if the EFS the neighbor a to G and the ability the equal to true adjuster return to if all of them we have unluckily so just a little close in the end okay sink your voice you see you next time
|
Sentence Similarity II
|
sentence-similarity-ii
|
We can represent a sentence as an array of words, for example, the sentence `"I am happy with leetcode "` can be represented as `arr = [ "I ", "am ",happy ", "with ", "leetcode "]`.
Given two sentences `sentence1` and `sentence2` each represented as a string array and given an array of string pairs `similarPairs` where `similarPairs[i] = [xi, yi]` indicates that the two words `xi` and `yi` are similar.
Return `true` _if `sentence1` and `sentence2` are similar, or_ `false` _if they are not similar_.
Two sentences are similar if:
* They have **the same length** (i.e., the same number of words)
* `sentence1[i]` and `sentence2[i]` are similar.
Notice that a word is always similar to itself, also notice that the similarity relation is transitive. For example, if the words `a` and `b` are similar, and the words `b` and `c` are similar, then `a` and `c` are **similar**.
**Example 1:**
**Input:** sentence1 = \[ "great ", "acting ", "skills "\], sentence2 = \[ "fine ", "drama ", "talent "\], similarPairs = \[\[ "great ", "good "\],\[ "fine ", "good "\],\[ "drama ", "acting "\],\[ "skills ", "talent "\]\]
**Output:** true
**Explanation:** The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.
**Example 2:**
**Input:** sentence1 = \[ "I ", "love ", "leetcode "\], sentence2 = \[ "I ", "love ", "onepiece "\], similarPairs = \[\[ "manga ", "onepiece "\],\[ "platform ", "anime "\],\[ "leetcode ", "platform "\],\[ "anime ", "manga "\]\]
**Output:** true
**Explanation:** "leetcode " --> "platform " --> "anime " --> "manga " --> "onepiece ".
Since "leetcode is similar to "onepiece " and the first two words are the same, the two sentences are similar.
**Example 3:**
**Input:** sentence1 = \[ "I ", "love ", "leetcode "\], sentence2 = \[ "I ", "love ", "onepiece "\], similarPairs = \[\[ "manga ", "hunterXhunter "\],\[ "platform ", "anime "\],\[ "leetcode ", "platform "\],\[ "anime ", "manga "\]\]
**Output:** false
**Explanation:** "leetcode " is not similar to "onepiece ".
**Constraints:**
* `1 <= sentence1.length, sentence2.length <= 1000`
* `1 <= sentence1[i].length, sentence2[i].length <= 20`
* `sentence1[i]` and `sentence2[i]` consist of lower-case and upper-case English letters.
* `0 <= similarPairs.length <= 2000`
* `similarPairs[i].length == 2`
* `1 <= xi.length, yi.length <= 20`
* `xi` and `yi` consist of English letters.
|
Consider the graphs where each pair in "pairs" is an edge. Two words are similar if they are the same, or are in the same connected component of this graph.
|
Array,Hash Table,String,Depth-First Search,Breadth-First Search,Union Find
|
Medium
|
547,721,734
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.