Transcript for:

data structures and algorithms are an important aspect of every coding interview this algorithms and data structures course will teach you everything you need to prepare for placements coding interviews and logic building this course walks you through multiple Java algorithms data structure problems and their Solutions with step-by-step visualizations so that you're actually learning instead of blindly memorizing Solutions daesh varani created this course he is an experienced Cloud engineer at Google Hello friends do you want to learn data structures and algorithms through animations and implementation so that you can crack the coding interview hi my name is Danes varani and I am your instructor for this course I have over 10 years of experience as a full stack developer through this course and by other means I have helped over thousands of students just like you to improve on data structures and algorithms SS so through this course you will learn about singly link list W link list circular singly link list AR is Stacks Q's binary tree binary heaps graphs Matrix tries we will also look into its implementation by coding the algorithm in ide and what else you will get much more than that through this course so friends what are you waiting for you can go to this playlist link provided in the description of the video where you will find all the video videos that are part of this course I update this playlist daily so the only help I need from you is in case you like any of these videos then please share this playlist with your friends and colleagues and please subscribe to my channel it will only motivate me to add more and more videos into this playlist so friends let's move ahead and begin this course thanks have a nice day hello everyone so in this section we'll discuss about a basic introduction to data structures so what is data structure structures so if you see it is a way to organize the data now what do we mean by that is when we want to program anything and we have a huge amount of data so we basically take the help of data structures to organize the data into the memory so why we organize the data it's because after organizing the data it becomes very easy to process it now what do we mean by that is if we have an organized data we can very much efficiently access and process it so here let's say if we take an example let's say if you go to a library where you find this unorganized books now if someone ask you that bring a book related to algorithms from this unorganized books of let's say any particular author so now here you can see that as books are unorganized there is a problem because in order to find a book related to algorithm for a particular author you need to find that book in this unorganized books so it will take a lot of time to find that book now let's say if this unorganized books are basically organized like this in a particular shelf and now if somebody asks you that go and find a particular book related to algorithms of a particular author so it would be very easy for you you will just go to that particular section where the books related to algorithms are kept and you will just find that book so here you can see that books can be related to the data and when we organize these books you can similarly relate it to the data structures where we are simply organizing the data so that it becomes easy to process it so this is the basic introduction about what is data structures now let us see what are the types of of data structures so basically there are two types of data structures linear and nonlinear now when we talk about linear data structures they have the data elements arranged in a sequential Manner and they are arranged sequentially so that each member is connected to its previous and next element and as they are connected sequentially it becomes easy to Traverse them and usually the traversal is a single level now these type of data structures are very easy to implement because they are stored sequentially in the memory so some of the examples of the linear data structures are as follows so here if you see array link list stack and Q so these are the linear data structure where the elements are stored sequentially and mostly they are single level so the other type of data structure is nonlinear data structure so if you see see by this term nonlinear we mean that the data element inside these data structures are not in sequence they're basically connected to one another through different paths and as in linear data structure they were single level here they're basically stored in multi- level and as they are multi level so in order to Traverse each and every element in this nonlinear data structure takes some amount of time now as they're multi- level in order to Traverse each and every element in this nonlinear data structure is bit difficult and compared to linear data structure they are not easy to implement so some of the example of nonlinear data structures are tree and graph so here if you see if you take an example of an array the data is arranged sequentially and it is basically in a single level so we can Traverse it sequentially so it is very easy to implement but here if you see that nonlinear data structure are multi-level so here it's an example of a tree where the topmost element is the root so here if you see these data elements are connected through multiple paths and they are in multiple levels so here we discussed about the data structures and we also discussed about the types of data structures which is linear and nonlinear in linear few examples are array link list stack q and in nonlinear We have tree and graph so in our upcoming videos we'll discuss more about the array link list stack Q tree and the graph data structures so I hope you like this video thanks have a nice day hello everyone so in this section we'll discuss about a basic introduction to algorithms so what is an algorithm so if you see the formal definition of algorithm an algorithm is a set of instructions to perform a task or to solve a given problem so what do you mean by set of instruction is that let's say we are given a problem so there would be a sequence of steps or there would be a set of instruction if we follow that our given problem will be solved so let's say for example we are aware of a recipe book so it is nothing but a collection of recipes in which each recipe provides an step-by-step instruction to prepare the food so let's say if someone ask you that provide me the recipe to prepare a tea so basically the steps inside that recipe would be the first step would be that we need to boil water second would be put tea in the teap pot the third step would would be that put that boil water into the teapot so after adding the hot water the fourth step would be that as we have hot tea so we just put that hot tea into the teac cups so the fifth step would be that do you need sugar so there is a choice if yes then put that sugar into the teacups and if no then do nothing and the last step would be stir drink and enjoy the tea so here if you see that this recipe of preparing a tea is very much similar to an algorithm which is nothing but set of instructions which help us to solve a given problem so here let's say we take an example that we want to print the average of three numbers so we are given three numbers and we want to print the average of it now let's say you want to write an algorithm to solve this given problem so the steps you would provide would be first you will perform the sum of three numbers store that sum into a variable by name sum divide the value stored in sum by three and store the value into a variable average and finally print the value stored in the average so this would be the sequence of Step which you would perform to print the average of three given numbers and this set of instruction is nothing but an algorithm so here if we transform this five steps into the code then here we have a method find average where we are given three numbers a b and c so we perform the sum of three numbers here we store it in a variable sum so here we are storing it here then we are dividing the sum by three so whatever the value is there in sum we are dividing it by three we are storing the value in variable average here and finally we are printing the value stored in average here so this sequence of steps is nothing but an algorithm and usually when we are given a particular problems we derive the sequence of steps and then we try to implement it in particular language and write the logic around it and finally after performing all the steps properly the given problem is solved so friend this was the basic introduction to algorithms in our upcoming videos we will discuss the algorithms and data structure in great detail I hope you like this video thanks have a nice day hello everyone so so in our previous section we discussed about a basic introduction to algorithms and data structure now in this section we'll mostly discuss about the analysis of algorithm so what do we mean when we say analysis of algorithm so before that we saw in our previous section that an algorithm is a set of instruction which we use to perform a task or to solve a given problem so when we talk about analysis of algorithm this set of instructions are very much important and why they are important because in order to solve a given problem there can be several different algorithms so our analysis mostly deals in finding the best algorithm which runs fast and takes in less memory so why we actually do that because let's say we are given a problem and we have two to three algorithms to solve that problem but out of the three algorithms one algorithm let's say takes 1 second the other takes 5 seconds and the third one takes 10 seconds and similar with the memory so we usually do analysis of those three algorithms and we take that algorithm which takes the less time because if we take an algorithm which takes more time then slowly our system will degrade and we have this performance issues so let's say for example we are given a problem to find sum of first and natural numbers so then natural numbers would be 1 2 3 4 5 6 and so on so to our method we are given a value n and we want to find its sum so let's say if we input n equal to 4 so the output we get is 10 that is 1 + 2 + 3 + 4 so 1 + 2 gives 3 3 + 3 gives 6 and 6 + 4 gives 10 so this is the sum of first four natural numbers and similarly let's say if we input n equal to 5 then we get output as 15 so when we do 1 + 2 we get 3 3 + 3 we get 6 6 + 4 we get 10 and 10 + 5 we get 15 so this is the sum of first five natural numbers now let's see we want to solve this problem and let's say we have these two programmers who come up with their own algorithms so rames comes with one of the algorithm and sures comes with yet another algorithm so here Ramesh is trying to find the sum of first and natural numbers using the mathematical formula which is n into n n + 1 by 2 so here let's say if we input n = 5 so it will be 5 into 5 + 1 by 2 so 5 + 1 is 6 6 / 2 is 3 and 5 into 3 gives 15 so this is the mathematical formula which is directly using to find the sum of first and natural numbers and here Sur has written one algorithm which is what we discussed in our previous slide that 1 + 2 + 3 + 4 + 5 so what he's actually doing is he's creating a variable sum initializing it with zero and is providing a for Loop which starts from one so here I equal to 1 and this I will go till it's less than equal to n and once this statement gets executed we are simply incrementing I by 1 so let's say if we input value of n as 5 so the start sum will be zero so when this for Loop will start execution I becomes one and we check that 1 is less than five or not so it is less than five then we simply add zero with 1 because sum initial value is 0 so 0 + 1 becomes 1 and 1 is assigned to sum now after this line we increment I by 1 so I becomes two we check with 2 2 is less than 5 or not so 2 is less than 5 the value of sum is 1 so we do 1 + 2 we get three we assign three to the sum now then we increment I by 1 so I becomes 3 we check whether 3 is less than equal to 5 or not so it is less than equal to 5 so now as the value of sum is three we do 3 + 3 we get six we assign 6 to the sum now so sum becomes 6 then we simply increment I by 1 so I becomes 4 4 is less than equal to 5 so sum value is 6 we add 4 to it so 6 + 4 gives 10 and 10 is assigned back to sum and then we again increment I by 1 so I becomes 5 we check whether 5 is less than equal to 5 or not so I is less than or equal to 5 so so some value is 10 we add five we get 15 we assign 15 to Su and then we increment I by 1 so I becomes six so now here you can see 6 is not less than equal to 5 so this for Loop terminates and the whatever value we have in sum we simply return so the value of sum is 15 so we simply return 15 so friends here you can see these are the two algorithms which can solve our problem of finding the sum of first and natural numbers but there is no way to figure out that which algorithm is better than other so in order to determine the best algorithm among these two algorithms we usually check two things one is the time complexity that how much time this algorithms are taking to complete and another is the space complexity that how much memory this algorithm is taking to complete so here in this section we discussed about the analysis of algorithm and its formal definition in our upcoming lecture we'll discuss more on what is time complexity and what is space complexity I hope you like this video thanks have a nice day hello everyone in our previous section we discussed about the analysis of algorithm and we also discussed that there are two complexities which decides that how best is the algorithm so one is the time complexity and the other is space complexity so in this video we will discuss about the time complexity of an algorithm so what do we mean by time complexity so in the simplest terms that is the amount of time taken by an algorithm to run so let's say we have written an algorithm and we try to execute so when that algorithm finishes the amount of time taken by algorithm determines our time complexity so here usually an algorithm takes in an input and in order to process that input some amount of time is taken so an efficient algorithm will try to process the input very fast and a non-efficient algorithm will take some more time to process the input so this processing of input by an algorithm helps in determining the time complexity so here in our previous example where we have this two programmers rames and sures who have written these two algorithms so here the input is same for both the algorithms but here rames is calculating the sum of first and natural numbers using the mathematical formula which is directly putting the values inside this formula and returning the sum of first 10 natural numbers whereas here if you see that whatever value of n we are providing we are simply running this statement that many times so in for Loop it is running from one to a value less than equal to n so here let's say if the value of n is very large this statement will run that many times so the time taken by this algorithm will be somewhat More Than This algorithm because here we are processing an input based on a for Loop where where this line is executing n number of times and here we are simply using the value of n into this formula which is directly rning as the sum of first 10 natural numbers so definitely this algorithm will be more efficient than this algorithm because the time taken by this algorithm will be less as compared to this and we'll also discuss more about how to calculate this time complexity in much greater detail in our upcoming videos but for time being we just analyze that this algorithm will be much better than this algorithm because here there is only one statement which is a constant statement and here we are iterating in a for Loop where this line gets executed for n number of times because this Loop goes from one to less than equal to n so let's try to execute this code in eclipse and see that how much time these algorithms are taking so friends here you can see that we have written this both the algorithms and inside our main method we are simply calling this find some method now here what we are simply doing is when we run this main method we are storing the current time in this variable then we are executing our find sub method and at the last we are again calculating the current time and we are simply subtracting this time so we can get the time taken by this algorithm and if you see it gives the time in Mill seconds so if you run this algorithm with a very large value of n you will find it will take almost no time because this is only a single statement where we are providing this value of n into this mathematical formula so if I run this so this is the sum of first and natural numbers of 99,999 and here you can see the time taken is almost 0 milliseconds now let's say if I commment this part and I uncomment this so now if I run this algorithm again so now this algorithm will be executed so here you can see the answer is the same but the time taken is almost 2 milliseconds so here you can see that though we have this two algorithms which solves our problem we usually do the analysis of the algorithms to get the best algorithm out of the options and also friend calculating the time taken by algorithm by this is also not good idea because this depends on machine to machine so it is just giving us a rough estimate about the time taken by these algorithms but when we do analysis of algorithm there are different mathematical tools which can help us determining the time complexity of an algorithm so this was all about the time complexity of an algorithm I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about the time complexity of an algorithm and we will discuss more on this in our upcoming videos so in this video we will discuss about the space complexity of an algorithm so the first thing which comes into our mind is what is space complexity so in simple terms you can say that space complexity is basically the amount of memory or space taken up by an algorithm to run so friend let's say we have this two algorithm written by two different programmers rames and Sur now in order to determine that which is the best possible algorithm one constraint is the time complexity which we discussed in our previous video the other is the memory required to process the input by an algorithm basically helps in determining the space complexity so usually we even measure that how much space this algorithm is taking and how much space or memory this algorithm is taking and whichever is taking the less memory we simply choose that algorithm because when we run this algorithms with a system having so many users it may happen that our memory get exhausted so we try to fit in the best possible algorithm which takes less memory so here when we calculate the time and space complexity we never go into the exact numbers there are certain mathematical tools which help us in determining the time and space complexity of an algorithm and we usually term them ASM totic analysis of an algorithm in our upcoming videos we will discuss more about the ASM totic analysis and its notations and we will also discuss that how we can use those mathematical tools to determine the time and space complexity of an algorithm I hope you have liked this video thanks have a nice day hello everyone so in our previous videos we discussed about the time complexity and space complexity of an algorithm we saw how time and space affects the performance of an algorithm but usually we don't go by the exact numbers that how much exact time an algorithm is taking or how much space in numbers an algorithm is taking so usually there are mathematical models which help us in determining the time and space complexity of an algorithm and the analysis which deals with those mathematical models we term it as asymptotic analysis so what do we mean by asmic analysis asmic analysis helps in evaluating the performance of an algorithm in terms of input size and its increase so let's say we have given an algorithm with certain input size we use this asmic analysis and determine the performance of an algorithm so this study also help us in determining let's say if the input size is less then how much time the algorithm is taking and if we increase the input size then how much time or space the algorithm is taking so usually when we do this ASM totic analysis we don't actually measure the actual running time of an algorithm this analysis simply help us in determining that how time and space taken up by algorithm increases with the input size so as we already discussed that if the input size to an algorithm is less then less time and space will be required by the algorithm to process that input and if we slowly increase the size of the input usually the time and space will also increase so this ASM totic analysis help us in determining that increase and also when we perform this analysis there are certain notations which we need to know to perform the ASM totic analysis so we'll discuss about the ASM toting notations in our upcoming videos so in this video we simply discussed about the a basic introduction to ASM totic analysis in our upcoming video we'll discuss about the asmic notations and the types of asmic notations I hope you like this video thanks have a nice day hello everyone in our previous video we discussed about the ASM totic analysis and we also discussed about its basic introduction that asymptotic analysis help person Det determining the runtime complexity and space complexity of an given algorithm so usually this astoic analysis is being done by asmic notations so what do we mean by ASM totic notations so if you see the definition of it asymptotic notations are the mathematical tools used to describe the running type of algorithm in terms of its input size so here we will discuss more on this mathematical tools that what are those and how it helps in determining the running time of an algorithm so in order to understand about this ASM totic notations we'll take an example let's say you go to a car showroom where you want to purchase this car so the mostly you will look into the design of the car and to the salesman you will ask one most important question is is what is the performance of car in 1 liter of petrol that how much this car travels in 1 liter of petrol so basically the salesman will never give you an exact answer he will simply give you the numbers based on certain conditions the car is running so it will simply tell you that if you're running this car on Highway where the traffic is very minimum this car can give you a mileage of 25 km per liter and if you running it in a city where the traffic is Max it will give you 15 km per liter and let's say if you running for some amount of time in city and then in Highway which means you are encountering an average traffic so it will give you around 20 km per liter so these are the three answers where salesman might give you when you ask about the performance of car in 1 liter of petrol so when we talk about an algorithm this ASM totic notations give us this rough idea that how an algorithm will be performing in certain situations so here the ASM totic notations help us in determining the best case average case and the worst case so you can simply relate this analogy to these conditions that best case would be that if you're driving on a highway the average case would be that you're driving in both City and Highway and the worst case would be that you are simply driving in the city so this is how asmic notations provide us an in-depth description about the running time of an algorithm in terms of its input size so in our upcoming videos we'll discuss that what are the ASM totic notation types and how we can use those types to determine the running time of an algorithm in terms of its input size I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about ASM totic notations and we also discussed that how ASM totic notations help us in determining the running time of an algorithm in terms of its input size and we also discussed that asmic notations help us in determining the best case average case and the worst case and we also saw an example of an car that how the performance of car in one liter of petrol differs in different situations so similar analogy is being performed on the algorithms where we determine the best case average case and the worst case so there are types of asymptotic notations which determine these three cases so here you can see that there are three notations for performing the running time analysis of an algorith lthm the first notation is the Omega notation which is being denoted by omega symbol the second is the bigo notation and the third one is the Theta notation so let's discuss about the Omega notation first so if we see the definition of Omega notation so this notation basically expresses the lower bound of an algorithm's running time now what do we mean by the lower bound of an algorithm's running time so basically lower bound means that for any given input size this notations determines the best amount of time an algorithm can take to complete so by best amount of time we mean the lower time so therefore we denote it by lower bound and this determines the best case of an algorithm because Omega notation provides us the best amount of time an algorithm can take to complete so as we already discuss that this is the best case analysis of an algorithm so what do we mean by best case let's say for example if you have written certain algorithm and if we say that algorithm takes 100 second as the best amount of time so what do you mean by that is that 100 seconds will be the lower bound of that algorithm and the algorithm can take more than 100 seconds to complete but it will not take less than 100 seconds to complete so the best case analysis takes the lower time and provide us with the information that a particular algorithm will take minimum let's say 100 seconds but will not take less than 100 seconds it can take more than 100 seconds but as the lower bound is 100 seconds it will be the best case for that algorithm so this notation is very least used because we are not interested in finding the best amount of time algorithm can take but this notation basically provides an information that what's the minimum resources we need to run this algorithm the other notation is bigo notation so this notation expresses the upper bound of an algorithm's running time now what do we mean by upper bound upper bound means that for any given input size into an algorithm this notation determines the longest amount of time the algorithm may take to complete now what do we actually mean by the longest amount of time let's say for example that if we say that certain algorithm takes 100 second as the longest amount of time so 100 second will be the upper bound of that algorithm in bigo notation the algorithm may take less than 100 second but it will not take more than 100 seconds so this is very opposite of the Omega notation so when we say that 100 second is the longest amount of time that algorithm may take to complete then that would be the upper bound the algorithm may take 90 seconds 80 seconds but it won't take more than 100 seconds so this notation is mostly used because we are very much interested in finding the maximum amount of time the algorithm may take to complete so that we can optimize that algorithm to whichever time we want so here the bigo notation basically provides us the worst case analysis of an algorithm by worst case we mean that it determines the longest amount of time the algorithm may take to complete moving ahead the third notation is the Theta notation now this notation basically expresses both upper bound and the lower bound of an algorithm's running time so what do we mean by both upper bound and lower bound it means that for any given input size to an algorithm this determines the average amount of time so basically the average case analysis is being determined by the Theta notation so for example if we say that certain algorithm takes 100 seconds for the first run 120 seconds for the second run and 110 seconds for the Third Run and so on so Theta notation gives an average of running time of that algorithm so it basically determines the average of the upper bound and the lower bound of an algorithm's running time so this notation is also very leastly used because there are very rare use cases where we actually determine the average time taken by algorithm to complete so in this video we discussed about the three ASM totic notations which are being used to determine the running time of an algorithm and these three notation also determines the best case the average case and the worst case analysis of an algorithm I hope you have liked this video thanks have a nice day hello everyone so in our previous video we discussed about the best average and the worst case analysis of an algorithm and we also discussed about the three notation and we discussed that bigo notation is the mostly used notation and Analysis of the time and space comp comp lexity so in this video we'll look into the analysis of time complexity in bigon notation and we'll also see certain rules in Computing the bigo notation so in our previous videos we discussed that bigo notation provides us an upper bound of an algorithm's running time by upper bound we mean the longest amount of time an algorithm can take to complete so let's see some rules and assumptions when Computing the running time of an algorithm using bigod notation so let's say we are given a machine so we assume that it's a single processor machine so let's say the algorithm we have wrote we are running it on the single processor and this processor is executing the algorithm sequentially now in an algorithm if we see any assignment operation then we simply assume that it can take one unit of time so this one unit of time can be anything let's say 1 second 1 millisecond 1 nond we simply term it as one unit of time so if we encounter something like this so we pretty much assume that it may take one unit of time if we encoun a return statement we take it as one unit of time so something like this will be taken as one unit of time if we encounter arithmetical operation we take it as one unit of time so something like x + y x - y x / by y x mtip by y and many other operations we simply take it as one unit of time that these operation will require a single unit of time if we encounter any logical operation we simply take it as one unit of time so something like X and Y X or Y negation of X negation of y x or operation so everything which deals with logical operation takes one unit of time and basically other small and single operation we simply take it as one unit of time now as we are Computing the bigo notation of an algorithm based on the input size so we basically assume that we have a very large input size so let's say the time taken by algorithm comes out to be n² + 3 n + 1 so here n is nothing but the input size so here you can see that time is proportional to n² + 3 n + 1 so which is a polinomial equation so here what we actually do that in order to calculate the bigo of this polinomial equation we assume that we have taken n as very large so if n is very large we can simply drop the lower order terms so the lower order terms would be 3 n and 1 because n sare contributes more and and determining the time taken by algorithm to run so we simply drop this lower order terms and to n Square we denote as o of n s which is nothing but denoting it in the form of vgo notation we simply say the time complexity comes out to be o of n² so similarly there's one more rule we drop the constant multipliers so for example let's say the time taken by an algorithm comes out to be 3 n² + 6n + 1 where n is the input size so here you can see that 6 n + 1 is usually dropped because they are lower order terms as we are taking n as very large but here you can see that it also contain the constant multipliers like 3 6 so usually as n is very large we also drop the constant multipliers so here after dropping the lower order terms like 6n and 1 we also drop this three and we simply denote it by o of n squ so we deduce the time complexity in bigo notation by following these Simple Rules so friends in our upcoming lectures we will apply these rules and we will compute the time complexity of few of the programs so that calculation of bgo notation becomes more clear to you I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about the rules related to bigo notation so now let's apply those rules and calculate the time complexity of a constant algorithm so here you can see that let's say we are given this piece of code where we are getting two integers we are doing the sum of it and we are returning the result so here you can see that these are the line numbers here where second and third line are the statements which get executed and here is a simple table provided with the line number and the operations getting performed on each line and the unit of time taken by each line so here we start with the line number two so here we are simply taking in two integers doing it sum and assigning it to the integer variable result so if we apply the rules which we discussed in our previous video so here first we are accessing X so it will be one operation then we are accessing y so it will be the other operation then we are doing the sum of it so this will be one more operation and then we are assigning it to the result so this will be one more operation so here we are simply performing four operations and we also discussed in our previous video that these four operation will take four unit of time because we are providing one unit of time to assignment to arithmetic operation if you're accessing any variable so like that so line number two takes 4 unit of time to execute this statement now let's see for the line number three here we are accessing the result so it will be one operation and then we are returning the result so it would be the other operation so there are total two operations and we know that when we are accessing a variable and when we are returning we provide one unit of time to one operation so total it will take two un unit of time and when we take the total time taken by this piece of code it will be 4 + two which is six and usually if you see six is nothing but a constant because here whatever value you take of X and Y it will always take a constant amount of time which is six so your time taken is nearly equal to a constant amount of time so similarly if we see this piece of code let's say we are passing in an array and we are passing in an index and we want to Simply get the value stored at that particular index so here you can see that accessing a value of an array from a particular index takes in a constant amount of time so the time taken by this piece of code will be constant now irrespective of how many elements are there in this array let's say array has one lakh element still it will take the con constant amount of time and if the array is one Element still it will take the same amount of time so therefore this is a constant algorithm so we simply denote the time complexity of such algorithm as o of 1 because this is the constant and usually in biger terms we denote the constant by o of one and if you see the graph of this constant algorithm so here you can see the x-axis denotes the volume of data so here you can think of it as the number of elements in this array and the y- axis denotes the execution time which is the time taken so here we already discussed that irrespective of number of elements or the volume of data inside this array the time taken will be always constant so we simply denote it as constant algorithm which takes constant amount of time even if the the volume of data increases so for in this video we discussed that how we can calculate the big old notation of a constant algorithm I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed that how we can calculate the time complexity of a constant algorithm so in this video we'll now discuss how we can calculate the time complexity of a linear algorithm so here let's say we are given this algorithm and this algorithm basically find sum of the first and natural numbers which we also discussed in our previous videos so here we are given a value n so let's say for example if we take value of n as three so we want to find the sum of first three natural numbers so we start the sum with the value zero we then apply for Loop where I is equal to 1 and we provide condition that I should be less than equal to 3 so at the first step value of I is 1 so 1 is less than equal to 3 so this condition comes out to be true so in the for Loop we do 0 + 1 and assign one to the sum and after this statement gets executed we do I ++ so now I becomes 2 then we check whether 2 is less than equal to 3 or not so here 2 is less than 3 so then we do 1 + 2 because value of I is 2 which gives three and we assign three to the sum now we again increment I by 1 so I becomes 3 and 3 is less than or equal to 3 so now we do sum of 3 + 3 which is 6 and we assign it to the sum and then we increment I by 1 so I becomes 4 and we check this condition so 4 is not less than equal to 3 therefore this condition comes out to be false and this for Loop terminates and we return the sum as six so here let's calculate the time complexity of this algorithm so here we have provided a table where we have marked the line numbers which actually gets executed and takes some amount of time so if we start with line number two so here you can see that we are cre creating a integer variable sum and assigning it to Value zero so this will only take one step so the operation will be only one and the unit of time would be 1 so now we'll count the operations at line number three so here you can see in the for Loop we are creating an integer variable I with a value one so this would be one operation now here you can see that we are accessing n so this would be one operation we are accessing value I this would be the second operation and then we are comparing them so this would be our third operation so overall for one execution of this for Loop this take three operations so we need to calculate how many iterations this for Loop will make so that depends on this incrementation here so let's say if value of n is three so when I was 1 it took three operations then then we incremented I to two so when I became two it took three more operations and then we incremented I by 1 so when I became three it took three more operations and then we again incremented I so I became four and here you can see that it took three more operations just to verify that I is less than equal to n or not so in total this statement executed four times we provided a value three and it executed four times so therefore when we have provided value n this will get executed n + 1 times and as there are three operations in each step so the total operations would be 3 into n + 1 so then we move to I ++ so in i++ what we actually do we access value I we increment it by one and then we again assign it back to I so accessing I takes one operation incrementing it by one and assigning it back to I takes three operations so for the one iteration of this for Loop this take three operations so now we simply count that how many times this i++ will get executed so let's say if we take n equal to 3 the first time it executed it made I ++ and I became two then we executed to make I 2 + 1 which was 3 and finally we made it 3 + 1 which is 4 so here you can see that for Nal 3 this got executed three times so if we take value of n this will execute n times and as this take three operations per iteration for n times it will take 3 n operations so here we are simply adding one to 3 into n plus 3 into 1 which is 3 and then we are doing plus 3 n so it will become something like this 1 + 3 n + 3 + 3 n so the total unit of time it will take is 3 n + 3 n 6n 1 + 3 is 4 so 6 n + 4 so now we'll see the time taken by the step four so here we are accessing I which is one operation we are accessing sum which is two operations we are doing addition which is three operation and we are assigning it back to sum which is four operations so for one iteration of this for Loop it will take four operations and we know that this for Loop will execute nend times because I is traveling from 1 to n so this line will get executed n times so here in total it takes four operations multiplied by n so the total unit of time it will be 4N so now we'll calculate the time taken by line number six which is accessing sum and then returning the sum which is 1 + one so total time would be two so if we add this unit times we get the total time would be 1 + 6 n + 4 + 4 n + 2 which will be equal to 10 n + 7 unit times and also in our previous video we discussed that while calculating the bigo notation we usually ignore the lower order terms because we assume that value of n is very large so after ignoring the lower order terms and we also discussed that we ignore the constant multipliers so here we ignore 10 also so the time complexity comes out to be o of n which means that time is directly proportional to the value n which is nothing but the input size so if we plot the graph of the execution time on the Y AIS and the volume of data which is n on the x-axis we find that time is proportional to n so here you can see that if you plot this graph it will come a straight line because the execution time is proportional to the number of input size which is nothing but our volume of data so as volume of data will increase the time taken by this algorithm will increase so this comes out to be a straight line so this is how we denote the time complexity of O of n which is a linear algorithm I hope you have liked this video thanks for a nice day hello everyone so in our previous video we discussed that how we can calculate the time complexity of a linear algorithm so in this video we'll discuss that how we can calculate the time complexity of a polinomial algorithm so here we are given an algorithm and we are also given an integer and now what we are doing in this method is we have provided a for Loop which goes from I = to 1 to less than equal to n and it gets incremented by one for each iteration of this for Loop and for each iteration of the outer for Loop we have again provid provided a for Loop which starts from Jal to 1 and goes till J is less than equal to n and it also gets incremented by j++ and inside this inner for Loop we are simply printing the value of I and J on the console and after this inner for Loop get executed we are printing end of inner loop and after this outer for Loop gets executed completely we are printing end of Outer Loop Loop so here you can see if we run this code let's say for Value Nal 3 so here you can see that this get printed on the console so in our previous video we also discussed that this outer for Loop will go from I = to 1 to I less than equal to n which is 3 so it will get executed three times the outer for Loop and for its each execution the inner for Loop will also get EX executed exactly three times because J is also starting from one and J is also going till J is less than equal to 3 so here you can see that what it gets printed on the console so for I equal to 1 inner for Loop gets executed n times so here you can see I = to 1 I = to 1 and I equal to 1 so for I equal to 1 the inner for Loop will get executed n * where J will go from 1 to three so here you can see Jal to 1 Jal to 2 and J equal to 3 and after inner for Loop gets executed end of inner loop gets printed which is here and once it gets finished the execution Point reaches here does increment of I by 1 so I becomes two and we know that 2 is less than 3 so therefore again the inner for Loop will execute from Jal to 1 to J is less than equal to n and and this will get printed three times because the inner for Loop will get executed end times so for IAL to 2 the inner for Loop gets executed from Jal to 1 to 3 then we print end of inner loop here and then again I gets incremented to three and for I equal to 3 the inner for Loop will again get executed three times and then here we print end of inner loop and then we again increment I by 1 so I becomes 4 and 4 is not less than equal to n so therefore the condition breaks and finally we print end of outer loop so here you can see that for each iteration of outer for Loop inner for Loop gets executed that many number of times from J equal to 1 to J is less than equal to n so here in this example as you have taken value of n is three so you can simply think that outer for Loop gets executed three times and inner for Loop will get executed 3 into three times which is nine so here you can see that this statement gets printed nine times for each value of I inner for Loop gets executed from 1 2 3 for I = 2 it gets executed 1 2 3 for IAL to 3 it gets executed 1 2 3 so usually this statement at line number four gets executed n² s so let's see how many operations are getting performed on each line so for line number two so in our previous video we already discussed that how many times this for Loop will execute so this assignment integer I equal to 1 will get executed exactly one time we are accessing I we are accessing n and then we are comparing so this will get executed exactly n+ 1 times because so when we are providing value of n is three so when I becomes four this condition will comes out to be false so therefore we provided value n and this will get executed exactly n + 1 times this is the same stuff which we discussed in our previous video and then this i++ will also get executed 3 n times so this for Lo will execute end times so it will take 3 n times and if we do the sum of it it will take 6 n + 4 unit times now let's see about the operation taken by the inner for Loop so here you can see the condition are exactly same so here we know that it will take 6n + 4 unit time the inner for Loop because J is also getting started from one and it will also go till J is less than equal to n and we are simply doing j++ so here line number four will get executed 6 n + 4 unit of time but this for Loop will also get executed multiple times based on the execution of outer for Loop so if outer forloop runs end times the inner for Loop will run end times of the outer for Loop so which will give us 6 n² + 4N unit time of execution moving ahead at line number four we are accessing I we are accessing J and we are printing so there are total three operations and how many time it will get executed you can see for value of n equals to 3 it got executed 3 Square Times which is 9 so here the total operations would be n² * 3 which will give us 3 n Square the line number six which is end of inner loop will get exactly printed end times so here if n was three it printed three times and for n times it will get printed and into one times which takes n unit of time and the line number eight will get executed exactly one time so if we add all the unit times we get the total time would be 6 n + 4 + 6 n² + 4 n + 3 n² + n + 1 and if we add the N sare terms and N terms and then the constant it will become 9 n² + 11 n + 5 so here as we assume that we take value of n to be very large we ignore the lower order terms and we also ignore the constant multipliers so we remove N9 also so if you want to represent a Time complexity of this algorithm it would be o of n² because rate of increase of time is getting directly proportional to n sare and if you plot the graph with time versus the input size it will give us a parabolic curve where execution time will increase by n Square so here you can see that as volume of data will increase the execution time will increase n Square times because time is directly proportional to n² so this is the graph for a polinomial algorithm so here you can see that this is a really bad algorithm because execution time is drastically increasing with the input size so usually we try to avoid the nested for Loops because for each outer for Loop inner for Loop gets executed that many number of times so which you can see by the operation at line number three so here you can see based on the condition provided here inner for Loop gets executed end times the outer for Loop and also friends similarly let's say if we had one more for Loop inside the second for Loop this would have gone to n Cub times based on if the condition here provided are same so it would have taken o of n Cub time so which is also a polinomial algorithm and which is also really bad so here in this video we discussed about that how we can calculate the time complexity of a polinomial algorithm I hope you like this video thanks have a nice day hello everyone so in this section we will discuss about the error data structure we'll see a basic introduction to array and then we will discuss that how we can create an array initialize an array and assign some values to an array so friends what is an array so here let's take an example of a chocolate box so you must have seen a chocolate box having these chocolates separated by the partitions and the containers so when we actually see it for the first time we get few things in our mind the number one is we can tell that it's a collection of chocolates or a box of chocolates and all the partitions which are holding this chocolate you can see they are adjacent or we can say they are contiguous because they are very next to each other and here you can also see that each partition has two Neighbors except the first and the last one for example the second partition has one neighbor to its left and one neighbor to its right but the first and the last one they have only one neighbor for the first it is the right and for the last it is the left and when we receive this pack of chocolates the size of this box is fixed and cannot be modified so any chocolate making company will first create this box and based on how many chocolate they want to add into this box they will create that many partition and once this box is created it cannot be modified and also we saw that these partitions are very Adent to each other so therefore they are also indexed and can be determined by its position so looking at the Box we can simply number a position and simply can ask that okay I need the third chocolate or fourth chocolate because we know that the chocolates are very adjacent and they are inherently indexed so friends similar analogy can be applied over an array so here you can see that this is an array having four elements so we can say it is a collection of data elements of a particular type and here you can see that all the partitions which are holding this data have memory locations so they are very next to each other we can also see that those partitions have two neighbors except the first and the last one and we can also deduce that once we create an array we need to provide a size so when we provide a size we are given with an array and once it is created we cannot modify it so if you want a dynamic array there is some complex logic behind it which we will discuss in our upcoming videos so for now you can have an understanding that an array can hold some data elements and the size to hold the data elements is fixed and we cannot modify it and here you can see that these partitions have contigous memory locations so therefore each partition comes with an index so for an array of four elements usually the index starts with zero and ends with number of elements inside this array minus one so which is the length of the array minus one so whenever we create an array basically we have a index associated with it which starts from zero and for one dimensional array it ends with the complete length of this array minus one so let's say length of AR is four because we have four elements so the last index would be length minus 1 which is 4 - 1 3 so friend this was the basic introduction to an erray data structure that how it holds the element and how they are very much next to each other and basically they are indexed so this indexing of array also help us in accessing the value inside that container so we can simply do array of three and we will get the value stored at the third index so so this is also one of the advantage of having the index data structure so friend in this video we saw a basic introduction to an array data structure in our upcoming videos we will see that how we can create an array initialize an array and add values to an array I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about a basic introduction to an ARR data structure so in this video we will discuss that how we can perform declaration and initialization of an array so here when we say Declaration of an array we'll first discuss about the onedimensional array so the onedimensional array can be declared bya syntax we can provide a data type then we can provide the variable name and then we simply provide the square brackets so that we can come to know that this is an array so this is the one way the other way is we can provide any data type and along with that we provide this square brackets and then comes our variable name so for example let's say if we want to declare an integer array so we can simply provide int and then we can provide our own customized variable name so here I have just given it as my array and then the square brackets and similarly we can do something like this that int square brackets and then we provide the variable name so here when we declare an array in Java we can use both these syntaxes the most preferred use syntax is the second one because we can simply deduce the this is an array of integer data type by just looking at the int and the square brackets so this is the mostly used syntax to declare an array moving ahead now let's see how we can initialize an array so by initialization we mean that when we initialize an array we are simply providing a memory to the array elements so that now array can store the collection of data into it so the Syntax for the onedimensional array is something like once we declare an array what we saw in our previous slide in the next step we can do we can give them variable name and we can use the new operator to initialize an array and then we need to provide the data type along with a size so we also discussed that when we create an array we need to provide a size because once the array is initialized we cannot modify the size so by this statement we are actually telling that provide us an array of this particular data type whose size is whatever the value you have provided here so once this lines get executed we are provided with an array of fixed size and certain memories associated with this data type so that now we can use this array and store our for data elements so for example we can write something as as we have declared my array in our previous slide we can say my array equal to new the data type and in the square bracket we can provide the size so this will initialize an array of size five so we can add Five Element inside this array and also friend usually we perform the Declaration and initialization of an array in one go or in one step so the Syntax for that is we can just combine the Declaration and initialization in one step as we simply give the data type then square brackets then variable name equal to new data type for which we want to create an array and then the size and we can also use this syntax data type the variable name with the square brackets and then we can simply provide new data type and the size associated with it so for example we can simply create an integer array something like this so here using new operator this will create an integer array of size five so that we can store five integers inside this array so this is the other syntax so the most preferred syntax is the first one so just by looking at the statement we can come to know that this is an integer array because usually the square brackets are alongside with the data type and also friend there is one more way to declare and initialize an array along with it data elements is we can write integer square brackets variable name and we can simply say curly brackets and we can simply provide the actual data along with it so here you can see that if we know that what data we want to store inside is an array beforehand then we can simply use this syntax so it will directly initialize this array with proper values such as 5 4 3 2 6 at index 0 1 2 3 and 4 and here you can see it deduces the size by counting the number of elements we have provided inside this curly bracket so here as we have stored five elements this integer array will now have a size of five so friend in this video we saw that how we can declare and initialize an array with various syntaxes in our upcoming video we will discuss that how we can add an element or update an element inside the array using the index position I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about how we can declare and initialize an array so in this video we'll go a step ahead that after declaration and initialization of an array we will see how we can add or update the elements in an array so friends here you can see let's say we have this method as array demo having few statements so when we execute the statements in Java we will see what happens to this error data structure so when we call error demo method so here you can see at the first line what we are doing is we are declaring and initializing an array of integer type having a size of five so when this line will get executed you will see that we have this variable named my array which is referencing an array of size five so you can see five partitions here and this array will also have a proper index starting from zero and ending at length minus 1 which is 5 - 1 which gives gives four so here you can see this array object is created inside the Heap memory and using my array we have this reference which is pointing to this object so you can consider this reference as a remote control where using my array we can simply control this array inside the memory so using this variable and the indexes we have we can simply store or update the element inside this array so how we can do that let's see its demonstration so let's say at the first position we want to store a integer having value as five so how we can store that that we have this variable name and when we do square brackets and we provide this index so we are telling to this array via this remote control that please add five to index zero so inside this partition here you will get a value as five and also friend before that when we initialize or create an array using this new operator you can see that initial values of the integer came out to be zero so when we initialize an array this object doesn't know that what value this array could hold so it simply assigns the default value so for integer the default value is zero and similarly let's say for other types such as float double it would be 0.0 for long it will be zero for Boolean it will be false and for a proper object it will be a null value because those are the default values for primitive and non-primitive data types so here after giving the value five at index0 we can access the index one via this syntax and we can assign the value one so it would look something like this that one is being stored here and similarly we can store it at index 2 value two at index 3 value 10 at index 4 and now friends you can see that we have assigned all the values inside all the containers now let's say if you want to update any value so we can simply access it a normal way and assign a new value so here at this line we have added eight at index 2 here so if we again call this with a different value so 9 will override this value and 8 will be gone and 9 will be edit splits so this is just an update to an array and friends at the last step what we are doing is so here you can see that this integer array is of size five and we know that index starts from zero so the last index would be 5 - 1 which would be 4 and now friends here what we are doing is let's say if we access my and do something like this five so here you can see the fifth index is not there and if we try to assign a value seven to it so once this line get executed at run time you will get this exception in Java which says that array index out of bounds exception and it also gives a message saying index 5 out of bounds for length five which means that the length of this array is five which is the size and index five is basically out of bounds because in an array index starts from zero so the last index would be the length minus one which is four so it simply says that index 5 is out of bounds for length five so this is the most common exception which we actually get when we try to work with an error data structure because sometime it might happen that we wrongly access an index which is not present inside an array so friend this was all about adding or updating elements in an array now let's go to eclipse and see the demonstration of this code I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about how we can create initialize an array and we also discussed that how we we can add or update elements inside an array so in this video we will see the demonstration and working of the code which we discussed in our previous video so here we have this class array util and which is one utility method which prints the array on the console so this method we will be discussing in our upcoming videos in great detail so for timeing just think that this will print the contents of an array so we have this method error demo so let's see the working of that code which we discussed in our previous video so at the first step what we did was we created an integer array we gave it a name as my array so we can provide any name and let's say we provide a size as five so friends here you can see that this will actually create an array which would be of integer type and the values this array will hold will be the default values and these default values will be decided based on the data type and here see let's say if we call error demo method so when this main method will run this line will get executed and this array will will be created with default values so let's say if I call Print array here and we pass my array to it so here this method will be called and the contents of this array will be printed so if I run the main method now so here you can see it printed 0 0 0 0 0 so because we created an array of size five 5 * 0 was printed because this integer has default value of zero so for each partition this array head it stored the value zero into it so friends in our previous video we also discussed that we have this my array which will be acting as our remote control to modify the array object inside the memory so what we can do is let's say we want to add a value of five at index 0o so this would be the syntax and similarly let's say I fill all the values for each and every index say 0 1 2 3 and four and let's say I give a different value 5 1 8 2 and 10 and if I call the print array method here after assigning this few values and if I run the code now you can see all the default values which were getting printed at 0 0 00 0 have been updated by 518210 and let's say after assigning a value8 at index 2 which is here what we can do is let's say I want to update this and I want to update it by 9 so I can do simply like this and if I run the code now again so you can see that only at index 2 the value was updated from 8 to 9 and also friend let's say if we try to access an index which is not in range of this size so let's say if we try to access an index which is not present inside the array let's say five and if we give a value at let's say 20 6 and if I run the code now so friend here you can see that we got an exception saying array index out of bounds exception giving an index 5 saying that five is out of bounds for this array so here if you see when we do my array so the indexes starts from zero and ends at size minus one which is four so here you can see that this array will go from zero 1 2 3 4 so these are the indexes which we are using it here to access a particular container so that we can store these values so this arror data structure inherently has this one variable by name length so if you want to know that what is the length of any particular array we can simply use this value my array. length so let's say if I print this on the console and if I run the code now so here you can see it printed the length of this array as five because we have created the integer array of length five so usually when we get an array and if we want to just know what is the length of that array we can simply use this variable we can give the variable name do length and we'll get the length of that array and similarly let's say if we want to access the last element of an array so what we can do is we can simply say my array and here you can see the last index is actually length minus 1 which is 4 so here we need to give the value as my array do length minus one so here my array. length will give value as five and when we do minus one we we can get get the last index of this array and in order to access that element we need to provide the name of the array and then square brackets and inside the square brackets we can provide the actual index for which we want to access a particular value so if I run the code now you can see that it printed 10 because 10 is the value hold by the last index of this array and also friends similar to this what we can do is we can also create an array something like like this where we actually know what this array could hold so we can simply give the values as five 1 8 and let's say 10 so this array will hold the these values at the respective index starting from 0 1 2 3 so the length of this array is four and the index goes from 0 to 3 so if I print this array now and if I run the code you can see printed 51 8 10 which are the elements present inside this array so friend in this video we saw few operations related to an array that how we can create an array and how we can add or update values inside this array I hope you like this video thanks have a nice day hello everyone so friends in this lecture we will discuss how to print elements of an array in Java so here most of you know how to print elements of an array in Java the only reason we are discussing this algorithm here is because in our upcoming lectures this algorithm will be mostly used so let's see the demonstration of algorithm by an animation so friends here you can see that we have this public method by name print array which takes in an array and to this array will iterate its element one by one using the for Loop and will print its content on the console so let's see the demonstration of this algorithm so let's suppose we call the print array method by passing in an array so let's say we pass this array having five elements as 5 1 9 2 and 10 moving ahead so in the first step what we do is we take out the length of an array and store it in an integer variable n so here if you see as the array holds five elements so when we will do array. length the value five will be stored in N so it would look something like this the value of n is five moving ahead now friends in order to print each and every element of an array we need to trade this array from the first index to the last index and as we know that the index of array starts from zero so the value of I will be zero because this is our starting point and we'll iterate in a for Loop till I is less than n so here if you see I will start from zero and it should go to four so we want this Loop to go from i0 to I4 so therefore we have provided this condition that I should be less than n it means for the last index 4 should be less than 5 because when I will be equal to 5 then we know that I has crossed the boundaries of this array therefore we'll get an exception so we'll iterate till I is less than n so here we'll start with i equal to Z so if we see in this array then I is pointing to the zero index moving ahead now in order to print the elements on the console we are doing system.out.print and in order to access the value at this particular index we do array then we provide this square brackets and inside that we provide the index for which we want the value so on the console it will print five because I is pointing to the zero index and array of zero will give value as five moving ahead now we will increment I by 1 so I becomes 1 and now I will point to the index one and here we'll check that whether 1 is less than five or not so this bullan condition comes out to be true so the for Loop execute s and then we'll simply print the value at first index which is one so it would look something like this moving ahead will now increment the value of I by 1 so I will become two and it will point to the second index we'll simply print the value at the second index which is N9 so it would look something like this moving ahead we'll again increment the value of I by 1 so I will become three and it will point to the third index we'll print the value at the third index which is two so it would look something like this is moving ahead we again increment the value of I by 1 so I becomes 4 and it will point to the fourth index now and we know that 4 is less than 5 therefore the condition in for Loop comes out to be true and then we'll print print the value at index 4 which is 10 so it would look something like this now we'll increment I by 1 so I will become five so friends here we can see that five is not less than five therefore the condition in follow Loop comes out to be false and as we have iterated each and every element and printed it on the console we'll simply exit this for Loop and at the last I will simply do a print line so which will bring the cursor to print stuffs on the console to the next line so friends this was a demonstration that how we can print the elements of an array in Java so here we iterated each and every element using for loop from the start index to end IND index and we printed the contents of array on the console so now let's go to eclipse and see the demonstration of this code I hope you like this video thanks have ni day hello everyone so friends in our last lecture we saw that how we can print the elements of an array in Java and we saw the animation of the algorithm now in this lecture we'll code the algorithm and we'll see it's working through main method so here I will be creating one method as public void and we'll give the name to it as print array so this method will take in an array let's have integer type so now our task is to print elements inside this array on the console so what we do is we simply iterate each and every element of this array and print its content on the console so in the first step what we do is we simply take the length of the array and store it in an integer variable and so why we do this because in order to iterate this array we'll provide a for Loop and we know that array starts from the zero index so we want to know that what the size or the length of the array so that when we are using the for Loop to iterate this array we can give a range that iterate the for loop from start to end so the value of n is nothing but our end point so then we'll provide a for Loop and inside it for Loop we'll start our iteration from index zero because in an array the storage of element starts from zero to index and will Traverse till I is less than n so let's say arrays n elements so it will be distributed from the range of 0 to n minus 1 so therefore we need to Traverse from 0 to n minus 1 so therefore we are providing this condition I should be less than n and then we'll simply do I ++ each time in order to print the elements of an array on Console we simply provide the system do out do print and inside this print method we'll simply take out the value stored at the IAT index and print it on the console so I will travor from 0 2 N minus one so when it will start from zero the index it will print the value stored at zero the index then we'll do i++ then it will print the value at first index and and similarly at the last it will print the value stored at n minus 1 at index and after forl will simply provide the print line so friend this is the code to print the elements of an array on Console so here now let's see the working of this code through main method so first we'll create the instance of aray util class now we'll call the print array method by passing in an array so here we'll call Print array and we'll simply pass an array so let's say we provide five elements whose value would be 5 1 2 9 and let's say 10 so friends here we have created a new array and using this curly brackets we have provided that this array should have five elements and we are directly passing this array to this print array method so now let's run this code so here you can see that it printed five 1 2 9 10 by treating over the array one by one using this for Loop so from this lecture we saw the working of this algorithm that how we can print the array elements on the console I hope you like this video thanks have a nice day hello everyone so in this video we are going to discuss that how we can remove even integers from an array now here let's suppose we are given an array of integers we need to return an array with even integers being removed so for example let's say we are given the array such as 3 2 4 7 10 6 5 so your 2 is even integer four is even integer 10 and six are even integers now we need to remove those even integers and only return the odd numbers which is 3 7 and 5 so let's see the demonstration of this algorithm step by step so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here is the algorithm which will help us removing the even integers from an array so the method name is remove even it takes in an array and returns an array in which the even integers are removed so let's say we take the example of the array having Seven Elements 3 2 4 7 10 6 5 and let's say when we call remove even method by passing in the array this method actually starts as execution now how we can remove the even integers from the arrays first we actually count the number of odd integers in the array and why we count the number of odd integers is because we need to return an array having only odd integers by removing mov the even integers from the given array so at the start odd count is zero now we provide a for Loop and we Traverse the array elements one by one so starting from I equal to Z which is zero index we go till I should be less than ARR do length so ARR do length is 7 because there are seven elements and less than seven means up till six so at the start I is actually less than a. length so friends how we can find the odd integers inside this arrays we can take the value at any particular index if we divide it by two and if the remainder is not equal to zero it means it's an odd element so friends we know that even integers are 2 4 6 8 where if we divide the element by two let's say 2 divided by 2 so we get the remainder as zero so the even integers when divided by two give remainder as zero and if we take the odd integers 1 3 5 if we divide 3 by 2 we get remainder as 1 if we divide 5 by 2 we get remainder as 1 so if the remainder is not equal to zero it means it's an odd integer so we will take the help of this modulus operator which will directly provide us the remainder and if it is not equal to zero we will increment the odd count so at the start we get three 3 divided by 2 will give remainder as 1 1 is not equal to zero so therefore this condition comes out to be true we will increment odd count because three is an odd integer so here it becomes one we will increment I now array of I which is 2 2 ided 2 will give remainder is zero so therefore this condition comes out to be false so this statement is skipped and we reach here again so we do I ++ I becomes 2 now 4 ided 2 will give remainder as zero because 4 is divisible by 2 so this condition comes out to be false we'll increment I again I becomes three so this condition comes out to be true now 7 ided 2 will give remainder as 1 and 1 is not equal to zero therefore this condition comes out to be true we will increment odd count because s is an odd integer we'll increment I 10 / 2 will give remainder is zero so this condition comes out to be false we will again increment I now six which is array of I divided by 2 will give remainder as zero so this condition comes out to be false we will again increment I now 6 is equal to 6 and it is less than array. length because aray do length is 7 so this for Loop will run one more time we will take 5 5 ided 2 will give remainder is 1 1 is not equal to Z so therefore this condition comes out to be true we will increment odd count it becomes three now when we'll increment I it will become 7 and 7 is not less than 7 so this condition comes out to be false and for Loop will terminate so here you can see that when we traversed each and every element in the array we figured out at three 7 and five are three elements which are odd and we need to return this three elements by removing the even integers from the array so therefore the array which we want to return will have only three elements which will be the odd integers so we will create the result array we pass in the odd count because we have calculated the odd count through this for Loop so the result array will have only three elements now here we will create one index starting from zero so this index will help us filling the result array so it will simply Traverse the result array now here we will again provide a for Loop which will iterate the array like we did here from I equal to0 to I less than array dot length so I starts from zero now why again we are iterating the the array and here providing the same condition to find out the odd integer is because once we find out the odd integers we will simply assign that value to the result array at a particular index so at the start 3 / 2 will give us a remainder as 1 so 1 is not equal to zero so therefore this condition comes out to be true so it means we have found one odd integer so we will assign the value in the array at aat index which is the zero index which is three to the result array at the index zero so three will come here with this assignment now after we have assigned one value to this index we will increment the index because we need to fill the next value so index becomes one we will increment I 2 / 2 will give remainder is zero therefore this condition comes out to be false and we skip this element we will again increment I I becomes 2 so value at second index is 4 4 divided by two will give remainder as zero so this condition comes out to be false we will again increment I I becomes 3 now the value of third index which is 7 7 ided 2 will give remainder as 1 1 is not equal to Zer therefore this condition comes out to be true it means we have found our second odd integer which is 7 so we will assign the value 7 to the result array as index one so 7 comes here we will increment the index we will increment I 10 / 2 will give remainder as zero so this condition comes out to be false so friends here you can see that whenever we are encountering a even integer we are simply skipping that value and we are traversing ahead so when we increment I I becomes five 6 ided 2 will give remainder as zero so this condition comes out to be false we will increment I 5 / 2 will give remainder as 1 so this condition comes out to be true because 1 is not equal to zero it means we have found our third odd integer so we will assign five to the result at this particular index which is second index so five comes here and we will increment index so as we have filled all the values we will again increment I so when we will increment I I will become seven which will be going out of the boundaries of this array so this condition comes out to be false because 7 is not less than 7 so this for Loop will terminate and at the end we will simply return the result so here you can see that we have removed the even integers from the array and we are returning a new array having only odd integers so friend this was all about this algorithm the main idea behind this algorithm is to figure out the odd integers so we can take the number and when we divide it by two if the remainder comes out to be 1 it means it's an odd integer and if it comes out to be zero it means it's an even integer so why we calculate the odd count at the start because we need to find the length of the new result array so that we can create this new array of three values because the odd count is three and then we can perform the same steps again we will figure out the odd integer and we'll simply assign that odd integer to the respective indexes 1 by one and at the end we will simply return the result so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have nice day hello everyone so in our previous video we saw an animation in which we discussed an algorithm that how we can remove the even integers from an array so in the problem statement we were given with an array of integers and our task was to remove the even integers from the array so in that video we saw the animation of the algorithm and in this video we will actually code the algorithm and we will test it working in the main method so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in our previous videos we have discussed that how we can print an array and in this video let's say if we are given with this array of integers and we want to remove the even integers from the array so the output would be 2 4 10 and 6 will be removed so it will give us 3 7 and 5 so here you can see two is even integer four is even integer and 10 and six are even integers so we need to remove those elements and return an array having only odd integers so now let's code the algorithm which we also saw in our previous video let's say I provide the method name [Music] is remove E1 so this method will take an array of integers and it will return back an array of integers in which the even integers will be removed so here the basic idea we do is first we count the number of odd integers in the array so for that we create an integer variable odd count and then we simply Traverse the array using a for Loop so why we are evaluating odd count we will see later so here how we can figure out whether an element is an odd integer or an even integer we simply take that element we divide that element by two and if the remainder is zero it means it's an even integer and if the remainder is not equal to zero it means it's an odd integer so here if array of I if we do mod 2 and it is not equal to zero it means it's an odd integer so 3 / 2 will give remainder as 1 so 1 is not equal to zero it means it's an odd integer so this modulus operator is helpful in determining the remainder so if remainder is not equal to zero it means it's an odd integer so we'll simply increment odd count and if it is an even integer then we simply skip so after knowing the number of odd elements what we do is as we need to return return an array of integers having only odd integers we'll create a result array of size odd count because we need to return this three elements so this odd count after traversing each and every element will have value three because there are three odd elements 3 7 and 5 so we need to return this aray having three elements so we'll create this result array of three elements so this is the reason we are evaluating OD count here now after creating the result array we need to fill this result array with the respective odd elements so first we'll create an index variable starting from zero and then we will again iterate the [Music] array and we provide the same condition what we have done here so here if element at index mod 2 if it is not equal to Z it means it's an odd integer so we need to put this integer into the result array so in order to put the element into result array we need to find the index that where we need to put in the result array so for that we have created this index variable so this index variable starts from zero so let's say if we encounter three so we need to put three at the zero if if you have encounter 7 then we have to put in the next index and if you have encounter five then we have to put in the next index so we will use this index variable to keep the track of these positions and after placing the odd integer at a proper index we have to increment the index as well because after putting three let's set zero the index 7 will come in index one so we need to increment index as well and after doing that we'll simply return the [Music] result so here you can see if the element at index is even we are doing nothing we are simply skipping it and if it is a odd integer then we are taking that integer placing into the result array at a proper index and then we are incrementing the index as well so now let's test it working in the main method so first we will print the original array if I run the code now you can see it has printed the original array now we will call remove even method we'll pass the original array and it will return back a result array now this result will have only odd integers so if I print it again if I run the code now so here you can see it printed 375 it has removed the even integers 2 4 10 and 6 so friend this was all about the implementation of this algorithm I hope you must have liked this video in case if you're new to my channel then please subscribe to my my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to reverse an array in Java so friends let's suppose we are given an array and our task is to reverse the array so for example let's suppose we are given an array of integers having values as 2 11 5 10 7 and 8 so when we will reverse this array of integers it would become 8 7 10 5 11 2 which you can see below so friend let's suppose we are given a numbers array whose length is six that is having index from 0 to 5 and we want to reverse this array so here is an algorithm to reverse an array so let's see the demonstration of this algorithm step by step so in order to call the reverse array method we pass in the numbers array which we actually want to reverse we also provide a range in which we want to reverse the array so here as we want to reverse this complete array we give the start position at zero and the end position numbers do length minus one so here you can see the length of the array six and minus one becomes 5 so the end index is five because you want to reverse this complete array so when we call this method by passing in the numbers array which we want to reverse the value of start is zero and the value of end is five so Friends start and end is nothing but the range between which we want to reverse an array so the idea behind this algorithm is we we usually take two pointers one is the start pointer and one is the end pointer so here you can see currently the value of start is zero so we simply refer to the index zero and the value of end is five so we simply refers to the value at index 5 so the values which start and end hold are nothing but the indexes of the array which is nothing but the range so here we actually want to reverse this array from the start position to end position so let's see it's working so in the first step what we do is we actually provide a while loop and the condition we provide in the while loop is we check whether start is less than end or not so your value of start is zero and value of end is five so here in the condition in V block comes out to be true so friends what we actually do we simply swap the value at start index with the value at end index because we want to reverse this array so we actually reverse this array by making swp pair wise between start and the end index so here in order to swap these two values first we will create a temporary variable to store the value at the start index so it would look something like this so the value at start index is nothing but two so we are storing it in temporary variable moving ahead now as we have stored this value in the temporary variable we can simply assign the value at end index to the start index so it would look something like this so now value at index 0o is 8 moving ahead and now we'll simply assign the values stored in temporary variable to the end index so it would look something like this so the value in the array at the end index now becomes two moving ahead so friends here we have swapped these two values which are being referred by the start position and the end position so after we have swapped these two values now we simply increment the start by one and we decrement The End by one so here we are incrementing the start by one so as start is holding the value of zero it becomes one so now it will refer to the index one moving ahead and then we'll decrement The End by one so as end is having value of five now it becomes four and now it will point to the fourth index and the while loop will again check whether start is less than end or not so here you can see value of start is one and value of end is four four so therefore the condition in while block comes out to be true and now we'll simply Swap this two values which are being referred by start position and end position so first we'll store the value of error at start index into the temporary variable so now 10 becomes 11 and then we'll simply assign the value stored in the array at index 4 to index one so it would look something like this that the value in Array at start index now becomes seven moving ahead and now we'll simply assign the value in temporary variable to the end index of the numbers array so it would become something like this that the value in numbers array at the end index becomes 11 moving ahead now as we have swapped this two values we'll simply increment the start by 1 so the value of start is 1 now it becomes two and now simply start will point to the index two moving ahead and we'll simply decrement The End by one so currently the value of end is four so it will become three and now end will point to the index 3 moving ahead now again condition in while block comes out to be true because 2 is less than three so now we will swap these two values so we'll assign the value at index 2 to Temporary variable so now temporary variable is having value as five and then we'll simply assign the value of index 3 to index 2 moving ahead and finally we will assign the value in the temporary variable to the numbers array at the end index so it becomes something like this and finally we'll increment the start by one so start becomes three and now it will point to the third index moving ahead and then we'll decrement the End by one so nend becomes two and it will point to the second index so now in while loop we'll again check whether start is less than end or not so here you can see the value of start is greater than end so therefore the condition in while block comes out to be false and also friend here you can see that is array is completely reversed so friends the idea behind this reversal algorithm was to actually take the two pointers one would be the start position and one would be the end position and we simply kept on swiping the values and then incrementing the value of start by one and decrementing the End by one so we' performed this operation till start was less than end so as soon as start becomes equal to end or greater than end then we have actually reverse the complete array friend here we saw an example with an array of even number of values so we actually swabbed in pairs but if we took an array of odd numbers of element then also this algorithm will work fine because because the middle element will always retain its place when we are reversing an array so friends let's go to eclipse and see the working of this algorithm so friends in our previous tutorial we saw the demonstration of how to reverse an array in Java so in this tutorial we actually code the algorithm for reversing an array so here I have created one class by name reverse array and this class has an starting method print array which will actually take an array and print its elements on the console and in the main method I have taken the same array which we discussed in the slide so initially if I run the code now you see it prints the values in the array is 2 11 5 10 7 8 and now we'll write the code to reverse this array so we'll create a static method public static void reverse this method takes in the array which you want to reverse and it also takes the r range that from which position to which we want to reverse the array so it actually takes the start position and the end position between which we will reverse the elements of the array so the first step we'll provide a while loop and we'll iterate till start is less than end and in this value will simply swap the values at the start index and the end index of the array so first we'll create a temporary variable and to this temporary variable we'll simply assign the value at the start index of array and then we'll simply assign the value at the end index to the value at start index and finally we we assign the value of the temporary variable to the end index of the array and then we'll simply increment the start by one and decrement the End by one so friend this is the algorithm to actually reverse an array now let's test it's working in the main method so here I will call reverse method by passing in the numbers array and the start position is zero and end position is numbers do length minus one so between this range the array will be reversed and finally we'll print the array so if I run the code now so friends here you can see initially the array was having values at 2 11 5 10 7 8 so after reversing this array it became 8 7 10 5 11 2 so friend in this tutorial we actually coded the algorithm to reverse an erray in Java I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will disc discuss how to find minimum value in Array so friend let's suppose we are given an array having few elements so our task is to find the minimum value in Array so friends below you can see the algorithm to find the minimum value of an array so the name of the method is find minimum which takes in an integer array and which returns back an integer value which is nothing but the minimum value of of the array so friend let's see the demonstration of this algorithm step by step and we will take the input array which is given in this slide so friends in First Step what we'll do we'll create an integer variable and we'll give it the name as Min so this Min variable will always hold the minimum value of the array so at the start what we do is we simply take the first element of the array and we'll mark it as the minimum value of the array so here Min will have value as five and at the start we'll treat the first element as the minimum value of the array so friends the basic idea behind this algorithm is now we'll provide a for Loop which will start from the index one and which will go till the last element of an array and in inside this for Loop we'll compare each and every element of the array with the minan value and let's suppose if you find any value of array Which is less than the Min value we'll simply update the minan with that particular value so we'll start this for loop with I equal to 1 so here the value of I basically represent the index of the array and we'll check whether I is less than the length of the array or not so here you can see the length of array is six and 1 is less than six so the condition in for Loop comes out to be true so in the F block now we'll check that whether the value at index one is lesser than the minan value or not so here you can see 9 is not less than 5 therefore the condition in if block comes out to be false now we'll increment I by 1 so I becomes 2 so now we'll compare the value of index 2 which is three with the Min value which is five so here you can see 3 is less than 5 therefore condition in if block comes out to be true so friend inside this array we have found a value Which is less than the Min value so at this step we'll simply update the Min with the value which we found as the minimum value so now Min will become three so after this assignment our new minimum value becomes three now we'll again increment I by 1 so I becomes 3 we'll compare the value of array index 3 which is 15 with three and we will check whether 15 is less than three or not so here you can see 15 is not less than three so the condition in if block comes out to be false we'll again increment I by 1 so I becomes 4 and then in if we again compare that value at index 4 which is one is less than minimum value or not so here you can see the value of index 4 is 1 and we know that 1 is less than three therefore condition in if comes out to be true and we have found one more El Which is less than the minimum value so here in the F blog we simply update the minimum value with a value which we found to be the minimum so now Min will become one so after this assignment our updated minimum value would be one now we'll simply increment I by 1 so I becomes 5 so now here we will come compare the value of index 5 which is nothing but two with the minimum value which is 1 so we'll check whether 2 is less than one or not so here condition in if block comes out to be false because 2 is not less than 1 and then we'll simply increment I by 1 so I becomes 6 so when I becomes six we know that I has crossed the B boundaries of the array so the condition in for Loop comes out to be false and the for Loop terminates so after the for Loop completes whatever the value Min will hold it would be the smallest value of this array so at the last I will simply return this minimum value which is nothing but one so friends in this tutorial we have actually saw the demonstration to how to find a minimum value of an array now let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually discussed how to find the minimum value in an array we saw the demonstration of the algorithm step by step now in this tutorial we'll actually code the algorithm and we'll test this working in the main method so here I have created one class by name Min array with a main method and here I have created one array which we saw in the slide and then I have initialized this main array class so let's write the code to find the minimum value of an array so first I will be creating a public method whose return type would be the integer and the name of the method would be find minimum now this method will take an array and we have to find the minimum value of this array and we'll simply return it from this method so friends in the first step what we'll do we'll simply provide an edge case we'll check that whether array is null or not so if array is null or array do length is zero we'll simply throw an illegal argument exception stating that invalid input so here if the array is not equal to null and array. length is not equal to zero then we'll create one integer variable we'll give it name as Min and we'll assign the first value of array to it so here Min will hold the minimum value of array and here we are simply assigning the value of index zero to Min and treating it as a minimum value so now we'll provide a for Loop and we'll iterate over each and every element of array starting from one and we iterate till the end of the array so inside this for Loop we'll simply provide a if condition and we'll check that value of array aat index is less than Min or not so if the value of aat index is less than Min we know that inside the input array we have found a value Which is less than the current Min value so inside this if blog we simply update the Min value to be the value at I index and after iterating over each and every element and checking this if condition when the for Loop terminates we simply return return the minan value so friend this is the algorithm to find the minimum value of an array now let's test it working in the main method so here after creating an array and initializing this class we'll simply call find minimum method and we'll pass error to it and whatever value this find minimum returns will'll simply print it on the console so if I run the code now you can see it printed one so here you can see one is the smallest value inside this array so if I change the value to let's say zero and if I run the code now you see it printed zero because 0 is the smallest value inside this array also friend if I have pass null and if I run the code now you see it printed illegal argument exception saying that invalid input because we have passed null value for an array if I pass integer having length is zero and if I run the code now you can see it again printed inv valid input because array length is zero so friend in this tutorial we actually coded the algorithm to find the minimum value of an array and we also tested it working in the main method I hope you like this video thanks have a nice day hello everyone so in this video we are going to discuss that how we can find the second maximum value in an array so here we are given an array of integers we need to return the second maximum value now we have provided the array with some integers and we need to return the second maximum value and the second maximum value exist so for example we are given an input array 12 34 2 34 33 1 so here if you see the maximum value is 34 here we have duplicate 34 so the second maximum value is 33 we have to return return the second maximum value so despite we have duplicates value we need to return return the second maximum value which is 33 here and the constraint is the second maximum value exist so we will be given with an array of some elements in such a way that the second me maximum value will exist so let's see the demonstration of this algorithm step by step so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update now here is the algorithm to find the second Max so when we will call the method find second Max and we pass in the array having six elements 13 34 2 34 33 1 so friends the idea behind this algorithm is we create two variables one is the max and another is second Max so max will hold the maximum value in the array and the second Max will hold the second maximum value in the array and using this for Loop we will figure out which is the max and which is the second Max and at the end we will simp simply return the second maximum value so at the start what we do is to Max we assign the minimum integer value so that when we will compare Max with the actual array value we can compare it safely and here integer do Min value is actually equal to - 214 748 3648 so this is the integers Min value value which we are assigning to the max so if we have the lowest value and if we compare it with any of the value of the array then we can figure out that whether this Max needs to be changed or not and similarly to Second Max we assign the integers Min value So Max and second Max start from integers minan value now we will provide the for Loop which will iterate from I equal to 0 to I less than ar. length so I will start from 0 index 0 is less than 6 which is array. length now we will take the first array value which is at zero index which is 13 so we will compare that whether 13 is greater than our current Max or not so as the current Max is the minimum value of the integer 13 is actually greater than Max now what it suggest is we need to update Max to 13 because we have found one maximum value in this array till this point so this condition comes out to be true it means we have found a maximum value now here we need to update 1 to Max because we have found a value which is greater than Max so max will become from 13 but before updating this part array of I to Max when we will update array of I to Max Max will become 13 but but as Max has changed to a new value whatever the max old value was it will become our second Max so for example let's say if second Max would have been one and Max would have been two and let's say array of I is 13 for example so before assigning 13 to Max we need to assign two to Second Max because after this assignment second Max will become two and Max will become 13 so here as Max has been updated to 13 whatever the value Max had that will become our second Max because that value is lesser than the actual max value so therefore we need to be careful while updating the max to array of I before updating Max to aray of I we need to assign the old Max value to Second Max because this Max will now become our second Max So currently max value is integers Min value and second Max is also integer on Min value so when we will assign Max to Second Max the value won't change it will be still integer do Min value and now 13 will be assigned to Max so this value will be assigned to Max so max will become 13 moving ahead we will increment I I becomes one 1 is less than 6 now 34 is greater than Max which means 34 is greater than 13 max value is 13 so 4 is greater than 13 so this condition comes out to be true and we know that when we will update Max to 34 we need to assign the old Max value which is 13 to Second Max so here before updating Max to 34 we will assign its value which is the old Max value to Second Max so second Max will become 13 because this value comes here and Max will become 34 moving ahead we will increment I I becomes 2 2 is less than 6 so friends here you can see that if you would have given an array of these two elements then Max would have been 34 and second Max would have been 13 so these two steps are critical when we will update Max to any actual array value we have to assign that old Max value to Second Max because as Max is actually changing its value its old value will become our second Max So currently array of I which is two it's not greater than 34 which is our max value so therefore this condition comes out to be false and the else part will be executed now why this else if condition is provided because let's say here value would have been 14 for example instead of two it would have been 14 so 14 is not greater than 34 and then we have provided lse if condition where we are checking that there could be a possibility that 14 is actually greater than 13 which which is our second Max it means we have to update second Max to 14 because if a value is not greater than Max but this value can actually be greater than our second Max so therefore after this condition we have to provide an lse if we need to check whether array of I is actually greater than second Max or Not So currently 2 is not greater than 13 which is our second Max X so this condition comes out to be false we will increment I I becomes 3 3 is less than 6 which is array. length now here you can see this is one critical step array of I is 34 34 is actually equal to Max but not greater than Max so this condition comes out to be false now in the lse part the first if condition 34 is greater than 13 which is true and if it is true but still we can't update 34 to Second Max because we need to provide yet another condition in the end part which will check whether whether array of I should not be equal to Max it means it is checking for the duplicate max value so let's say our Max is 34 and if you have found 34 again so we have to compare this array value 2 over Max and they should not be equal array of I should be greater than second Max which is true but 34 should not be greater than the max which is 34 so this is false so therefore the overall condition with this end operator comes out to be false so therefore though 34 is greater than 13 which is this condition still we won't update 34 to Second Max because 34 is actually our max value which we have figured out here so therefore this overall condition comes out to be false we will increment I I becomes four [Music] 4 is less than 6 now here you can see array of I which is 33 33 is not greater than 34 which is our Max so this condition comes out to be false in the L If part 33 is greater than second Max which is 13 so 33 is greater than 13 and we need to compare whether 33 should not be equal to Max so 33 is not equal to 34 so therefore this condition is also true so therefore now we have found one Contender which can be our second Max which is 33 so this condition comes out to be true we will update second Max to 33 moving ahead we will increment I I becomes 5 5 is less than 6 so this condition is true array of I which is 1 1 is not greater than 34 so this condition comes out to be false array of I which is one one is not not greater than the second Max which is 33 so this condition comes out to be false and overall condition comes out to be false we will increment I so it will go out of the array boundaries I will become six so 6 is not less than 6 so therefore this for Loop will terminate now and at the end we will return the second Max which is 33 so friend this was all about how to find the second maximum value in an array I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we will discuss that how we can move all the zeros to end of an array so here we are given a problem that given an array of integers write a function to move all zeros to end of it while maintaining the relative order of the non-zero elements so friends for example you can see that we are given with an array of integers 0 1 0 4 12 now our task is to move the zeros to the end of the array and we have to move it such a way that we have to maintain the relative order of non-zero elements so here you can see that the first nonzero element is one then it's four and then 12 so we have to move this both zero to the end of the ARR in such a way that this order is maintained 1 4 12 so the solution would be that when we'll move the zero after that the first nonzero element is 1 then 4 then 12 and both the zeros are at the end so let's move ahead and see the algorithm for it and we'll see the demonstration of the algorithm step by step so here you can see that we are provided with this algorithm where the method name is move zeros which takes in an integer array and a value n which is nothing but the length of the array so when we will call move zero method and let's say we provide this array having the elements as 8 1 0 2 1 03 going from index 0 to 6 so therefore the value of n will be 7 because there are seven elements moving ahead so here the idea behind this algorithm is that we usually take two pointers and let's say we provide name to it as I and J so one pointer basically focuses on the non-zero elements and the other pointer focuses on the Zero elements and when this two pointers where one is at nonzero element and the other is at zero element we simply perform a swap so here you can see that we are starting from Z equal to0 and I equal to Z and in this algorithm J Will basically focus on the Zero elements and I will focus on non-zero elements so here you can see that value of G J is zero so we are simply representing it as like this but it is basically storing an integer value zero moving ahead now friends as you want to travel each and every element of this array and try to move zeros to the end of the array we need to Traverse complete array so we have provided a for Loop where I will starts from zero and this will go till the end of array where we provide this condition as whether I is less than n or not so value of n is 7 so I will travel till 6 and after each iteration of this for Loop we simply increment I by one and we also discussed that J will focus on zero elements and I will focus on nonzero elements and we will perform the swipping of elements When J Will point to zeroth element and I will point to non-zero element so let's see the demonstration of this algorithm step by step so here value of I is zero and I is also less than 7 so the condition in for Loop comes out to be true so the first step we check that the value of aat index is non zero or not so here we can see the value of I is Zer and the value at zeroth index is 8 so therefore this condition is true and we also check whether value of jth condition is equal to zero or not so here you can see value of J is also zero so the value at zero to index is 8 therefore this condition is false and we also know that when this both the condition will be true then only we will perform the swap but currently the second condition comes out to be false because the value at zeroth index is 8 which is not equal to zero so we simply move ahead the value of jth index is 8 which is non zero so therefore we'll simply increment J by 1 so J becomes one and while we are traversing J by one because we need to find a value at any particular index which is zero so that J could reach there and we can perform this swap moving ahead now we'll increment I by 1 so I becomes 1 and 1 is less than n therefore this condition also comes out to be true so for Loop executes we check value at aat index is zero or not so value of a index is 1 which is not equal to zero so this condition is true and we also check value at jth index so the value at J J index is also one but this condition comes out to be false because it is not equal to zero so therefore the condition in if blog comes out to be false and we check whether value at the J index is 0 or not so here you can see the value of J index is non zero therefore this condition comes out to be true and we simply increment J by 1 so J becomes 2 now we'll again increment I by 1 so I becomes two and also here you can see the value of I which is two is also less than 7 so therefore this condition also comes out to be true and for Loop executes now here you can see the value at aat index is basically equal to Z Z therefore this condition comes out to be false and we don't evaluate this condition because of this end operator so this if block condition comes out to be false and we are checking the value of Z index is zero or not so here you can see the value at Z index is zero so therefore this condition also comes out to be false because we have incountered zero and J should focus on zero elements so that we can perform a swap so this condition comes out to be false and J stays at the same position now we'll again increment I by 1 so I becomes 3 and 3 is less than 7 so for Loop executes so here you can see that now we have encountered a interesting situation where J is pointing to zeroth element and I is pointing to a non-zero element so this condition where the value at I at index is not equal to zero so this condition comes out to be true and the second condition also comes out to be true because J is pointing to Value two and the value at second index is zero so therefore this condition also comes out to be true and overall if condition comes out to be true so now this if blog will execute and we need to perform this swap so we are creating this temporary variable to store one of the values so we are simply storing the value at aat index into the temporary variable so two is stored into this temporary variable because we need to perform the swap so somewhere we need to store this value and now we are storing the value at J and index into the value of I index so value of J index is zero and we are assigning this zero to valuate aat index so it would look something like this that zero will be assigned to the aat index moving ahead and finally we'll assign the value showed in temporary variable to J index so it would look something like this so here we have simply swiped these two values and after this swiping we again check that value of J index is equal to zero or not so here you can see the value of J index is two so we simply Traverse J by 1 so J becomes 3 now we'll again increment I by 1 so so I becomes 4 and 4 is less than n therefore for Loop executes so friends here you can see the value of aat index is 1 which is not equal to zero so this condition is true and the value of J index which is zero is equal to zero so this both condition comes out to be true and when both condition comes out to be true we know that we have to perform a swap so we will store one into the temporary variable we'll assign the value at J index which is zero and we'll simply assign it to the value at I index so it would look something like this the zero has been assigned to the fourth index moving ahead and then we'll simply assign the value stored in a temporary variable to the J index because we need to perform this swap we again check what's the value at Z index so here you can see the value is one so 1 is not equal to zero therefore this condition comes out to be true and we'll increment J by 1 so J becomes 4 so friends the whole idea behind this check is that we need to Traverse J so that it reaches to any zero element so that we can perform a swap so here the value of J's index is non zero therefore we are incrementing J by 1 so J becomes 4 we'll increment I by 1 I becomes five and five is less than 7 so this condition comes out to be true and now here you can see the value of J index is zero so this condition is true but this condition is not true because value of aat index is equal to zero so this condition comes out to be false and this if block will not get executed and now as J is pointing to the zeroth element so this condition also comes out to be false we'll increment I by 1 so I becomes 6 and 6 is also less than 7 so the for Loop will execute so in the first condition we'll check whether value of I index is zero or not so here you can see the value of I index is three 3 is not equal to zero so this condition comes out to be true and then we will check whether value at Z index is equal to Zer or not so the value at jth index is zero therefore this condition also comes out to be true so we need to Simply perform a swap so we'll store three into the temporary variable and then we will swich have Zer to this position by assigning value at the jth index to the a index so this will become zero and at the last step we'll assign the value three to the jth index so three will come here and here we will simply check whether the value of J index is zero or not so value of J index is non zero so therefore this condition also comes comes out to be true so we increment J by 1 so J becomes 5 and here we'll increment I by 1 again so I becomes 7 but now here you can see 7 is not less than 7 so the condition in for will comes out to be false and this for Loop will exit so after this for Loop will exit so here you can see that this array had two zero elements in the between and we have simply moved them to the end of the array by maintaining the relative order among the non-zero elements so friend this is one of the simple algorithm to move the zero elements to the end of an array now let's go to intelligent and see the working of this code so friends I hope you like this video and in case you have liked this video then please like comment share and subscribe my channel thanks every ni J hello everyone so in this video we'll simply code the algorithm and we'll see that how we can move the zero elements to the end of an array so here you can see that I have created one class as move zeros so this class is one main method and it calls the error demo method so where we have created this array which we also saw in our previous video and we have this one method print array which we already discussed in one of our previous videos so if I run the main method so here you can see it simply prints the array on the console as 810 2103 so these are nothing but the elements of array which has two zero elements so we need to move this two Z elements to the end of the array by maintaining the relative order of the non-zero elements so let's code the method so we'll create public void we give the method name as move zero and as we discussed in our previous video that this method will take one integer array and one value n which is nothing but the length of the array and we also discussed the idea behind this algorithm is we take two pointers let's say one s j which will focus on zero elements and one pointer is I so here I will focus on nonzero elements and as we want to iterate each and every element of this array will provide this for Loop where I will Traverse from zero and it will go to a value lesser than the length of the array which is nothing but the value n and after each iteration we'll simply increment the value of I by 1 so in for Loop what we do is we provide a condition and here we'll check the value stored at IOD index is not equal to zero because I will focus on non-zero elements and and if the value of J index is equal to zero because J will focus on zero elements so if these two conditions are equal then we'll simply perform a swap by taking a temporary variable so here we are assigning the value of I index to this temporary variable and then we are simply swapping the value of jth index and storing it on the aat index and at the last step we are taking the value of the temporary variable and storing at the jth index so this will simply swap the value of the ith and jth index and after we perform swap we'll provide one more if condition with where we simply check that value of jth index is not equal to zero so if the value at J's index is not equal to zero we'll simply increment J by 1 because that is not the value that J is focusing on J will only focus on the Zero elements so this is the condition so friend this is the algorithm to move the zeroth elements to the end end of an array now let's see the demonstration of it now after printing the array we'll simply call move zeros we'll pass the array and we'll pass the value of NS array. length and after moving the zero to the end of the array we'll simply print the array again and if I run the main method again so friend here you can see that initially array was 810 2 1 03 which had two zero elements and after we perform this algorithm where we are moving the zeros to the end of the array the value stored was like this 81 21 3 where both the zeros came to the end of the array and even the relative order of the non zero elements remain the same with 8 1 2 1 3 8 1 2 1 and 3 so here we simply coded an algorithm where we moved the zeros to the end of the array so friend this was all about this video in case you have liked this video then please like comment share and subscribe my channel thanks have a nice day hello everyone so friends in this lecture we will discuss how to resize an array in Java so friends as you all know that when we initialize an array we provide a size that how many elements this array can hold and this size we have to provide when we are creating an array object but sometimes what happen that we don't know that how many elements can be there in an array at the time of initialization so therefore doing the resize of an array is a very common operation in many algorithms so for example when we use array list inside the array list we create an array of default size and when we add elements to that default size it gets stored in the internal array and as soon as we try to add one more element so internally what happens a new temporary array is created with a size more than that of the original array and then all the elements are copied from the original array to this temporary array and finally the original array points to this temporary array so friends now let's see the demonstration of this algorithm so here is the algorithm and let's say we have this array whose length is four because it can store four elements and here you can see that all the elements inside this array are filled so therefore there is no more additional empty space left to add more elements and if suppose if you want to add more elements what we do is we simply call this resize method by passing in an array and we provide a capacity that how much more elements you want when this resize is done so let's say we call this resize method by passing in the array and whatever the length we have let's say four we simply want to double the length so we pass the capacity as8 so now this method will be called with the capacity as 8 and by passing this array moving ahead so so friends once we initialize this array we can't add more elements to it so what we do is we create a temporary array for whatever the capacity we provided so here we'll create a temporary array whose capacity or size would be eight so now this temporary area will range from 0 to 7 storing the at Elements which is nothing but the capacity of this array moving ahead now friend as we have created this temporary array our other task would be to copy each and every element of this array to this temporary array so in order to do that what we do is we provide a for Loop which starts from zero index and goes to the array do length minus one index so here value of I will be zero when this for Loop starts it will simply point to the zero index and we know that value of I which is 0o is less than four so therefore this for Loop will execute and in the for Loop what we'll do we'll simply copy the value stored at the ith index which is the zero index to the temporary array at the a index which is zero so here what we are simply doing we are simply copy in this value which is five to this temporary array at zero index so it would look something like this so f is copied here so now we'll move ahead now we'll increment the value of I so I becomes 1 it simply means that we can use this I to point to the first index and value of I which is 1 is less than four so this for Loop executes and now we'll simply again copy the value of aat index which is the first index to this temporary array at first index so it would look something like this moving ahead we'll increment the value of I by 1 so I becomes two it will point to the second index now now we'll copy the value at second index to this temporary array so it would look something like this the three is copied from the second index to Temporary ARR at second index moving ahead we'll again increment the value of I by 1 so I becomes three so it will point to the third index now and we know that 3 is less than four therefore the for Loop will execute and finally we simply copy the value stored at the third index to this temporary array at the third index so it would look something like this moving ahead we'll increment the value of I by 1 so I becomes 4 and we know that 4 is not less than four so this condition comes out to be false so therefore for Loop will terminate which actually makes sense because we have copied all the values of our original array to this temporary array so this for Loop will exit and at the last step what we'll do is here you can see that this temp variable is pointing to this array object in a heap and our array is pointing to this object in Heap so now what we'll do whatever the value is stored in this temporary array we'll assign to our original array so it simply means that we are reassigning this array to this array so it would look something like this that now this array will point to this temporary array which is nothing but pointing to an array object in Heap so friends after this resize method gets executed our original array is pointing to an array having size as eight but here you can see that there is issue with this code once the resize method gets executed completely here you will find this array will also get garbage collected because the return return type of this method is vo and we are not sending the value stored in this array from this method therefore whatever we did here will be garbage collected finally so instead of keeping this resize method as void what we should do is we should keep the return type of resize method as integer array and here after assigning the temporary variable to array we should return the value stored in in the array variable so that whatever the value is returned from this method and whoever is calling this method should actually get a reference to this object in the Heap memory so this is one step which is very much important and we must do that we should return the array after resizing it and also friend here you can see that we even don't need to do this reassignment here what we can directly do here is as we have copied all the elements from the original array to this temporary array and this temporary array has capacity of what we have passed we can simply return the value stored in this temporary array instead of assigning it to array variable and returning the array variable we can simply return the value stored in this temporary variable so friends this was a demonstration of how to resize an array using this animation now let's go to eclipse and see the working of this code I hope you like this video thanks of a nice day hello everyone so friends in our previous lecture we saw that how we can resize an array through an animation now in this lecture we'll code the algorithm and we'll see it's working inside this main method so in our array util class here I will be creating one method as public void and I will give the name to this method as resize now as we discussed in our previous lecture this resize method will take the array which we want to resize and it will take the capacity to which we want to resize so this is nothing but an integer value so what happens here is let's say our array has size four and we want to resize it to 8 10 16 or whatever value we want we simply pass it here so in the first step what we do is as you have already created this array of a particular size we can directly resize this array to this capacity so what we do is we first create a temporary array having the sizes the capacity we provide now after creating this temporary array what we do is we simply copy all the elements of this array to this temporary array so in order to copy all the elements of our original array to this temporary array what we do is we simply provide a for Loop Loop and inside this for Loop we simply iterate each and every element of our original array so here you can see this for Loop will iterate with a value of i as Zer and it will go till the length of our original array minus one and inside this for Loop what will will do we'll simply assign the value stor at aat index of our original array to our temporary array at aat index so when this line will execute what it will do is it will go to our original array it will take the value from the a index and then it will go to our temporary array to a index and simply copy the value from our original array from the at index to the temporary array at add index so this copy will go from the zeroth index and it will go to the last index of our original arrays which is array. len minus one index so after we copy each and every element from our original array to this temporary array what we do is at the last step we simply assign the value stored in the temporary array to our original array so when this line will execute the temporary array which we created here which was pointed by this temp variable now our original array variable will point to this temporary array which is capacity of what we have provided here so after this method get executed the original array has been resized to this capacity because at the last step we are simply assigning the value stored at the temporary variable to the array variable so initially this temp pointed to an array in an Heap which had this capacity now what it means is our array will point to this array in Heap so friend this piece of code simply resizes the array so let's see the demonstration of it I'll just copy this array initialization and I'll just command this print array call here we'll create an array we'll give it a name as original and we'll simply paste this part here so our original array has the size of storing five elements so when let's say if we want to store more elements so we can't store here so then we have to resize this original array so what we do is here I'll simply provide a s out and here I simply print the size of original array and let's say provide a value as original do length so friends if I run the code now so here you can see it printed the size of original array is five now friend as we want to resize it what we do is we simply call the resize method we pass in our original array and let's say we want to resize this array to a capacity of let's say 10 so we pass the value of capacity as 10 so friends after resizing the array we will'll simply print the size of original array after resize now what happens when I call this again the size of the original array after resize and I simply print original dot length so what it should print it should print five or 10 so friend here it looks that we have resized this original array to a capacity of let's say 10 we have even copied the contents so we usually think that when we print original do length here it should give the answer as 10 but if I run it you will see that it gives answer is five because though we have passed this original array here but when this method gets terminated this temporary array and everything will be garbage collected and whenever call will reach this point the original array will be still pointing to this so what we do here is we have to return return this array from this method and instead of void we have to give return type of the integer array so that here we can get this array as we are returning it from here and we can store it in the original and finally we can print the length of this original array and here if I run the code now you can see that now this original array is actually pointing to this resized array so friend this is one of the most smallest mistakes we usually make because we know that Java is pass by value so we are passing the value stored in the original array here we are doing resize on this temporary array and this array variable and if you're not returning it back then this all will be garbage collected and our original will be pointing to this array only so here we are returning this array we are storing it here so now we have actually reassigned it to a different array by this line and when we printed the length of this original array now it gave the value as 10 and also friends what we can do is here instead of assigning it to array we can even return something like this because we have copied the content of this array to this temporary array so instead of assigning the value of this temporary variable to array variable we can directly return something like this and if I run the code now you can see it again printed the size of the original array after resizes 10 so here now we have actually resized this original array so friend this method is used very frequently in many other data structures which involves the array internally so friends I hope you like this video thanks have a nice day hello everyone so in this video we will be looking into a problem find the missing number in an array so here let's suppose we are given an array having n minus one distinct numbers and basically in the range of 1 to n we need to find the missing number in it so it is a very famous interview question where you will see that we are given with numbers from 1 to n so this n could be let's say we are given with this array here you can see that there are seven numbers ranging from index 0 to 6 so it's basically the array do length which is 7 and here you can see the range is from 1 to n so here you can see in this seven numbers we are given a range from 1 to 8 and one number is missing in this so we need to find that number so for example here you can see one is present two is present three is present four is present 5 is not present 6 7 and 8 are present so basically we are given n minus one distinct numbers which you can see here and 1 to n is the range so here it is from 1 to 8 so your n is 8 and in the array we have provided with n minus one which is seven numbers so we need to find one missing number so here the output would be five so this is the missing number from range 1 to 8 which we can see in the array so let's see how we can solve this problem so one constant is we need to find it in O of n time complexity so let's see how we can find the missing number in this array so here you can see there is one mathematical formula which can help us in evaluating that what's the missing number in the array so the mathematical formula is something like the sum of first n natural numbers which is 1 + 2 + 3 + 4 till n is given by this formula that we simply do n into n + 1 by 2 so for example if we want to do sum of first four natural numbers so we can do 4 into 4 + 1 by 2 so this will give us 4 into 5 by 2 which is 20 by 2 which will be equal to 10 so here can see 1 + 2 will give 3 3 + 3 is 6 6 + 4 is 10 so this is the formula which help us in evaluating the sum of first and natural numbers so we will use this formula and find the missing number in the array so for for example let's suppose we are given with this four numbers so if you do array. length we will get four numbers and as we are getting four numbers the range will be from 1 to 5 so here you can see the four numbers are 1 2 3 and 5 so the missing number is actually Four so now how we can find the missing number is first the number of elements are are four which are present in the array we do+ one to it so five will be the actual final range so what we will do here is we will use this formula to calculate the sum so we will get 5 into 5 + 1 by 2 so this will give us 30 by 2 15 so the sum of first five natural number is 15 and in order to find the missing number what we'll do is we will iterate this array one by one we'll pick each element and we will simply subtract it from the sum and after subtracting all the elements whatever number will be left that will be our answer because this is the sum of first five natural numbers and if we are subtracting four numbers from it the leftover sum would be our missing number so for example first we encounter 1 so we do 15 - 1 we get 14 then we encounter 2 so we do 14 - 2 we get 12 then we encounter 3 so we get 12 - 3 9 and then we encounter 5 so we do 9 - 5 which will give us four so this four will be our answer so here you can see that this form is very helpful in many coding problems and this is one such problem so here the missing number is four which we just evaluated using this mathematical formula now let's move ahead and see the algorithm for it so here you can see the algorithm is very simple so let's see the demonstration of this algorithm step byep step using this array so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so let's say we call find missing number method with this array and here you can see the size of this array or the length of this array seven ranging from index 0 to 6 so if length is 7 we know that the range would be from 1 to 8 and we need to find one missing number in it so first we evaluate total number of elements present in the range so if we do array. length we will get the numbers present in this array and if we do plus one because this ARR doesn't have that number which we need to find so we simply add one so n will be 8 and now we will use the formula and calculate the the sum so it will be 8 into 8 + 1 by 2 it will give us 8 into 9 by 2 which is 9 into 4 which is 36 so sum will be 36 and now we will iterate the array 1 by one using this for Loop and inside this for Loop we will subtract each number from the sum and at the end whatever the sum is left that will be our answer so let's see how first we get number two when we subtract two from sum sum becomes 34 then number becomes four 34 - 4 will give 30 then number will become one 30 - 1 will give 29 then number will become 8 29 - 8 will give 21 we encounter six 21 - 6 will give 15 now number becomes three 15 - 3 gives 12 and at the last number becomes 7 so 12 - 7 will give five and then this for Loop will end and whatever the values left in the sum that will be our missing number so here you can see one is there two is there three is there four is there five is not there 6 7 and 8 are there so at the end we'll simply return five so this question is frequently Asked in the coding interviews and if you come up with this formula n into n + 1 by 2 which is sum of first 10 natural numbers then you can easily figure out what's the missing number so friend this was all about this question I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw an animation to find the missing number in an array where we were given an array having elements from 1 to n and in that one element was missing so our task was to find that missing number so in our previous video we actually saw the demonstration of this algorithm step by step so now in this video we will actually code the algorithm and we will test it's working in the main method so here in our array util class here I'll be creating one method as public static let's say we give the method name as find missing number so this method takes in an array and it Returns the missing number so the return type is hint so here assuming the array is proper and it has various Elements which are ranging from 1 to n and there is guaranteed one number is missing in the array and we need to find that missing number so at the start we first evaluate the value of n which is the last number of our range from 1 to n so that is evaluated using array. length so this will give us the length of the array and it has one missing number so we will do plus one to get the last number of the range and after knowing the value of n what we will do is we will use the mathematical formula to calculate the sum of first and natural numbers so here in sum we will use the formula as n into n + 1 by 2 so after evaluating the sum of first and natural numbers what we'll do we will iterate the array 1 by one and as we need to find the missing number what we can do is we can subtract each element from the sum and whatever the sum will be left that will be our final answer because this formula is giving us sum of first and natural numbers and among those first 10 natural numbers in the array we have n minus one numbers so if we subtract n minus one from the sum we will be left with the missing number so here we simply do sum equals sum minus number and after this for Loop we'll simply return the remaining sum which will be our missing number so now let's test it's working in the main method here we are given with an array so here you can see the length of the array is seven but the range is from 1 to 8 and we need to find the missing number so we will call find missing number we pass in the array and if I run the main method so here you can see it actually returned number five from this method it means five was the number which was actually missing so here you can see one is there two is there three is there four is there five is not there 6 7 and 8 are there so so friend this problem is asked in many coding interviews where we can use one single for Loop and this mathematical formula to evaluate the missing number from the range 1 to n I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so friends in this lecture we will discuss that how we can check that a given string is a palindrome or not so friends what is a pandrum string so a pandrum string is a string when we do reverse of it and compare it with the original string they both are same so for example let's say we are given a string Madam so if we read this string in forward direction we get m a d a m Madam and if you read it from backward we get m a d a m which is the same so therefore this string is a palindrome string so let's say we are given a method in which we are passing a string it should return return true if the string is palindrome or it should return return false if the string is not pend drum so friend in second example you can see that we are given a string that if we read it in forward direction we get t h a t and if we read it from backwards direction we get t a h t so here you can see that if you reverse that and if we compare the reverse string with the original string they are not equal therefore this string is not pendro so friend let's see is a demonstration of the algorithm step by step so here you can see that this is the algorithm where we are calling the method is palindrome and we are passing in a string and if the string is palindrome or not we are simply returning a Boolean value that if a string is palindrome we return true and if it is not then we return false so let's say we call this palindrome method and we pass a string as m M so by looks of it you can see that Madame is a palindrome string because if we reverse Madam and compare it with the original string they both are equal so let's see how we can figure it out that whether Madame is a palindrome or not so string word will hold the Valu as mom so friend in this algorithm what we do we take two pointers one we place at the start and another we place at the end and we just compare these two characters and if they are same then we move first pointer ahead and the last pointer backward and then we compare the second character with the second last character and if they are equal then we simply move ahead the first pointer and move backward the last pointer and similar we keep on checking the Valu stored at these two pointers and if anytime these values are not equal we can come to know that the string is not a palindrome string so friends here in order to compare this string character by character we first convert this string to car array so in Java string has this method to car array which returns a character array so it would look something like this the character array will store one one character at each index and it is in form of an array moving ahead so we'll initialize the first pointer we'll give it a name as start and it will start from the zero index so value of start is zero and we'll also initialize an end pointer whose value will be word. length minus one so here on a string if we do what do length we get the length of the string so here we'll get the length of the string as five because there are five characters and when we do minus one it simply means that this pointer will point to the last index so end value will be four 5 - 1 will give four so friends we have got our two pointers and one is at start and other is is at an end now we'll start comparing the character stored at start index and the end index using this while loop so this while loop will run till start is less than end so if the start becomes equal to end or more than end then we know that we have traversed this complete string So currently you can see that start value is zero and end value is four so therefore the condition in while loop comes out to be true so friends we know the palindrome property that if you read the string in forward Direction and if we read the string in backward Direction both the strings should be equal so friend it means the first character should be equal to the last character second character should be equal to second last character and it should go on till we reach a midpoint and if any of these characters are not equal then we can come to know that that string is not palindrome string so here we are comparing the character stor at start index and character stored at the end index so which is these two characters and we are checking that if that whether they are equal or not so if they're not equal we can straight away return false that string is not PM string but here if you see m is equal to M therefore the condition in if block comes out to be false so we have compared the first and the last character now we'll proceed to compare second character with second last character so fored what we need to do is we need to increment start and decrement end by one so here we'll increment start by one so start will become one and then we will decree End by one so end becomes three we check whether start is less than end or not so 1 is less than three therefore condition in while block comes out to be true and here we simply check that whether character stored at start index and character stored at end index are equal or not so as value of start is one it will point to this character and end is three so it will point to this character so we are simply comparing this character with this and here we know that these two characters are equal therefore the condition in if block comes out to be false and then we'll simply increment start by one and decrement end by one so start becomes two and end becomes two so friend here you can see start and end will point to index two which is D and this is the only index left now and if you check whether start is less than end so here you can see two is not less than two therefore condition in while block comes out to be false and we don't compare this because if even if we compare D with d we know that there those are equal but as this is the only character left if we read the string from this point or if we read the string from this point this character will be at the same position so therefore we never check for start equal to end we simply do start should be less than end so here condition in while block comes out to be false and while loop terminates and as soon as while loop terminates if our execution Point reaches here we know that the string is bent room because we have compared every character from start to end so we finally return return true therefore string Madam is a pandrum string so for now let's see whether that is a pandrum string or not so here we call this pandrum method providing a string as that we will convert this string to character array by calling two car array method so it would look something like this that set character array having length is four storing each character in each of the index of this array moving ahead we again create two pointers one starts from the beginning and other starts from the end so we create two integer VAR start we'll give it a value of zero and we create integer variable end which points to the last index and in order to get the last index we do word do length minus one so word do length is the length of the string which is four if we do minus one we get the third index which is this so end becomes three moving ahead we see whether start is less than end or not so here you can see 0 is less than three so condition in while block comes out to be true so now we compare the value at start index and the value at end index which is these two characters and we check whether they are equal or not so if they are not equal then we can simply return for false because string is not pend Drome but here you can see T is equal to T therefore condition in if log comes out to be false so now we move start pointer a step ahead and we move endp pointer a step backward and then we'll compare these two characters so start becomes one and end becomes two so we check whether start is less than end or not so here you can see 1 is less than two so the condition in while block comes out to be true and then we'll simply compare the value stored at the start index with end index so here you can see that H is not equal to a which means the condition in if log comes out to be true and we come to know that string is not a pandrum string because this should have been equal to make it a palr string but here H is not equal to a therefore condition in if blog comes out to be true so finally we return return false from this point that string is not a palindrome string so friend in this lecture we saw that how we can check that whether a given string is a palindrome or not we saw the demonstration of algorithm step by step now let's go to eclipse and see the working of this code I hope you like this video thanks have a nice day hello everyone so friends in our last lecture we saw that how we can check that whether a given string is a palindrome or not we saw the algorithm using an animation so in this lecture we'll actually code the algorithm and we'll test its working in main method so here I will be creating one method as public and as we want to check whether a given string is a palindrome or not the method which we are creating should return a Boolean value that whether a given string is palindrome or not we also provide the method name as is palindrome and into this method we provide a string let's say we give the name to it as word so friends here we are not seeing any edge cases so in order to check whether the given string is a palindrome or not what we do is we first convert this string to a character array by using the method provided in a string class as two care array so this method returns a character array so whatever the characters are stored in this string it will be now in form of an array where each index will store one character also friends in last lecture we discussed that we are using two pointers to check whether the string is palindrome or not so one pointer will start from the beginning so to start we are providing a value as zero another pointer will start from the end and to this we provide the value as word. length minus one so word do length minus one will give us the last index so friends now we'll start comparing each character at start and end index so we'll provide a while loop and we'll iterate in this V Loop till start is less than end so inside this V Loop the first step we do is we check red weather character at start index is equal to character at end index so if they're not equal then we can straight away come to know that string is not a palindrome so here we'll simply return false because as we are starting comparing first index with the last index to make string palindrome those two characters should be equal and if if they are not then we can simply return false so friend after doing this first comparison what we do is we move start a step ahead and we move end a step backward so that after comparing this we compare the second character with the second last character then third character with third last character and similarly till start meet end because we are incrementing start and decrementing end also friends here you can see that when the value of start will be equal to end this V Loop will terminate and we know that inside this V Loop we never got any chance that character at start is not equal to character at end so therefore once file Loop terminates we can come to know that string is palindrome and we simply return return true so friend this is the algorithm to check whether a given string is palindrome or not so let's test it's working in main method so here we'll create instance of string util class and here we provide F condition if we simply check by calling this pel androme method and we pass the value as let's say Madam and if it comes out to be true then we simply print the string is palindrome or else we print the string Is Not Bent room so friends if I run the code now so here you can see it printed the string is pend Drome because if we reverse Madam and if we compare with the original string they both are equal now friend let's say if I provide the string as t a which is not a palindrome string because if we reverse the string we get t a HT which is not equal to our original string and if I run the code now you can see it printed the string is not well in room so friend this lecture we wrote the code to check whether a given string is a palindrome or not we tested its working in main method I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to create a singly link list in Java so friends here you can see a simple singly link list in our previous tutorial we discussed what is a singly link list we discuss the singly linklist is a data structure which actually stores collection of data it contain sequence of notes so here you can see that there are four notes having data is 10 1 8 11 and you can also see the first note is being referred by the head so this head node actually holds complete link list and it is also the first node of the singly link list and you can also see the last node whose next always points to null because it signifies that it is the end of the list we also discussed that node is having two properties one is the data property and one is the reference to the next node in the list so friends let's see a demo to how to create this singly link list having the data is 10 1 8 and 11 so friends here is the code which can add few notes in the singly link list we will also discuss the other ways to insert the nodes into the singly link list so let's see the demo of the code step by step so friends when we initialize a singly link list it contains instance variable head which is of type list node and when we initialize the singly link list usually head points to null because at the initialization of the singly link list there are no elements into the list so at first head points to null moving ahead now in this step what we do is we first create a new list node and we pass the data into it so here we are creating a new list node and we are passing the data as 10 so it would look something like this here you can see the data is 10 and whenever we create a new list node it next points to null and also here you can see when we are creating this new list node we are assigning its value to the head so currently head points to null and after this assignment it would look something like this so now head will point to this first node which is having data as 10 and its next is pointing to null moving ahead and in this step we are again creating a new list node and we are assigning its value to the list note by name second so it would look something like this that second is pointing to a list note having data and whose next is pointing to null moving ahead now here similarly we are creating third list note having data it and we are naming the variable as third so it would look something like this the third is pointing to a not having data as it and whose next is pointing to null moving ahead and now we are creating a list note having data as 11 and we are assigning its value to a list node by name fourth so here you can see the list note fourth is having data as 11 and whose next is pointing to null so this is how list node is created we create a list node by passing into data and whose next always points to null so friends in order to create a singly link list what we do is like we connect all these four nodes together and form a chain so this chain is built something like this we connect first Noe to second second to third third to Fourth like that so in order to achieve this what we do is here we know that head points to a node having data is 10 and whose next is pointing to null so in order to connect these two nodes what we do is we assign the of second to Heads next so here you can see second is pointing to node having data as one and head next is pointing to null so if we assign the value of second to Heads next so instead of pointing to null now it will point to Second node because second is pointing to this node moving ahead and now in this step what we do is we assign the value of third to seconds next so here second seconds next is pointing to null and third is pointing to a node having data as eight8 so whatever value is in the third we assign it to seconds next so it would look something like this moving ahead and in the final step what we do is we assign the value of fourth to thirds next so this fourth list note is pointing to a node having data 11 and whose next is pointing to null so we simply assign the value of fourth to thirds next so it would look something like this so now finally the third node is pointing to a node 4 so friends when method ends all this three note goes away and as head is the instance variable of the singly link list it is holding this complete list together so friends let's go to eclipse and see the working code so friends in our previous tutorial we created a class by name singly link list and to this class we provided an instance variable of the type list node by name head so here the instance variable list node by name head will actually hold the link list for us and friends we also created one static in our class list node in our previous tutorial whose Constructor only took the data part so now let's move ahead and create a singly link list what we actually saw in the slide in the previous tutorial so we'll create a main method so inside this main method first we will initialize the singly link list so friend as soon as we initialize a singly link list the value of head is null so here we'll create the four notes what we actually saw in the slide in the previous tutorial so to head we'll assign newly created list node having data as 10 then we'll create a second list node having data is one then we'll create a third list node having data it and finally will will create a fourth list node having data is 11 so friends here we are having four notes now we will connect them together to form a chain which is nothing but our singly link list so in order to form a we'll first assign the value of second to Heads next because currently head next is pointing to null so so this would make structure something like this moving ahead we'll connect second with third by assigning value of third to seconds next so it would make structure something like this and finally we will assign the value of fourth to third next in order to connect third and fourth so third next we'll assign the value of four to it so it would make structure something like this so here you can see that we have connected all these four notes together so it would look something like this that 10 is pointing to one one is pointing to 8 8 is pointing to 11 and finally 11 next is pointing to null because there are no more notes we have attached to this fourth note so friend this is how we connect the notes of a singly link list together in our upcoming tutorial we will discuss a more generic way to insert the node into singly link list I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to print elements of a singly link list in Java so friends let's suppose we are given the singly link list having four notes with the data is 10 1 8 and 11 so in this tutorial we will discuss how we can print the data of the elements of the singly link list so below you can see the algorithm of it so currently in the console you will see no output so so let's see the demonstration of this algorithm step by step now in the first step what we do is in order to print the elements of the singly link list we need to Traverse each and every note one by one and we are given with the head node which is the first node of the singly link list so we actually start traversing from this first node only so in order to start traversing from this head node what we do is we temporarily create a list node which points to this head node so the name of this list node is current and we assign the value of head to it so it would look something like this that we are having a list node by name current and it is pointing to head moving ahead now in this algorithm we encounter a while loop and in while loop we place a condition that whether current is equal to null or not so why we put this condition because once current is equal to null we come to know that we have traversed the list completely so therefore we come to know that there are no more elements left to be traversed so initially now as current is pointing to this first node we know that it is not null so therefore condition in while loop comes out to be true and the code inside the while loop executes so in the first step what we do is we simply print the data associated with this current node so it would look something like this the data associated with this current node is 10 moving ahead so friends as we have traversed this node now it's time to move to the next node so in order to move to next node what we do is so friend if you assign the current next value to current what will happen is as current is pointing to this first node having data as 10 now it will point to the second node having data as one so here simply what we are doing is current next is pointing to second note and this value we are assigning to current itself so it would look something like this by this assignment we are simply traversing current to its next by assigning current next value to current moving ahead we again check whether current is equal to null or not so here you can see as current is pointing to Second node it is not equal to null so the condition in while block comes out to be true and we simply print current data on the console so current data is nothing but one so it would look something like this moving ahead so friends as we have not travs the second note now we need to move to the third node so the only way to move to third node is current's next because current next is pointing to this third node so if we assign current next value to current current will now point to the node having data is eight so it would look something like this moving ahead so friends here again current is pointing node having data as it so it is not equal to null therefore the condition in while block comes out to be true and then we simply prints the data associated with this current node which is nothing but eight moving ahead now we simply assign the value of current next to current to Traverse to the fourth node so it would look something like this moving ahead now again we know that current is not equal to null because it is pointing to a node having data is 11 so therefore the condition in while block comes out to be true we then print the data associated with this current node which is nothing but 11 moving ahead and then we simply Traverse current to its next so current is pointing to this fourth nodee and its next is pointing to null so we simply assign the value of current next which is null to current so it would look something like this moving ahead so friends we already know that the list is traversed completely and we have printed all the notes of the singly link list so now the current is pointing to null so in the while we check whether current is equal to null or not so here you can see current is equal to null so the condition in while block comes out to be false and we know that when this condition comes out to be false the list is completely traversed so now the statements in the while loop doesn't execute and in the last we simply print null so on the console it will print something like 10 is pointing to 1 1 is pointing to 8 8 is pointing to 11 and 11 is pointing to null stating that after 11 there are no more notes so friend this is the algorithm to demonstrate how to print the elements of a singly link list now let's go to eclipse and see the working code Hello friends in our previous tutorials we have actually created this class by name singly link list we also created a list note class and in our previous tutorial we also created four notes and we connected them together so here they are connected in the form as 10 is pointing to 1 1 is pointing to 8 8 is pointing to 11 and 11 is pointing to null because here what we have done is head next is pointing to second second next is pointing to Third and third next is pointing to fourth so in this way they are connected to each other and in this tutorial write the code which will actually demonstrate how to print the elements of a singly link list on the console so here first we'll create a method as public void we'll give the name of the method as display because it will be printing the elements of a singly link link list on the console so friends in our previous tutorial we actually saw the animation of this algorithm so here now we'll code this algorithm so first we'll create a temporary node by name current and we'll assign the value of head to it and then we actually saw in the animation slide there was a while loop into which condition was that we were checking whether current is equal to null or not so if the current was not equal to null we were printing the current's data on the console and then we are traversing the current to its next so here here we will print currents data on the console and then we'll simply Traverse current to his next by assigning current next value to current and once the current is pointing to null we know that we have reached to the end of the singly link list so there are no more notes left to be traversed so in the final step we'll simply print value as null so friends here we have already connected this four nodes together now let's test that whether they are actually connected or not so we'll simply call this display method and we'll run the code so friends here you can see it printed 10 1 8 and 11 because this head is having data is 10 and it is pointing to second note whose data is one and second is pointing to the third note having data is eight and eight is pointing to the fourth note having data is 11 and finally fourth next is null so therefore it printed null over here so friend this is how we actually print the elements of the singly link list on the console by traversing one node at a time I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to find length of a singly link list in Java so friends let's suppose we are given a singly link list having four notes with data is 10 1 8 11 now in this singly linklist head is pointing to the first node and as you can see the last node is pointing to null and we also know there are four notes into the singly link list so in order to find the length of the singly link list below is the algorithm for it so let's see the demonstration of this algorithm step by step so in the first step what we'll do we'll create an integer variable count which will hold the actual count of the number of nodes in the singly link list so friends initially the value of count will be zero so it would look something like this moving ahead so friend now we'll Define a list node by name current and which will point to the head so it would look something like this that as head is pointing to this first node now current will also point to the first node moving ahead so friend in order to find the length of this singly link list we need to Traverse each node one by one and we need to increment the count by one so friend in order to Traverse each node one by one we will provide a while loop and in while loop we'll provide a condition that current is not equal to null so when the current is equal to null we can come to know that list has reached its end and there are no more notes left to be traversed so here you can see current is pointing to this first node therefore it's not equal to null therefore the condition in while block comes out to be true so in the first step what we'll do we'll increment the value of count by one moving ahead so as current is pointing to First node so we already counted this node so now it's the time to move to its next node so here you can see current is pointing to this first node and current's next is pointing to the second node so in order to Traverse current to its next node what we'll do we'll simply assign the value of current do next to current so it would look something like this so friends here we simply assigned the value of current next to current so therefore now current is pointing to this second note having data as one moving ahead so now we'll again check whether current is equal to null or not so here you can see this current is pointing to the second node having data as one therefore it's not equal to null so the condition in while block comes out to be true in the first step we'll simply increment the count by one moving ahead and as we have traversed this node now it's time to move to its next node so here you can see current is pointing to the second node and it next is pointing to this third node so in order to make current Traverse to this third node what we'll do we'll simply assign the value of current do next to current so current do next is pointing to third Noe therefore we'll assign this value to current so it would look something like this we'll now again check whether current is equal to null or not so as current is pointing to this third node therefore it's not equal to null we'll again increment the count by one and then we'll simply move current to its next node by assigning current do next value to current so it would look something like this now again current is not equal to null therefore condition in while block comes out to be true we'll increment the count by one and then we'll simply Traverse current to its next node by assigning current. next value to current so here you can see current is pointing to his last node and and its next is pointing to null and as we are assigning current do next value to current therefore now current will point to null so it would look something like this we'll check whether current is equal to null or not so here you can see now current is equal to null therefore condition in while block comes out to be false and we also know that we have reached to the end of the singly link list so now there are no no more notes left to be traversed so in the final step we'll simply return the value of count which is nothing but four and we also know there are four notes 1 2 3 and four so friends let's go to eclipse and see the working of this algorithm so friends in our previous tutorial we created one class by name singly link list so this class demonstrated how we can Implement a singly link list in Java we also created One display method which actually printed the singly link list on the console and in the main method we also created few notes what we actually saw in the slide so if I run the code now so you can see the singly link list has four notes with the value as 10 1 8 11 and finally it points to null so there are four notes in A singly Link list so friend in order to find the length of the singly link list we'll first create a method and we'll give it a name as length so this length method will return return an integer value which will be nothing but the count of the number of notes in the singly link list so in the first step what we'll do we'll provide a if condition and here we'll check that if head is equal to null then we'll simply return zero because in a singly link list if head is pointing to null then we can come to know that there the singly link list is empty moving ahead we'll create an integer variable count and we assign a value of zero to it so this count variable will be actually holding the value value of number of notes in the singly link list moving ahead we'll create a list Noe by name current and we'll assign the value of head to it so the current is pointing to head node and then in order to Traverse each and every node of a singly link list will provide a while loop and inside this while loop will provide a condition that that if current is not equal to null so if current is not equal to null we know that there are notes in the singly link list and if current is equal to null then we can come to know that we have reached the end of the singly link list so in the first step we'll increment the value of count by one because as we are in the while loop we are actually traversing a particular node of a singly link list so we are incrementing the count by one and after incrementing the count by one we'll simply Traverse current to its next node by assigning the value of current. next to current and finally when current is equal to null we know that we already traversed the singly link list completely and there are no more notes left to be traversed so we'll simply return return the value of count so friends in the main method Let's test the working of this length method so here we'll simply print the value of length we'll call the length method and if I run the code so friends here you can see that we had a singly link list with the four notes 10 1 8 11 and finally we printed the length of the singly link list which is nothing but four so friends in this tutorial we saw how we can find the length of a singly link list in Java I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to insert node at the beginning of a singly link list in Java so friends here you can see below is the algorithm to insert a note at the beginning of a singly link list in Java friend let's suppose initially singly link list is empty therefore when singly link list is empty we know that head points to null because there are no notes into the singly link list so friend let's suppose we want to insert a node into a singly link list whose data is 11 so we pass in a value to this method let's say 11 now we want to insert this node at the beginning of a singly link list so here is the algorithm for it so let's see the demonstration of this algorithm step by step so when we call this method we pass in the value as 11 so friend as we want to insert this node at the beginning of a singly link list what we do is first we actually create this new node and in our previous tutorial we also saw that how we can create a new list node usually create a new list node by passing in the value into the Constructor so here a new list node will be created by name new node whose value will be 11 so it would look something like this so here you can see the new node is pointing to this list node whose data is 11 and whose next is pointing to null so friends now we want to insert this new node to the beginning of the singly Ling list where currently head is pointing to null so in the next step so friends as you want to insert this new note to the beginning of the singly link list we know that head always points to First Noe and if you want to insert the note to the beginning then we are inserting the node just before the head so in the first step what we do is currently new node next points to null we assign the value of head to new notes next so it would look something like this that as head is pointing to null new node next is also pointing to null and friends here you can see as head is the first Noe we are inserting it just before that so in order to insert this note just before the head we have to Point new node next to head moving ahead so the last step what we do is as we have inserted this node at the beginning of the singly link list we know that now head should point to this node because we know that head points to the first node of a singly link list so we simply assign the value of new node to head so currently head points to null and new node points to this list node so therefore now head will point to this list node so it would look something like this so friend after we have inserted this new list node to the beginning of the singly link list now our singly link has this one node now now let's suppose we want to insert one more node having value as8 so we call this algorithm again in the first step we simply create a new list note by passing in the value as eight so it would look something like this that new node is pointing to a list note having data as it and whose next is pointing to null so friends now we want to insert this new node at the beginning of this singly link list so by that we mean mean that we want to insert this node just before the head so in order to insert this new note just before the head there has to be some link between these two so in the next step what we do is as new node next is pointing to null we simply assign the value of head to new noes next so it would look something like this that new node next now points to head and which also makes sense because we are inserting this new note at the beginning of this singly link list which is nothing but just before the head moving ahead and the last step what we do is as we have inserted this new node in the beginning head should point to this node so we simply assign the value of new node to head so it would look something like this so friends after we insert this new note having the data is eight the link list has now two notes and here you can also see that whatever the node is inserted it is now at the beginning of the singly link list so friends let's suppose we insert one more node to this singly link list with the value as one so this algorithm again get executed in the first step we'll create a new list node so it would look something like this that new node is pointing to a list node having data as one and whose next is pointing to null moving ahead as you want to insert this new note at the beginning of the singly link list we have to make a connection from this node to the Head node because we want to insert it just before the head so what we do is whatever the value is there in the head we simply assign to new nodes next so here you can see has head is pointing to a node having data as eight and new noes next is pointing to null so now new node next will point to a node having data as eight moving ahead and as we have inserted this new do at the beginning of this singly link list we know that head should point to this node now so we simply assign the value of new node which is nothing but the node having data is one to head so it would look something like this so friends here we saw the demonstration of this algorithm by inserting three notes at the beginning of the singly link list first we inserted 11 which became the first note of the singly link list then we inserted 8 and then we inserted one so friends now let's go to eclipse and see the working of this code so friends in our previous tutorial we created one class by name singly link list and we implemented the singly linkage into this class we also implemented a display method which was actually printing each and every node of this singly link list so friends let's write a method which will insert a node into the beginning of this singly link list so first we'll create a method insert first so we have created own method by name insert first because we are inserting this node to the beginning of this singly link list and this method takes in an integer value which we actually want to provide to the list node which we want to add to the beginning of the singly link list so in the first step what we do is we create this list node and to the Constructor of list node we pass in the value so after this step a new node is created having data is whatever the value we have passed so in order to insert this new node to the beginning of the singly link list what we do is to new nodes next we provide a value which is stored in the head and in the last step what we do is we Simply Now Point head to this new node so friend this is the method which inserts the node to the beginning of the singly link list now let's test it's working so first we'll insert a node having value is 11 and we'll simply print the singly link list on the console so here you see singly link list has one note having data is 11 now let's say we insert 8 and we also insert a node having value as one and if I run this code now so friends here you can see the singly link list contains three notes now first we inserted 11 and then we inserted 8 to the beginning of the single link list so 8 came before 11 and finally we inserted a node having data is one which came just before the eight so friend this is how we insert the node to the beginning of a singly link list in Java I hope you like this video thanks have a nice day hello everyone welcome to my new data structures and algorithms in Java tutorial series video in this tutorial we will discuss how to insert a node at the end of a singly link list in Java so friends below you can see the algorithm to insert a node at the end of a singly link list in Java so here in this tutorial we will see the demonstration of this algorithm step by step here the algorithm basically insert the node to the end of the singly link list so let's suppose at the start the singly link list is empty so if the singly link list is empty we know that head will point to null because there are no nodes into the singly link list so now let's suppose we want to insert a node having data as 11 so to the method we'll pass the value as 11 and this code will be executed so in the first step what we do is in order to insert this value into the singly link list we first actually create a list node by passing in the value to its Constructor so so it would look something like this that a new list node is created whose data is 11 and whose next is pointing to null so now we will insert this new node into the singly link list at the end so first here in the algorithm we check that whether head is equal to null or not because if head is equal to null then we know that singly link list is empty and there are no notes so therefore currently singly in is empty because head is pointing to null so the condition in if blog comes out to be true and in the if blog we simply assign the value of new node to head so new node is pointing to a node having data as 11 and we want to insert this new node into the singly link list at the end but here as the singly link list is empty therefore in the first step what we do is we simply assign the value of new node to head so here as a head is pointing to null after this assignment head will point to this node having data is 11 so it would look something like this and we'll simply return from this method so friends here we inserted one node into the singly link list at the end so initially the singly link list was empty but now it has one note where head is pointing into this node moving ahead let's say we want to insert one more node having value is8 so we will pass this value into this method and the firstep will simply create a new list node by passing in the value to its Constructor so it would look something like this that new node is pointing to the node having data as 8 and whose next is pointing to n now we want to insert this new node to the end of the singly link list it's nothing but just after the node having data is 11 so friends now we want to insert this new node to the end of the singly link list and here you can see that singly link list is only one node therefore this node having the data is 11 is the last node of the singly link list so now after this node we have to insert this new node so we again check whether head is equal to null or Not So currently you can see the head is pointing to the node having data is 11 therefore the condition in if block comes out to be false so here we simply create a temporary node by name current and we'll assign the value of head to it so it would look something like this that current is now pointing to the node having data is 11 and head is also pointing to this node moving ahead so friends now we actually provide a while loop so while we are providing this V Loop is because in order to insert a new node to the end of the singly link list we need to Traverse from head to the end node so once we reach the end node we can simply assign the value of the last node next to point to this new node therefore we start from the head node as current is pointing to head and we iterate the while loop till current. next is null so friends when current do next will be equal to null therefore we can come to know that that is the last node of the singly link list so friend the while Lo we provide a condition that current do next is not equal to null so here if you see current is pointing to the node having data is 11 and its next is pointing to null and we also know that currently in the singly link list there is only one node having data is 11 and its next is pointing to null so therefore the current is pointing to the last node so therefore the condition in while loop comes out to be false because current. next is equal to null so as the singly link list has only one node therefore this node is the first and also the last node of the singly link list so as we are on the last note of the singly link list in order to insert this new note to the end of the singly link list what we do we simply assign the value of new node to currents next so here you can see new node is pointing to the node which we want to insert and currents next is pointing to null so if we assign the value of new node to currents next it would look something like this that current next is now pointing to a node which we want to insert into the singly link list at the end so friends when when this method gets executed we know that we have inserted this new note to the end of the singly link list now let's suppose we want to insert one more node having value as one so this code will be executed again in the first step we simply create a new list node by providing in the value as one so it would look something like this that new node is pointing to a list node having data as one and whose next is pointing to null we check whether head is equal to null or not so here you can see head is pointing to a node having data is 11 therefore it's not equal to null so friends in order to insert this new node to the end of the singly link list we have to start from the head and we have to reach till the last node of the singly link list so in order to perform this step we simply create a temp orary node by name current and we started from the head by assigning the value of head to current so it would look something like this that current is pointing to this first node having data is 11 now we will simply provide a while loop and Traverse this current to the last node of the singly link list by providing a condition that current do next is not equal to null so in the first step we see current is pointing to a node having data is 11 and its next is pointing to a node having data is 8 therefore current do next is not equal to null so the condition in V block comes out to be true so in the v block we simply Traverse current to his next position by assigning current. next value to current so here you can see current is pointing to this node having data is 11 and it next is pointing to a node having data is 8 so we'll assign the value of current. next to current so it would look something like this that current has simply traversed to its next node because we have assigned the value of current. next to current moving ahead we will again check whether current do next is equal to null or not so here you can see current. next is equal to null and here we also know that singly linklist has two nodes so the node having data 8 is the last node of the singly link list so we have traversed the current to the last node and now we can simply insert this new note to the end of the singly link list so here the condition in while block comes out to be false because current do next is now pointing to null and in the last step we simply assign the value of new node to currents next so new node is pointing to the node which we want to insert and current next is pointing to null so if if we assign this value to current next it would look something like this that current next is now pointing to the node having data as one so friends once this method gets executed we know that our singly link list has now three notes so here we started by inserting a note having data is 11 then we inserted a note having data as it and then we inserted a node having data as one so you also saw that we are actually inserting this note to the end of the singly link list so friends this was the demonstration of the algorithm now let's go to eclipse and see the working of this algorithm hello everyone in our previous tutorial we actually discussed how we can insert the node at the end of the singly link list in Java so in this tutorial we'll actually write the code and test the working of the code so friends in our previous tutorial we actually created Ed one class by name singly link list so friends in this class we actually wrote the code for the implementation of the singly link list so now let's write the code to insert the node at the end of the singly link list in Java so here I will be creating one method as public void insert last because you want to insert the node at the end of the singly link list so we'll provide a value to this method so here in the first step as we discussed in the slide that first we will create a new node and we'll pass the value into the Constructor of this list node so after this step a new node is created and now our task is to insert this new note to the end of the singly link list so here in the first step we actually make a check that whether head is equal to null or not so if head is equal to null we know that singly link is empty and there are no notes into the singly link list so we simply assign the value of new node to head and we simply return from the method so here if the singly link list is empty we simply assign the value of new node to head because after the insertion of this new node this would be the only node into the singly link list moving ahead and if the singly link is not empty then we'll create a temporary node by name current and we'll assign a value of head to it so here in order to insert this new list note to the end of the singly link list we need to start from the head and we need to reach to the end of the singly link list so in order to start from the head and reach to the end of the singly link list we create a temporary list node by name current and we start from the head and then we will provide a while loop and to this file will provide a condition as current. next is not equal to null and inside this Val Loop we'll simply iterate current to his next position so once we reach to the last node of the singly link list we know that it next points to null and as we want to insert this new list node to the end of the singly link list after while loop we simply assign value of new node to current next so friends here we started from the head node and we reached to the last node by providing this V Loop and we traversed current from first note to the last note of the singly link list and once we reach to the last note of the single link list we simply assign the value of new node to currents next and so the current next refers to this new node and this new node is part of the singly link list so in our main method Let's test it's working so we'll simply call insert last so here we have called insert last three times but first we are inserting the value 11 and then we are inserting a value eight and then we are inserting a value of one and then finally we are displaying the singly link list on the console so if I run this code now so friends here you can see first we inserted 11 and then we inserted 8 so 8 came just after 11 and then we inserted 1 so one came after it so it is nothing but inserting the node at the end of the singly link list so friend in this tutorial we actually saw how we can insert a note at the end of a singly link list in Java I hope you like this video thanks have a nice day hello everyone so in this video we will discuss that how we can insert a node in a singly link list at a given position so here we can see that in this problem we want to implement a method which will insert a node in a singly link list at a given position and this position we are assuming to be valid and it will start from one so for example here you can see that we are given let's say with the singly link list and now let's say if you want to insert any note at a given position so here we are assuming that position to be validated means that position should Lie from one to whatever is the length of the singly link list and here we are starting it from one which means if you want to insert a node at position one it would be the first node and if you want to insert at position five then this would be the last node and in case if you want to insert in between of these nodes the position would be the number where we want to insert so let's say if we want to insert at position three and we are given with this singly link list so here you can see this is position one 2 and three so what we are trying to do here is we will insert node here and this node will get shifted ahead of the node which we want to insert here so let's go ahead and see the demonstration of this algorithm step by step so before we start in case if you're new to my channel then please subscribe to my channel so that you never miss any update so now here you can see this is the algorithm to insert a node at a particular position now let's suppose if we are given with this singly link list having only two notes so we'll apply this algorithm on this singly link list and let's say if you want to insert a value8 at position one so the second parameter is position and this is the value which you want to insert so here you can see that whatever the value we have passed which is 8 here it's nothing but our data so in the first step what we are doing is we are creating a list node having data as 8 because you want to insert this node at position one so it would look something like this that node is pointing to a list node having value as8 and it next is pointing to null now here you can see that there are two cases in if and else so if position is one it means we want to insert this node at the beginning of singly Link list which is just before our head so currently this if block condition comes out to be true now as you want to insert this node before head what we have to do is as node is pointing to this list node its next should point to head because we want to insert this node before head so this node next should point to head so in the first step we are doing that we are assigning the value of head which is this node to nodes next So currently node next is pointing to null so after this assignment nodes next will point to head so it would look something like this that now node next is pointing to head moving ahead so here you can see that node next is pointing to head but as head is pointing to the node having value as 10 which is our second node we need to reassign this head to this node because because in order to insert a node before head which is the position one after insertion head should point to that node or else when this method will get exit this node won't be part of our singly link list so we need to assign head to this note so that this note comes into the singly link list so we are simply assigning the value of node to head so head is pointing to the second node now it will point to the node which you want to insert and here you saw that after inserting the node at the beginning this was our position one initially at position one was this node which shifted towards right and this note came into position one moving ahead now let's suppose if we are given with this three notes and we want to insert a value seven at position three so here you can see this is position one this is position two and this is position three so we want to insert node here and once we insert node here this one will be shifted a node ahead because we want to accommodate 7 between 10 and one because this is the third position so let's see how we can do that at the first step we'll create the node with the data as 7 we check whether position is equal to one or not so position is not equal to one so the else part will be executed so friends now idea behind this algorithm is we want to insert a node at position three so this is the position three which means we want to insert this node between this node and this node so that once this node is inserted our new node is at position three so in order to insert this node at position three what we have to do is we need to Traverse somehow to position two and then we can break this link and instead of pointing to node one we can point to our node 7 and node 7 will point to 1 and by this way our node will be inserted between 10 and 1 and will occupy position three so let's see how so here we'll create a list node previous because we want to reach somehow to this node which would be previous to our node after insertion so we'll start from the head so previous will point to head and in order to reach to this note we will keep the track using the count variable so value of count will be one at the start we sign ifies that we are already at this position and then in order to Traverse to a node previous to our position three we will provide a condition as count should be less than position minus 1 so position minus 1 will be two and here you can see that we have already taken up this place so count is one so currently count is less than position minus 1 which is 1 is less than 2 so this condition comes out to be true so we'll simply Traverse previous to its next node by assigning previous do next to previous So currently previous is pointing to this node it's next is pointing to this node so we'll assign previous next value to previous so it would look something like this that now previous will point to its next node moving ahead we'll increment Val value of count because we have traversed previous to its next node count becomes two now here you can see 2 is not less than 3 - 1 which is 2 and we also know that we have reached to position two and now we can simply use its next pointer to Simply insert this node into the singly link list at position three so this V Loop condition comes out to be false now here what we'll do is as we want to first break this link so at the first step what we do is we simply create a list node current we'll assign a value of previous do next to it so as we want to break this link so we can't directly break this link because if you break this link the notes after that will be removed from the singly link list because there would be no reference so at the first step we are simply creating a temporary list node by name current and we are assigning previous do next to it so that whatever the nodes are after that will be hold by current so previous next is this node so now current will point to this node so friends now we need to perform two steps in order to insert node between 10 and 1 the first thing we need to do is as node next is pointing to null and we know that after it insertion it should point to this node because that way it will be inserted in between of node 10 and 1 so the first step what we are doing is as current is pointing to this node we will assign the value of current to nodes next so here node next is pointing to null so after this assignment there will be a linkage from node next to current so it would look something like this moving ahead and at the last step what we do is we simply break this link and we can safely break this link because the rest of the list is being hold by current so how we can break this link is previous is pointing to this node it next is pointing to this node so if we assign nodes value which is this value to previous next so it would look something like this that now previous NEX is pointing to node by the this assignment and why we have performed this step is because we want to insert this node in between 10 and 1 so there was one linkage between 10 and one so we break that linkage we assigned previous next to node and node next to current so here you can see that if we stretch the singly link is side so it would look something like this that 7 will come in between 10 and 1 and here you can see that that is the position three where we actually wanted to insert our node this is portion one two and this would be our three so it is nothing but inserting a node somewhere in the middle of the singly link list so friend one last Cas remains is we want to insert node at the last so that will also be inserted via position so here you can see let's say we are given with the singly link list having only two notes 8 and 10 so this is position one and this is position two now if you want to insert a node at the third position so it would be nothing but inserting the node at the end of the singly link list and here we are assuming that position should be valid so if you call insert 7 comma 3 7 is our data and three is our position at the first step we'll create the list node having data 7 and it's next pointing to null we check whether we want to insert it position one or Not So currently we want to insert it position three so this condition comes out to be false now in the lse part we perform the same steps which we saw in our previous slide if we want to insert it position three we need to sum out travs to position two so that we can use this link to insert this node so we'll start previous from the head and in order to keep the track of the position and where to insert the node will'll create a integer variable count starting from value one because we have already taken up this value and the while loop we provide the condition is Count should be less than position minus one position minus 1 is 2 and as count value is 1 therefore the condition in while loop will come out to be true and the first First Step will simply Traverse previous to its next node by assigning previous next value to previous so it would look something like this we increment count so count becomes two and now here the condition in while loop comes out to be false because position minus 1 is 3 - 1 which is 2 and two is not less than two so this will signify that previous is one step behind our position so here you can see previous is pointing to position two and why we need a previous position is because as it is a singly link list we need to somehow use previous next pointer to Simply accommodate our newly created node inside that so at the first step what we are doing is we are simply assigning previous next value to a temporary list note current so previous next is pointing to null so current will point to null now as you want to insert this node what we saw in our previous steps node next should point to current so after this assignment it would look something like this that node next is pointing to null so friends here you can see as we are inserting this node at the end of the singly link list these steps are pretty much generic to accommodate both cases inserting in between and inserting at the end now at the last step we are simply assigning value of node to previous next so previous next is pointing to null so it means we want to reassign this value to this node because we want to insert this node at position three so it would look something like this so now head is pointing to node one node one is pointing to Second node and second node is pointing to third node which is our position three and this note is pointing to null because we have inserted this note at the end of the singly link list so it would look something like this so here we discuss the cases where we want to insert the note at a particular position of the singly link list I hope the information provided in this video is useful to you and in case if you find this useful then please like this video and in case if you're new to my channel then please subscribe to my channel so that you you never miss any update thanks have a nice day hello everyone so in our previous video we discussed that how we can insert a node at a given position in a singly link list so in this video we'll code the algorithm and we'll test its working so here in our singly linklist class which has a instance variable head of typ list node here I'll be creating one method public void insert now this insert method will take two things one is the position where we want to insert and let's say other is the value which we want to insert for that particular node now here we are assuming that this position is valid and it is not crossing the boundaries of our singly link list so those edge cases you can handle it by comparing the value of the position that whether it is less than zero or it is greater than the length of our singly link list and basically you can assign a default value to position and proceed add with the algorithm or you can simply throw an exception so here we are assuming that position is a valid position and starting from one so for example if you we are given with the single link let's say one having this three notes so one would be our position one four would be at position two and five would be at position three so let's say if you want to insert a value six at position two so after this method get executed it would become something like 1 at position two it will come six then four and then five so so it means we have inserted value six between 1 and 4 because one is at position one and after our insertion six should come at position two so this method will perform three cases if position is one it will insert at the beginning of the single link list and it will also insert in between or at the end of the single link list so let's see the code for that so assuming the position to be a valid position at the first step we will create the node which we want to insert whose value would be the value which we have passed to our method now after creating this node which we want to insert we will provide a f else part in the F part we'll check whether position is one or not so if position is one it means you want to insert the node at the beginning of the singly link list so in the F part what we do is as head is pointing to the first note which is also position one so now head should point to our newly created node after the node gets inserted so in the first step what we do is as node next is pointing to null we want to point it to head because we want to insert this node before head so node next should point to head and after node next is pointing to head in order to make node part of our singly link list and to inserted position one we need to assign the noes value to head so now head will point to node which would be at position one and which would become the part of our singly link list so this is the case one and for the rest of the cases we'll see in the else part so in the lse part let's say if we take this example and we want to insert a node at position two so here you can see that initially the link list let's say it's 1 4 and 5 and if you want to insert a node at position two so it will become something like this after the insertion so here what we are doing is this linkage we are breaking between 1 and 4 and we are assigning it from 1 to 6 and then 6 to 4 so there are two assignments one is we are reassigning this linkage from 1 to 4 to 1 to 6 and then from 6 to 4 so there are two assignments which we need to do now as it is a singly link list in order to reassign this value we need to somehow reach to node one which is previous to the position where we want to insert the node so let's say if we want to insert node at position two we need to somehow reach to position one and using its next we need to assign it to our node which we want to insert so in the else part we'll create a temporary node at previous because we want to somehow reach to a node previous to this position where we actually want to insert our newly created node so we'll start from head and as you have already started from head we'll create a integer variable count we'll assign it a value one because this count will help us in traversing to position minus one so in the while loop we will provide a condition as count should be less than position minus one and insert this look till this condition fails we will keep incrementing previous to its next position by assigning previous do next to previous and we'll simply increment count by 1 one position so when previous will reach to position minus one this Val Loop will terminate and after this V Loop gets terminate what we do is we create a temporary list node by name current and we assign a value as previous dot next to it so here let's say if we have reached here so to current we are assigning previous next which is value four because we need to reassign it to six if we break this linkage and reassign it directly then four and five will be removed from the singly link list because there is no reference to them so at the first step we are simply creating this temp temporary reference so that the rest of the singly link list is intact now after assigning previous do next value to current we can simply remove this linkage and assign it to our node which we want to insert so here what we do is we do previous do next and we'll assign a value of node to it so now this linkage is gone and it will point to six now we need to do one more assignment as this node next should point to four because we want to insert node 6 in between 1 and 4 so that it comes to position two so for that what we do is we do node do next and assign a value current to it because we know that current is pointing to previous next which was this node so now six next will point to this node and this way with this three step you can see that we have inserted our node in between node one and four and after this assignment you can see that six is now inserted position which we wanted which is position two in this case so friend this is the code to insert a node in a singly link list at a given position so now let's test it working in the main method so here in the main method I will comment this part and let's say after creation of singly Link list head is pointing to null because here you can see that at the start head is pointing to null so here what we do is let's say we insert a noed position one value is three and then let let's say I print it on the console the singly link list using the display method so if I run the code now so here you can see it inserted at position one which is the first position having only one note three pointing to null now let's say what we do is at position two we assign five and if you run the code so here you can see at position one was three so position two we got value five and now what we do is let's set position one we insert value two so now here you can see at position one three is already there and if we are doing this it means two will come before three so if I run the code now so here you can see two came before three which was our this case so now let's see the else part let's say insert a value four between 1 and two so we'll do two and if I run the code now so here you can see initially singly link list was 2 3 and five and when we did that four came in between 2 and three which is the position two which we actually wanted now here after this insertion you can see there are four notes 2 4 3 5 and let's say if you want to insert at the end so the portion would be value five because four nodes are already there so here what we do is at position 5 we want to insert value 7 let's say if I run the code so you can see seven inserted at the end of the singly link list which is position five so friends here we saw different use cases at the first step the singly link list became something like this and when we inserted five at position two it became something like this and then we inserted value two at position one so three got shifted ahead and our singly link list became something like this I'll just copy this part so it would be two it became something like this because two inserted at position one and rest of the singly link is shifted by one position and then we inserted four at position two so it became something like this it was like this so at position two 4 came and rest of the list notes were shifted by one position and here you can see that we had this four notes already so at the position five we inserted seven so it became something like this I'll copy this 7 null so which is our this case so friend this is how we actually insert a node in a singly link list at a given position I hope you have find this information useful and in case if you find this information useful then please like this video and if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in this video we will discuss that how we can delete the first node of a singly link list so let's see the code and it's working step by step using an animation so here you can see that let's say we are given a singly link list having three notes with data is 10 1 and 11 where head is pointing to the first nodee and let's say in our singly link list class we have created this head as an instance variable and we have written one of the method in that class which will manipulate this singly link list so here you can see that this is the code to delete the first element of the singly link list so let's see the demonstration of this method that how it manipulates the singly link list and deletes the first node so when we call delete first method you can see it has a return type of list node so what it will do it will delete the first node and it will return from this method so when we call delete first the first step we check is whether head is equal to null or not because if head is equal to null it means head is pointing to null and there are no nodes to delete so we simply return null So currently you can see that head is pointing to a node having value as 10 so therefore this condition comes out to be false and the execution Point reaches here now here what we do is we create a temporary variable which will also point to the first node of the singly link list because head is always pointing to the first node now why we are creating this temporary variable is because when we delete this node we need to return it from this method so we are creating this temporary variable of type list node and whatever the reference value head is holding we are simply assigning it to the temporary variable so as head is pointing to this first node after this assignment there will be a temporary list node which will also point to this node moving ahead now as the temporary list node is pointing to the first node of the singly link list after his deletion the link list will have only two notes and head should point to the second note now because when we delete the first note the link list remains with the two notes and the second note becomes our new head so we need to Traverse this head to the second node so how we will do that we'll simply assign the value head. next to head so head is pointing to this node it next is pointing to the second node so once we assign head do next to head it would look something like this that now head is simply Travers to the second node and as head is Travers to the second node we can safely delete this first node moving ahead so here you can see that head is pointing now to the second node and this will be our newly singly link list because you have deleted the first node but if we return this temporary list node directly from this method these two noes will also get written along with this temporary list node because there is still a linkage here so what we do is in order to break this linkage we simply assign null value to Temp next so temp is pointing to this node node and it next is pointing to the second node so we need to break this linkage so after assigning null it would look something like this you can see we have completely separated the first note from the singly link list so at the last step we simply return this temporary list node and after deletion of the first note now our link list is only two notes with a new head pointing to the second node which has now become the first node of the singly link list so friends let's say if you want to perform delete first again so we call delete first again on this singly link list having two notes so it would look something like this we check whether head is equal to null or not so head is pointing to this note therefore condition in if blog comes out to be false we again create a temporary list node which will point to the first node of the singly link list because we are assigning the value of head to it after assigning this value we simply Traverse head from this note to its next because we want to delete this node so by assigning head do next to head head will not point to the second node of the singly link list then we'll simply break this linkage here by assigning null value to temps next and finally we'll return the temp so now our singly link list has only one element so by calling this delete first two times we have deleted two notes which were at the beginning of the singly link list so let's say we want to delete this not node also so we'll call delete first again we check whether head is equal to null or not so here head is pointing to this node therefore it's not equal to null so this condition comes out to be false we created a temporary list node pointing to head something like this and then we'll simply Traverse head to it next because we want to delete this node so by assigning the value head dot next to head what will happen head is pointing to this node and its next is pointing to null because this is the only node left in our singly link list so now head will points to next which is null we simply assign null to temp. next to break this linkage but as it is already pointing to null it would look something like this and we can return this temporary node because we have deleted it completely so now a singly link list has no elements and head is pointing to null so if we call delete first again we first check whether head is equal to null or not so here you can see now head is equal to null so therefore this condition comes out to be true and as there are no notes left to be deleted we simply return null so friends this was the algorithm to delete the first node of a singly link list we saw that singly link list had three elements at the start we call this method delete first four times to delete this all the notes from the singly link list so now let's go to eclipse and see the demonstration of this algorithm step by step I hope you like this video thanks have a nice day hello everyone so in this video we'll write the code to delete the first node of a singly link list so here you can see that we have the singly link list class having an instance variable head of type list node so this head is responsible for holding complete list in our previous lecture we also saw the different operations such as length where we can get to know the length of the singly link list and even we can display the data which is being present in the singly link list we also discussed about the insert first method and insert last method so let's say if I run this code now so here you can see that we have inserted four notes 11 8 1 10 and then it's null so here we have inserted this four notes and we have displayed the singly link list here so let's write the code and see that how we we can delete the first note of a singly link list so here I'll be creating one method as public list node delete first so here you can see that after deleting the first node we'll simply return it from this method so as we discussed in our previous video that in delete first the first condition we check is we see whether head is equal to null or not so if head is equal to null then we simply return null which means that singly link list is empty and there are no notes left to be deleted we can even throw an exception from here but for time being I'm returning null and then we also discuss that after if condition we create a temporary variable variable and we point it to the head so here you can see that why we have assigned the value of head to 10 because after deleting the first note we have to return this list note from this method and also head points to the first note of a single link list so for example let's say we want to delete the first note from the singly link list so head points to 11 and once we delete 11 head should point to eight now because there are three more elements left so head should point to it so here after assigning head to this temporary variable now we can simply move head to its next position by simply assigning head dot next to head so here as head was pointing to 11 now it will point to 8 so now after placing head to its correct position we can simply delete the first node by assigning null value to temp. Next in order to break the linkage between this temporary node and the rest of the list and finally we can return the deleted node so this is the code now let's test it's working so here after display what we'll do is we will simply print the deleted nodes data so here what we'll do SSL dot we will call delete first method so this will return return as the list node which we have deleted and then we can simply print its data and then after deleting the data what we can do is we can again print the singly link list and if I run the code now so here you can see that we removed the first node which is 11 and we printed its data here and then after deleting the first note the singly link list was left with 8 1 and 10 so similarly let's say if I remove one more node and if I run the code now now so here you can see that when we call delete first for the first time 11 was removed then we called it second time so 8 was removed which got printed here and finally when we did display so the link list was printed as 1 and 10 because we have removed 11 and then eight so friend this is how we actually delete the first node of a singly link list I hope you like this video video thanks have a nice day hello everyone so in this video we will discuss about how to delete last node of a singly link list so here you can see that this is the algorithm to delete the last node of a singly link list so let's say we are given a singly link list having these three notes and we want to delete the last note of the singly link list so here the singly link list can contain n number of notes and here if we take this example where head is pointing to a node having value as 10 10 is pointing to one one is pointing to 11 and finally 11 is pointing to null so there are three notes and if you apply this algorithm when we call delete last first 11 will be deleted and we will be left with two notes and if we again call delete last then one will be deleted and we will be left with one node if we again call delete last then the only node left will be removed and simply returned from this method so in our previous video we saw that how we can delete the first note of a singly link list so there as head pointed to the first note it was very easy to delete the first Noe of the singly link list but here as we want to delete the last node we need to someh Travers to the second last node and remove this link to delete the last node from the singly link list so in order to achieve that what we do is we create two pointers one by name current which Travers to the last node and one pointer by name previous which travels to the second last node so as current travels to the last node previous travels to the second last node and why we need the second last node because in order to free the last node we need to break this linkage here so we need to travel somehow to the second last node break this link to make this note free so this is the algorithm for that now let's see the demonstration of this algorithm step by step so when we call delete last for the first time we first check whether head is equal to null or not so head is pointing to this node so this condition is false and we also check whether head. next is equal to null or not now why we perform this check is because let's say if the link list has only one single node so this node next will point to null and this will be the only node in the singly linklist so we don't have to delete anything we simply have to return the head because this is the only Noe which we want to return from this method So currently head. next is also not equal to null therefore this both the condition comes out to be false and now as we discussed we create two pointers current and previous so we start current from the head by assigning the value head to it so it would look something like this and as head is pointing to the first node its previous node will simply point to null moving ahead now friend as we want to delete the last node we need to provide a while loop so that we can Traverse current to the last node of the singly link list and previous to the second last node so here if you see in the while loop we are providing condition that iterate till current do next is not equal to null so here when current will reach to the last node its next will point to null so this value will terminate when current do next becomes null so as current is pointing to this first node and it next is not equal to null therefore this condition comes out to be true and while loop executes so before moving current to its next node what we do is we simply assign current's value to previous so that previous is is one node behind the current when current travels to the second node so in the first step we simply assign the value of current to previous so it would look something like this now as current is pointing to the first node previous will also point to this first node and in the second step we simply move current by one position by assigning current's next value to current so current next is pointing to the second node so now current will point to the second node so here you can see we have traversed current to the second node and previous is just one node behind it so this is all we do in the while loop till current reaches to the last node and previous reaches to the second last node so let's see how we again check check current do next is equal to null or not so current next is not equal to null this condition comes out to be true and before moving current to its next position we make sure previous is at current's position by assigning current's value to previous so it would look something like this then we simply move current to its next position by assigning current do next to current so current do next is pointing to this third node so after this assignment current will point to this node moving ahead now friends here you can see that we have this three noes but in singly link list there can be n number of nodes so the only idea to delete the last note of the singly link list is we need a reference to the second last node of the singly link list so that we can remove this linkage so now here you can see current has reached to the last node and previous is on the second last node so here the condition current next not equal to null comes out to be false because current next is pointing to null so this while loop terminates which makes sense because we have traversed till the last node using the current pointer and we also know it second last position using this previous pointer so after this while loop the next step we do is we assign a null value to previous next and why we do so because we want to break this link so that this last note can be freed up so previous is pointing to the second last Noe it's next is pointing to the last Noe and we want to delete the last Noe so we break this link by assigning null value to previous next so it would look something like this and finally we return the current so after the deletion of the third Noe we are left with two notes so let's say we again call this algorithm head is pointing to the first note so it's not null and head do next is pointing to the second node which is also not null so this condition comes out to be false we again create current and previous nodes by assigning head to current and null to previous so it would look something like this current points to the first node and previous points to null and then we provide a value because we want to Traverse current to the last node and previous to the second last node so first we check whether current or next is equal to null or not so currents next is this second node it's not equal to null so the condition in while loop comes out to be true and while loop starts execution before moving current to its next we assign current's value to previous so that it is just behind the current so it would look something like this that now previous is pointing to this node because current is pointing to this node and now we'll simply Traverse current to its next position by assigning current do next to current so current is pointing to this node it next is pointing to the second node so after this assignment it would look something like this and again in while we will check whether current next is equal to null or not so here you can see that this singly link list contains only two nodes and current is actually on the last node and previous is on the second last node and as current next is pointing to null current will be pointing to the last element of the singly link list so this condition comes out to be false and while loop exits and now we'll simply assign null value to previous next because we want to break this link so that this note can be freed up so it would look something like this that null is assigned to previous next finally we return current so now we are left with only one node so let's call this algorithm again so here you can see head is pointing to First node which is not null so this condition is false but head do next is pointing to null head do next is pointing to null which signifies that singly link list has only one element because head is pointing to the first note and it's next is pointing to null so therefore this list has only one node and if we want to delete that we don't have to do anything we simply return head so friend this was the algorithm where we discussed that how we can delete the last node of the singly link list we also discussed that how current and previous pointers help us in deleting the last node because in order to delete the last node we somehow need to travel to the second last node and once we travel to the second last node we simply assign null value to its next so that the last node can be freed up and can be returned from this method so friends now let go to eclipse and see the demonstration of this algorithm I hope you like this video thanks have a nice day hello everyone so in our previous video we saw the demonstration using an animation and we discussed that how we can delete the last node of a singly link list so in this video we will see that how we can code a method to delete the last nodee of a singly link list and in one of our previous video we also saw that how we can delete the first node so let's say I just comment out the delete first meth method and if I run the code now you can see we have inserted this four notes using insert L method and the singly link list contains 11 8 1 and 10 which are four notes and which got displayed using the display method now let's say we write the code to delete the last element of a singly link list so here when we call delete last for the first time 10 will be removed because it is the last element of the singly link list so here I'll create a method as public list node delete last and after deleting the last node we'll simply return it from this method so in our previous video we discussed that the first thing we do is we simply check that whether head is equal to null or not and we also check that head do next is equal to null or not now why we do it because this condition head equals equals null will signify that singly link list is already empty and there are no nodes to be deleted and head. next why we do it because if head. next is null it means the singly link list is only one element so what we do is we simply return head so if the first condition is true null is returned and if the second condition is true the head is return because this is the only node in the singly link list so this is the if condition and after that what we do is in order to delete the last node we need to somehow Traverse to the secondine CL node and remove the linkage so how we can achieve that in our previous video we discussed that we can create two pointers one is the current which will start from head and another is previous which will be always be previous to current and why would we do so because once current reaches to the last node previous is already at the second last node and we can simply remove the linkage by using this previous node and finally return the last node which got deleted so here at the start current points to head and previous points to null and then we need to provide a while loop so that we can reach to the last node of the singly link list so the condition we provide here is we simply check whether current next is equal to null or not so if current next is equal to null it signifies that we have reached to the last note of the singly link list because last notes next points to null so inside this value what we do is we move current by one position and before moving current to one one position ahead we simply assign current's value to previous so that previous always remains one node behind the current so that when current reaches the last Noe previous is at the second last note and once we get the location of the second last node we can simply remove the last node from the singly link list by simply putting previous do next equals null so this breaks the chain of the singly link list from the last node so here what we do is we do previous and assign the value current to it and after this assignment we simply move current to its next position by assigning current do next to current and this file Loop goes till current reaches the last position and previous reaches the second last position so after this while loop terminates one last step we do is we do previous do next equals null because this will break the chain between the singly link list and the last node because previous is pointing to the second last node and its next is pointing to the last node and we want to delete the last node so we simply assign null value to previous next so this will break break the chain and finally we simply return the current because we have deleted this node so we simply return return it from this method so now let's test it's working so here we have this list of four notes 11 8 1 10 so let's remove the last node of the singly link list which is 10 so I'll just uncomment this part and instead of delete first I'll do delete last because we are removing the last element and then I'll simply print the singly link list again if I run the code so here you can see that initially the list contain four notes then we call the delete last which removed the last node and returned from this method and then we simply printed its data which came out to be 10 so here you can see the 10 is the last note of the singly link list and after that I again printed the singly link list which came out to be 11 8 and 1 because 10 is already removed so similarly let's say if I remove one more data and if I run the code now so here you can see first 10 got removed by this method and then when we called again delete last one was removed so the singly link l now has only 11 and 8 10 and one are removed so for in this video we saw that how we can delete the last node of a single link list I hope you like this video thanks have a nice day hello everyone so in this video we will discuss that how we can delete a node from a singly link list at a given position in our previous videos we saw that how we can insert a node in a singly link list at a given position so now we'll see that how we can delete a node from a given position in a singly link list so here you can see let's say you want to Implement a method to delete a node at a given position so for example let's say if we are given with this singly link list and we need to write a method delete which will take in a position and we are assuming the position to be valid which means it should lie in the boundaries of the singly link list and which should start from one so let's say in this singly link list if you want to delete a node at position one then that would be this node which is the first node of a single link list so we are assuming that it should start from one and let's say if we want to delete a position three so this is position one position two position three so this is the node which we want to delete and we are assuming the position to be valid here so let's say our singly link list has four notes and if we pass position as six then either we need to throw an exception or we can assign a por to a value which points to the last node of the singly link list So based on these two assumptions let's see the algorithm so before we start in case if you're new to my channel then please subscribe to my channel so that you never miss any update so let's say if we are given with this singly link list having three notes so there arise three cases where we can delete a note from the singly link list one would be if we provide the portion as one then we are telling that we want to delete the first node of the singly link list and let's say if we provide position two then we are saying that we need to delete the second node which is between node one and node 3 and as we are assuming that we are starting from position one with first node here node having data is it will be por one this would be position two and we want to delete this node and after this deletion node having value is eight will not point to this node it will point to node one and the third case would be let's say if we want to delete the last node so we'll pass the position as three this is POR one portion two and por three so this node will be deleted and the second last node which is this node will point to null after this deletion so let's see these three cases so let's say if you want to delete the first note so we simply provide a position as one so in the code we simply check whether position is equal to one or not so if position is equal to one then if part will be executed and in order to delete this note which is being referred by head what we simply do is we simply assign value of head. next to head so head. next is the second node so we'll simply assign head. next value to head so now head will point to the second node so it looks like this so as we are deleting the first node head is pointing to that node so we can't directly delete this node because if we directly delete this note then rest of the notes will also get removed so first we do is we simply assign head. next value to head so that the rest of the singly link list is being referred by head because after deleting this node our singly link list will become 10 1 and null so once this assignment is done this node is being not referred by any other node so this will be garbage collected so it looks something like this that now our singly link list becomes head is pointing to node having value as 10 and node having value as 10 is pointing to a node having value as one moving ahead now let's say if we are given with this singly link list having four nodes and let's say if I want to delete any node in between of the singly link list so let's say if we call delete method with value as three which means we want to delete the node at position three which is this node now friend as it is a singly link list in order to delete this node we need to somehow Traverse to its previous node so how we can Traverse to this previous node is let's see the algorithm we check whether position is equal to one or not so position is equal to 3 so this condition comes out to be false in the else part as you want to delete the node at position three we need to somehow reach to position two so what we do is we simply create a temporary list node by name previous we'll assign a value head to it so it will simply start from the first node and our task is to make it reach two a node having value as position minus one so here as you already started with head we will create a count variable having value as one because this count variable will help us reaching previous to a node just previous to a portion from where we want to delete this node which is this position so we need to provide a while loop and in this while loop we provide a condition as count should be less than position minus one so position value is three and if we do minus one it becomes 2 so 1 is less than two so the condition in while loop comes out to be true and inside this Val Loop we simply Traverse previous to its next position by assigning previous do next to previous so previous next is pointing to this node so after this assignment previous will point to its next node via this reference so it would look something like this and as we have incremented previous two by one position will increment count by one so count becomes two now we'll again check whether value of count which is two is less than position minus 1 or not so 3 - 1 is 2 so 2 is not less than two so this condition comes out to be false and while loop will terminate and here you can see that as we want to delete the third por we have reached to portion two via this V Loop so after this while loop now our task is to delete the node at position three now as you want to delete this node and after its deletion this node next should point to this node because we don't want to remove this node along with this node we only want to remove this node so our task is to break this link and create a link from this node to a node after the node which you want to delete so at the first step what what we do is we can't directly remove this link here because if we remove this link then this complete singly link list will be garbage collected and in order to reach this node we also need a pointer to this node as well because if we have pointer to this node then we can use its next value to reach this node because we want to somehow assign previous next value which is this value to this node so at the first step what we are doing is we are creating a temporary list note having value as current and we are assigning previous next value which is this node so it would look something like this that current is pointing to previous next and after this it becomes very easy to delete this node as we discussed previous next should not point to this node it should point to this node the node next to our current so what we do is we simply assign value current. next to previous do nextt so here you can see current next is pointing to this node and previous next is pointing to current so we need to break this link and we want this link to point to currents next because if we break this link and we assign it to this node then this note can be freed up easily so when this assignment will be done current next value which is this node will now get referred by previous next so it would look something like this that this link will go away and previous next will now point to current next so it would look something like this that now previous next is pointing to currents next because we want to free this node from the singly link list and after this assignment when this method will get complete we know that current was part of this method as a local variable so now current will be simply garbage collected because there won't be any reference to this node after this method gets over so it would look something like this that it would be deleted and now if we rearrange it it would look something like this that now node 10 is pointing to node one so this was the case when we deleted a node which was between the singly link list so now let's say if we are given with this singly link list and we want to delete the last node which is at position three so we'll call delete method we'll pass the position as three and the algorithm Remains the Same at the first step we check whether por is equal to 1 or not so por is equal to three so this condition comes out to be false now as we want to delete the node at position three we sount it to Traverse to position two so for that we create a temporary list note previous which starts from head we create an integer variable count which starts from one so now in order to reach to a node which is previous to node which you want to delete we simply provide a while loop so now here you can see this count variable will help this previous to reach to a position which is just before the node which you want to delete so we provide condition as count should be less than position minus one because we have initialized already count by one and previous is already pointing to head so here you can see that value of count is 1 if we do position minus 1 we get 3 - 1 which is 2 so 1 is less than two so this condition comes out to be true and inside this Val Loop we simply Traverse previous next node by assigning previous do next value to previous so previous is pointing to this node and its next is pointing to this node so after this assignment previous will point to Second node via this link we'll increment count by one count becomes two and now here you can see this condition comes out to be false because 2 is not less than two so this value will terminate and we know that we have reached to a node which is just previous two node which we want to delete which is at position three so at the first step what we are doing is we are simply creating a list node current which will hold the value of previous do next so previous do next is this node which we want to delete so current will point to this node and now using previous and current we'll simply break this link and we'll assign this link to currents next because we want to free this node so we can only free this node if we break this link so here what we do is we simply assign value of current next which is null to previous next so this link will go away and previous next will point to currents next so after this method gets over here you can see current was a local variable so this node won't be referred by any other node so this will be simply garbage collected and our singly link list will become a list having two notes 8 and 10 and the last node will be removed so friends in this video we saw that how we can delete a node from a given position in a single link list I hope you have find this information useful and in case if you find this information useful then please like this video and if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in our previous video we discussed about that how we can delete a note from a singly link list at a given position so so in our last video we saw the animation of the algorithm step by step now in this video we'll actually code the algorithm and we'll test its working so in our singly link list class which has a head of type list note as a instance variable here we have coded many methods which are part of singly Link list now here I will be coding the method as delete which will take in a position I and based on that position that particular note will be deleted from the singly link list so let's say I give the method name is public void delete which takes in a position so friends here you can even return the list node which you just deleted via this method but I am keeping it as void and here we are assuming that position it's valid and starting from one so let's say for example our link list has few notes such as three 4 7 8 and let say N9 now here you can see the link list has five Notes 3 4 7 8 and 9 so three is at position 1 four at position 2 7 at position 3 8 at position 4 and 9 at position 5 so let's say if you want to delete the node from position one so this node will be removed and then link list will have this these noes if you want to delete a node which is in between then let's say if you want to delete node mode as three so 7 will be deleted and the remaining list will be 3 4 8 and 9 here four will simply point to8 and seven will be removed from the singly link list and let's say if we want to delete the last node so here you can see as there are five notes and if we pass the position as five then nine will be deleted so let's see the algorithm So based on our assumptions that position is valid and starting from one we provide the F condition the first step we check whether if position is equal to 1 which means if position is equal to 1 it means that we are simply removing the first note of the singly link list so here as head is pointing to the first node after its removal head should point to the second node so we'll simply assign head. next value to head so for example here if you see head is pointing to node 3 and if you want to delete the node from position 1 then after node 3 gets deleted our singly link list will become 4789 because head will now point to four so we can simply do head equals to head. next which will assign the next value which is this value to head so this is the first case so in the lse part we will see that how we can remove a node from a singly link list which is in between of these notes or at the end of the singly link list so both these cases will be covered in else part so here let's suppose if you want to delete the fourth node which is at position four now the idea behind this algorithm is which we also discussed in our previous video when we did for the insert here what we do is in order to remove it from the singly link list we need to break this linkage from 7 to 8 and instead of 7 pointing to 8 7 should now point to 9 and once seven will point to 98 will be removed from the singly link list so in order to break this linkage we need to First reverse to this node which is just behind this node because we need need to use this reference remove this reference link and make sure that seven now points to 9 so in order to reach the previous note from it what we do is we simply create a temporary list note previous and we start it from the head and then we'll provide a while loop so that we can reach to this node so how we can reach to this node is we will create a counter variable and as previous is already pointing to head we'll assign it with one and now using count and position we will reach to this node so in the while loop we provide condition as count should be less than position minus 1 so when count is less less than position minus one this file Loop will keep on iterating and with each iteration will simply Traverse previous to its next position by assigning previous do next to previous and we'll simply increment count by one so friends when previous will reach to node 7 the value of count will become three and here you can see we pass the value of position as 4 because we want to delete8 so 4 - 1 is 3 so 3 is not less than 3 so after this value will terminate in order to assign sens next to 9 because we want to break this linkage here what we do is we first reach to eight and how we can reach to eight is here you can see previous is already pointing to seven because we have reached 27 in this V Loop so here we'll create a temporary note current and we provide the Valu as previous do next so this is the previous and if we do do next we will reach here so current will point to node having value as 8 and now as we want to point 7 next to 9 what we simply do here is to previous do next which is currently pointing to8 we will assign the value as current do next because current next is pointing to 9 so now Seven's next will point to 9 instead of 8 via this line so after this line this link will be gone and there will be link from 7 to 9 so 8 once this method gets terminated 8 will be garbage collected so this is the the code to delete a note from a singly link list from a given position so in our main method now let's test it's working so here in our previous video we discussed about the insert method so let's say if I run the code you see the currently the link list has five Notes 2 4 3 57 so we'll use the same link list and we'll delete the first node the node in the middle and the last node so here if I do delete one which is at position one so this is the singly link list which we saw while running the program so two will be removed so let's run it so here you can see it printed 43 57 because two got removed and now let's say let's say Now link list say 4357 and we want to remove node 5 which is at position three because two is already removed and we are removing five which is at position three so we'll call delete with position three so now it should print 4 3 7 because five will be removed so here you see it printed 437 now we have 437 and let's say we want to remove the last node which is seven so four is at position one three is at position two and the last node seven is at position three so we'll again call delete with position three and if I run it should print four and three so here you can see it printed four and three so friend this is how we can delete a note from a singly link list from a given position and here we are assuming that portion should be valid that it should lie into the boundaries of our singly link list so friends I hope you have liked this information and in case if you like this information then please like this video and if you new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to search an element in a link list in Java so friends in our previous tutorial we discussed how to create a singly link list and also we disc discussed about the few of the concept associated with the link list so in this tutorial we will discuss how to search an element in a singly link list through a Java program so here you see that there is a simple link list having say four nodes with a data as 10 8 1 11 and we are having a head which is pointing to the first node so let's say suppose we want to search for a key having a data with a value one so looking at the link list we can see that the third node has a data with a value one so in order to search this key there is the algorithm for it which can search this key into this singly link list so let's demonstrate this algorithm quickly so so in order to search this key into the singly link list what we'll do we'll first create a a node which will name as current and this current will point to the head so which is the first node of our link list now moving ahead so idea behind this algorithm is we will Traverse the singly leg list completely till the end and we'll check for the data and we'll match it with the search key and if it if they are equal then we'll return true and if they are not then we'll return false in a while loop we'll place a condition that current is not equal to none till then Loop this So currently we see this current is pointing to the first node so it's not null so we'll it will go into the while loop and it will check that whether current do data is equal to the search key So currently the current do data points to 10 because the data inside this first node is 10 so we'll check that whether 1 is equal to 10 or not so it's not equal to 10 so this condition comes out to be false and we'll go to Next Step so we will just Traverse the current to its next so if if you if you see this current point to First and its next points to the second node so we'll Traverse the current to the second node moving ahead so again in while we will check whether current is equal to null or not so here current points to the second Noe so it's not null so it enters the while loop and then we'll check whether current do data is equal to the search key or not so here current do data points to8 and we'll check that whether 1 is equal to 8 or not 1 is not equal to 8 so this condition comes out to be false and we'll go to the next step so the next step is so what we'll do we'll just Traverse the current node to its next so if you see the current points to the second node and its next which is this points to the third node so we'll Traverse it to the third node and then again we'll execute the condition in while loop we'll see that current is not equal to null because it points to the hardd node and we'll go inside the loop and here we'll check whether current. data is equal to search key or not so current do data which is equal to one here we see that search key and current do data are equal so we have actually found our element so what we'll do so we'll just we'll just return true and we'll print a messages that search key found so similarly if we see the negative condition that whether suppose we want to make a search for the key having a value 12 so looking into the list we see that 12 is not inside this link list so we'll see the algorithm of it so first will create a current node which will point to the head so below we will check whether this current is equal to null or not and similarly we'll see whether this current do data is equal to search key or not so for the first ATT is not equal so we'll simply Traverse the current to the second node we'll again check whether current is equal to null or not so we see this current is not equal to null so this V Loop executes and current do data is also not equal to search key so we'll just Traverse the current to the third node and similarly we'll again check whether current is equal to null or not so as current points of hard note so it's not equal to null so the while loop executes and we'll check that the current. data is equal to to search key or not so 1 is not equal to 12 so again this condition fails and we'll just so we'll just Traverse the current to next note which is the fourth Noe and again we will check whether current is equal to null or not so it's not equal to null we'll check current do data is equal to search key or not so current do data is 11 and search key is so they are not equal so we'll Traverse the current to its next so now here you see that last node next point to the null so the current do next is null so we'll assign null to this current so it will be something like this so now current points to null and if we now execute the while loop so we'll see that whether current is equal to null or not so current is equal to null so this while loop condition breaks out and we'll simply return false that search key not found so friends this was all about our demo now we'll see how we can code this in Java so we'll go to our Eclipse initially in our previous tutorials we we created on singly link list which say if I run the program so this sing L list was something like this 108 1 and 11 and then null so in this tutorial we will first code the algorithm so we'll create a public method public and we'll give a return type as Boolean and we'll create a method say find and to this method we'll give list node the head and integer say search key so basically this method takes in a head and a search key so first thing will be if say let's say if head is equals to null so suppose we have a link list where head points to n so we will just return false and then we'll say code whatever we discussed into the SL right so we'll create a current node and make it point to head so now we'll give a while loop so inside this while Lo we'll say current not equals to null so we'll iterate till current equals null so inside this value we'll provide a condition what we discuss in the slide as when current. data equals search key then just return true and after if we'll just Traverse the current to its next node so current to current will provide currents do next value and if the current reaches the end and the search key is not found we'll just simply return return false so into our main method what we'll do we'll create a if condition and let's say here we'll say singly link list do find and to find we provide head and provide a value one so one is into the singly link list so we'll provide a value one and we'll say out as search key found or we'll say else search key not found so we saw that the link list which we created in our previous tutorial has the value as 10 at 1 and 11 so first we are considering the positive case we know that one is in the list so we'll just run the jaob program so you see it print the search key found because one is in the singly link list now let's say suppose you want find whether the link list contains the value 12 or not so we know that it doesn't contain the value 12 so if I run it so it print search key not found so friends in this tutorial we discuss how we can search an element in a link list through a Java program hope you like this video please like comment share and subscribe my YouTube channel you can also visit my blog the link is provided in the description thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to reverse a singly link list in Java so friends suppose we have a link list with notes say 10 8 1 11 and we provide this link list as a input so after its reversal the link list becomes something as 111 8 10 so basically it reverses the list so here 10 81 11 gets reversed and becomes 11 111 8 10 so let's see this algorithm through a demo so here we see a single link list having four nodes say 10 8 1 11 and we head points to the first node so in order to reverse this singly link list here is the algorithm so we'll see how this algorithm makes the singly link list reverse so the first step of execution would be we'll create a list node by the name say current and a value of head will be assigned to it so so currently head points to the first node so similarly the current will point to the first node which is 10 and moving ahead then we'll create one more node which will point to null so the name of this node would be previous moving ahead we'll create a node by the name next and we'll assign a null value to it so the basic idea of the algorithm is to Traverse each node one by one and and apply some logic to reverse the position of of the nodes so in order to Traverse each node one by one we'll apply a while loop and in while loop we place a condition that till current becomes null we'll iterate this V Loop so here we'll see this current points to First node and it's not null so this while loop executes and then what we'll do here we see this next point to null so we'll assign the currents next node to it so if you see current points of the first node and its next point to the second node so we'll assign current's next value to the next node so then it will become something like this moving ahead here you see the current next which is this pointer it points the second node and previous points to the null so idea is to break this pointer and provide it a null value so we what we have done is we will do current. next and we'll assign a null value to it so it will look something like this so moving ahead and to our previous node we'll assign a value which current holds so it will be the first node so it will become something like this moving ahead and then to Simply current will assign the value which is in the next so after the first iteration if I rearrange this notes it would look something like this so this is the condition with the first while loop now we'll again execute the while loop and we'll see that current is equal to null or not so current points to the second node which is not null so this V Loop executes then we'll we'll we'll perform the same steps so so here we'll provide the current next value to the next node so here current next is the third node we'll assign current next value to the next node and similarly to current next we'll provide the value which is present in the previous so so here if you see that current next pointer points to the third node so we'll remove this link and we'll assign it what the previous holds so here previous points to the first node so we do something like this so the currents next now points to the previous which is the first node so moving ahead to this previous now we'll assign the value current so moving ahead now we'll simply assign whatever the value present in the next to the current so the current traverses to the third node we'll again iterate the value and will check whether current is equal to null or not so here current points to the third node which is not equal to null so this Loop executes and similarly now we'll assign current next value to the next so it will look something like this moving ahead and to current next we'll assign to the previous so it BEC something like this moving ahead we make previous point to current and finally we'll make current to point to the value which next points so it will Trav to the fourth node and again we'll check whether current is equal to null or not so it's not equal to null so now next point to current's next so so here current's next point to null therefore the next will be pointed to null moving ahead and to currents next we'll assign the previous node value so it will look something like this and we Traverse previous to point to current so it will look something like this so finally we'll assign current the value of next which is null so now we'll again execute while loop and we'll see whether current equals null or not so here current equals null so therefore this condition comes out to be false and the while loop breaks out so the last step would be to return the previous so this previous becomes our new head so if you see the initially head pointed to 10 and then 8 1 11 and now as previous becomes our new head so now the link list is reversed so the first node is 11 second is 1 third is 8 and fourth is 10 and and then it points to null so here previous becomes our new head and we ex exit our algorithm so friends let's go to eclipse and see demonstration of this algorithm so friends in our previous tutorial we created one singly link list so here if I just remove this part and if I run this Java program so you see we initially we have created a singly link list having the notes as 10 8 1 11 and they are interconnected so let's reverse the singly link list so in order to reverse the singly link what we'll do we'll create a method whose return type is the list node and we'll give a method name is reverse so this reverse method will take the head of the singly link list so we'll say list node head now the first step would be we'll simply check whether head points to null so if it points to null we'll return the head so if head equals null so we'll simply return head and moving head will code our algorithm so we'll create a list node say current and assign a value of head to it then we'll create a list node previous and assign null value to it we'll create a list node next and assign a null value to it and now we'll create a while loop so the condition and while loop would be current not equals n so here while loop execute till current becomes null so here to our next we'll assign the value as current do next and to current do next we'll assign value as previous to previous we'll assign the value which current holds and find finally to our current we'll assign the value which next variable holds and the last step would be to Simply return previous because previous becomes our new head so we'll return the previous so this is the algorithm so let's see it demonstration so here I will call the reverse and provided a head and list node so whatever the return from this reverse method will be our head of the reverse list so we'll simply display it now so run this program now so here you see initially the list was 10 8 1 11 and last node was pointing to null and now it becomes 11 1 8 10 where 10 points to null so so this is how we can reverse a singly link list in Java so friends hope you like this video please like comment share and subscribe my YouTube channel you can also visit my blog the link is provided in the description thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to find nth note from the end of the link list in Java so friends given a link list and a value of n we need to find the net note from the end of the list if suppose this is the link list having the notes as 10 8 1 11 and 15 so there are total five notes and the given the value of n is equal to 2 so it means we have to find the second note from the end of the list so if you see the second node from the end of the list is say 1 2 so 11 is the second node from the end of the list so if this is the input then you can see the output would be the second node from the end which is 11 now let's see the demo of the algorithm and it's working so friends here is the link list having the nodes is 10 8 1 11 and 15 and suppose we are given the value of n is 2 it means we have to find the second node from the end of the list here you can see that this is the algorithm for it so let's see the demo of the algorithm so first we'll create a main pointer which will be pointing to the head and if you see the head points to the first node therefore there would be a main pointer which will point to to the first node moving ahead now we will create a reference pointer which will also point to the head so this is the reference pointer which will point to the first node we will create an integer variable by name count and we'll assign the value zero to it so currently count is zero so friends the idea behind this algorithm is in order to find the n note from the end of the list what we'll do we have taken these two pointers both of which are pointing to head so if we take the reference pointer we'll make this reference pointer to move end positions so when this reference pointer has traversed the end positions then we'll move main pointer reference pointer together till reference poter encounters null so when the reference poter will encounter null the main pointer would be the net position from the end of the list so let's see how this algorithm works when the value of n is 2 So currently this while loop will work till the value of count is less than n So currently if you see the value of n is 2 and the count is zero therefore the count is less than n so it will execute the while loop and now we will just Traverse the reference pointer to its next position so here we will assign the reference Pointer's next value to reference pointer so reference pointer points to First note and its next point to the second node therefore we assign the reference pointer next value to the reference pointer so it will look something like this moving ahead we'll increment the value of count and now again this V Loop will execute because count is less than n and similarly we'll move the reference pointer to its next that is assigning the reference pointer next value to the reference pointer and then we'll increment the value of count so now count becomes two so now the value of count is not less than n if you see the value of n is 2 and count is two and 2 is not less than two therefore the condition in while loop is comes out to be false therefore the while loop breaks out and our execution reaches the second while loop so at this point the reference pointer has moved the two positions from the head and in this while Lo what we'll do we'll move both pointers the reference pointer and the main pointer together till reference pointer encounters the null value so the condition inside it would be this while loop will execute till reference point is not equal to null So currently the reference PO is not equal to null therefore the condition in while loop comes out to be true so first we'll simply Traverse the reference pointer to its next value moving ahead and now we'll move the main pointer to its next value so we'll assign the main Pointer's next value to the main pointer again the reference pointer is not equal to n so this while loop will execute will Traverse the reference pointer to its next value and similarly we'll move the main pointer to its next value that is by assigning the main Pointer's x value to the main pointer so again this file Loop condition will be evaluated and you can see the reference pointer is not equal to null therefore this while loop will execute now reference pointer will move to its next value and similarly the main pointer will move to its next value so now once again the bullan value in the while loop will be evaluated and currently if you see the reference pointer points to the null therefore the condition in while loop comes out to be false and this while loop breaks and finally if you see the main pointer is at the second position from the end of the list therefore we'll return the main pointer because this is the second note from the end of the list so friends this was the demonstration of the algorithm let's move to eclipse and see it's working so friends in my previous tutorial I have created this singly link list class having an instance variable which stores the head and having inner class which is the list node if you want to see it's working then you can watch my previous tutorials so so in this tutorial we'll write a method which will F the Ed note from the end of the list so first we'll create a method and and the return return type of it would be list node let's say we give the name of the method at get n Noe from and so this method will be taking a value of n now first we'll check if head is null then just return null then we'll check that if let's say value of n is less than equal to Z so value of n is less than equal to Z then we can throw an exception say Throw new we can throw illegal illegal argument exception and we'll pass the string as say invalid value and equals moving ahead so first we'll create a list node having name as main pointer and we'll assign the value of head to it similarly we'll create another node which is the reference pointer and we'll assign the value of head to it then we'll create a integer variable count having value is zero now we'll create the while loop which we saw in the slide so while and we'll give condition as count we less than n and we'll simply Traverse the reference pointer to its next value that is we'll assign the reference pointer next to reference pointer and we'll increment the count by one and here let's say suppose the link list has three notes and if we provide the value of n as say five therefore this reference pointer might reach to a null value so before this we can even if we can check that if if reference pointer is null then we can simply throw an exception we can throw an illegal argument exception we can give a string as n is greater than the number of nodes in list so here if suppose reference pointer comes out to be null then the value of n is surely greater than the total number of noes in the list moving ahead we'll create another while loop and in this while loop we'll provide the condition is Rev pointer should not be equals to null and we'll simply and here we'll simply assign the reference pointer next value to the reference pointer and we'll Traverse the main pointer to its next value and finally we'll just return the main pointer because this will be pointing to the net note from the end of the list so if you see that this is the code for getting the net note from the end of the list and if you go to the main method then I here then here there is a list having five notes with the value as 10 8 1 115 and if I run this it will print the list so here it's 10 8 1 11 15 so there are total five number of notes so let's say if I do n node so I just created a list note by the name n node from end and if I call this method get n it note from in and if I pass the value as say two and if I I print and here if I print it n node from and is dot data so now if I run the program you can see prints 11 because 11 is the second note from the end of the list and suppose if I provide the value as say negative value say minus one then it throws an exception saying that illegal argument exception say invalid value of n which is equals to minus1 and suppose the total number of nodes are five and if I give the value as six which and I wanted six note from the end of the list and if I run this so you can see it will throw illegal argument exception saying that six is greater than the number of notes in the list so friends this was the working of the algorithm which we saw in the slide hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to remove duplicates from sorted link list in Java so suppose we are given a sorted link list so if you see then the link list has five notes having the data is 1 1 2 3 3 so this is a sorted link list but you can see that there are duplicates into it so you can see one is duplicate and the three is duplicate so in this tutorial we will discuss how to remove this duplicates from the sorted link list and if you see the output then the output would be like 1 2 3 and all the duplicates will be removed so let's move ahead and see the demo of the algorithm so here if you see we are given with the link list which is sorted and having nodes as one 1 2 3 3 and this is the algorithm which will remove the duplicates from this sorted link list so let's see working of this algorithm so in order to remove the duplicates from this sorted link list first we'll do we'll create a list note which will point to the Head moving ahead so the basic idea behind this algorithm is we will Traverse the link list through this current pointer and we'll check whether this data of this current node is equal to data of its next node and if they are equal it means we have encounted a duplicate and we will write the logic to remove that duplicate node so here if you see we'll iterate this completely based on this condition so the condition would be the current should not be null and current do next should not be null so here if suppose the current node reaches this last node so current do next will be null it means there is no more notes to Traverse therefore this condition is required so let's see how this algorithm works so first this condition will be checked that whether current is equal to null or not so so current is not equal to null because it is pointing to the first node and current do next should not be null so current. next is also not null because it is pointing to the second node therefore this while loop condition comes out to be true and it will encounter if statement and here we will check whether current node data is equal to current's next data current data is one and current next data is also one therefore they are equal so this if statement condition comes out to be true and we have encountered a duplicate so here if log will be executed and in order to remove this duplicate what we'll do we'll assign current next next to the current next so here if you see current next point to the second note so we have to remove the second note therefore we have to break this point and we have to assign it to the second node so this is the statement for it we'll assign currents next next two currents next so it would be something like this so now current next point to current next next and as this node has no reference therefore this would be garbage collected so moving ahead so now again the condition in while loop will be evaluated so here current is not null and current's next is also not null therefore the condition in while loop comes out to be true and while loop will be executed so now we'll check whether current data is equal to current next data so current data is one and current next data is two so they are not equal therefore the if block condition comes out to be false and the L will be executed so it means that both the notes like current and current next are different nodes and they are not duplicate therefore we'll simply Traverse the current to its next Noe and now once again the while loop condition will be evaluated so current is not null and current's next is also not null therefore the Y Loop will be executed and now we'll check whether current's data is equal to current next data so current data is two and current next data is three so they are not equal so it means that data and two both the notes are different so else condition will be executed and we will assign current next to current so we will simply Traverse the current to its next node so now once again the while loop condition will be evaluated and here you can see current is not null and current next is also not null therefore the while loop condition comes out to be true and now it will be evaluated whether current data is equal Al to current next data so current data is three and current next data is also three so they are equal it means that we have Contra a duplicate here and we have to now remove this node having the value as three therefore in order to remove this node we have to first break this pointer and we have to assign this pointer to current next next so current points to three and it next points to three and its next points to null therefore we'll assign current next next to current next so it would be something like we'll remove this pointer and we'll assign current next to current next next which is null and as this node has no reference to it therefore this would be garbage collected and now once again the while loop condition will be evaluated so current is not null but current. next is null so if you see current next points to null therefore this while loop condition comes out to be false and it makes sense because we don't have any more node to Traverse therefore the while loop condition breaks out and if you see then we have removed the duplicates from the sorted link list so head points to one one points to two and two points to three and three points to null so the output would be something like this so friend this was the demo of the algorithm now let's go to eclipse and see the working of the code so friends in my previous tutorials I have created a class by name singly link list so in this class we have this instance variable which holds the head of the link list and it is private iner class list node which will be holding the notes in the singly link list and if you want to see the working of this code then you can watch my previous tutorials so here we have simply created a singly link list and we have inserted few notes having the data as 1 1 2 3 3 and if I run this class so it will print the link list as 1 1 2 3 3 so this is the singly link list which we saw in our slide and it has duplicate as one and three so let's write the code to remove this duplicates from sorted link list public we'll give return return type as void remove duplicates so this is the method where we'll write the code to remove the duplicates from sorted link list so first we'll provide if conditions say if head is null then simply return from this method and next we'll code the algorithm which we saw in the slide so we'll create a list node by name current and we'll assign the value head to it then we'll create a while loop and we'll provide the condition as current not equal to null and current. next not equal to null and inside this value we'll provide F blog as if current data is equal to current. next. data so this is the condition to check whether adjacent notes are duplicates or not so if they are duplicate then we'll simply remove the duplicate node by current. next and we'll assign the value to it as current do nextt do next and we'll provide a else blog as so suppose the EDG and notes are not same then we'll simply iterate current to its next position by assigning currents next value to current so friends this is the code to remove the duplicates from sorted singly link list now in the main method I will simply call the remove duplicates and let's again print the link list so if I run the code now so here you can see initially the link list was 1 1 2 3 3 and after removing the duplicat it became 1 2 3 so friend this was the code to remove the duplicates from sorted link list I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to insert a node in a sorted singly link list in Java so friends let's suppose we are given as sorted singly link list having four notes say 1 8 10 and 16 and suppose we want to add a node having data as 11 to it friends here we want to insert this not such a way that the Sorting order is maintained in the link list therefore in order to insert this new Noe into this sorted singly link list the here is the algorithm for it so currently you see the head points to First node having data as one then it goes to 8 10 16 and we want to insert the node having data is 11 and we want to insert in such a way that after insert the Sorting order is maintained in the list so let's see the working of this algorithm step by step so in order to insert a new node in a sorted singly link first we'll create a list node by name current which will point to the head so here if you see the head points to the first node therefore the current will also point to the first node then we'll create a temporary node which will point to null so this file Loop will execute till current is not equal to null and current data is less than new nodes data so we'll see this algorithm step by step and after we complete this value you will come to know that why these conditions are needed so here if you see current should not be null so current is pointing to First note and it is not null and current data so current data is one here and new node data is 11 so 1 is less than 11 therefore this while loop condition comes out to be true so in First Step what we'll do we'll assign the value of current to Temp so current points to the first node therefore when we assign the current value to the temp it it becomes something like this so now 10 points of the first node and then we'll Traverse the current to it next node by assigning current do next value to current so current point of first node and next point to the second note therefore we'll simply assign the current's next value to current so it would be something like this so now current points to the second node moving ahead now again current is not equal to null and current data which is 8 is also less than new noes data which is 11 therefore this while loop condition comes out to be true and we'll assign current's value to the temp so it would look something like this and then we'll simply Traverse current to its next position by assigning current. next value to current moving ahead so again current is not equal to null and current do data which is 10 is also less than new notes data which is 11 therefore this while loop condition comes out to be true and we'll simply assign Curr value to the temp so it would look something like this and then we'll simply Traverse current to its next position by assigning current. next value to current moving ahead so now current is not equal to null and if you see current data so current data is 16 and new no data is 11 therefore current data is not less than new noes data therefore this while loop condition comes out to be false and this while loop breaks so if you see we have Traverse current to the node which is just greater than the value of new node and we have also kept a temporary node which is just behind the current node so the idea behind keeping this temporary node is once this while loop breaks out then we need to insert new node just between 10 and 16 because 11 is the value between 10 and 16 so in order to put the node between 10 and 16 we need this temp node because this pointer will now be pointing to new node and new node next which is pointing currently to null will point to current so in order to insert this new node into sorted singly link list what we'll do first we'll first make new node next point to current so new node next currently points to null so instead of pointing to null now we want to insert it between 10 and 16 therefore this next should point to 16 and if you see current points to 16 so so we'll simply assign the value of current to new nodes next so this is the step for it so it would look something like this so new node next points to 16 which is also referenced by current moving ahead now in order to insert the node between 10 and 16 temp next points to 16 therefore we need to break this link and we need to assign this link to new node so what we'll do we'll assign new nodes value to temp. next so temp. next currently pointing to current we'll break this link and we'll assign it to New node so it would look something like this and finally when we align this link list it will look something like this so you see we have inserted 11 just between 10 and 16 and also after insert the link list has maintained it sorted order therefore we'll simply return the head so friend this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorials I've have created a singly link list class which is an instance variable of typ list node which is actually the head of our link list it also has a say inner class by name list note which helps us in storing the data in the link list so in order order to know more about its working please watch my previous tutorials so in this tutorial we will simply write a method which will insert a node in a sorted singly link list so I'll just create a method public and I will give a return type to it as list node so let's say I give method name as insert in sorted list this method will take an argument of integer by name value so this value will be stored as a part of node into the sorted singly link list so first we'll create a list node for this value so I'll give the name to it as new node and then we'll give a condition is if head is null then simply return this new node moving add we'll create a list node current which you saw in slide and we'll assign a value head to it then we'll create a list node by name temp we'll assign null to it so first we'll create a while loop so in this value we'll provide a condition as current not equal to null and current. data is less than new node. data so we'll iterate till current is not null and current data is less than new nodes data so in while loop First Step would be we'll assign the value of current to Temp and we'll simply Traverse current to its next value so basically these are the two statement which we be providing into the V Loop and after V Loop gets executed we know that that current now points to a node which is just greater than the new nodes data and 10 points to the node which is just lesser than the new nodes data therefore First Step would be to new node next we'll assign the value of current and then do temp next we assign the value of new node and finally we'll just return head so friend this is the method by which we can insert a node into sorted singly link list so here if you see in the main method currently there are four nodes by data is 1 8 10 16 so they are the same what we saw in the slide so if I print this singly link list you can see it print as 1 8 10 16 and null so therefore currently this is in sorted order and let's suppose I call the method insert in sorted list and give the value as 11 so friends once this method is executed it will insert 11 into sorted singly link list so I will just print it again and if I run the program So currently it was a sorted link list and after insertion of 11 the Sorting order is still maintained so this is the algorithm by which we can insert a node into sorted singly link list so friends I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to remove a given key from singly link list in Java so here if you are given a singly link list having five notes say 1 8 10 11 and 16 where head points to the first node and if suppose we want to delete a key having the data is 11 So currently if you see the fourth node has data is 11 therefore we need to write an algorithm which could delete this fourth node from the singly link list if you see below is the algorithm for it so let's go over to the algorithm step by step so first we'll create a list node by the name current and it will point to head so here current points to the Head then we'll create a list node by name Temp and it will point to null so this temporary node points to null then we'll Traverse the link list in a while loop and we'll iterate the link list in such a way that current should not be null and current data is not equal to key so here current points to First node and it's not null and current data which is one is not equal to the key 11 therefore the condition in while loop comes out to be true so in First Step what we'll do we'll simply assign the value of current to Temp so current points to First note that therefore now temp will point to the first node and in Next Step we'll simply Traverse current to its next position by assigning current next value to current so current points to First node and its next points to second note therefore we'll assign current next value to current moving ahead here current is not equal to null and current data so current data is 8 and it's not equal to 11 therefore the condition in while loop comes out to be true so here we'll simply assign the value of current to Temp and current points to Second node therefore the temp will point to the second node now and we'll simply Traverse current to its next position by assigning current. next value to current moving ahead now again current is not equal to null and current data which is 10 is not equal to 11 therefore the condition in while loop comes out to be true we'll simply assign current's value to Temp and here if you see current points to third node therefore temp will now point to the third node and now we'll simply Traverse current to its next position by assigning current. next value to current moving ahead so if you see current is not equal to null but current data so current data is 11 which is equal to key therefore condition in while loop comes out to be false because current do data is equal to key therefore the while loop breaks out and and we have traversed the current to the node which we want to delete so here we will check whether if current is equal to null and if current is equal to null it means that we have Traverse complete link list and we haven't found the key therefore we'll simply return from the method and if you see current is not null therefore the if condition comes out to be false so finally in order to remove this node which is pointed by current and having value as 11 we need to break this link so the temporary node which we have created earlier was used to hold the previous node position so that once we found the node having the Valu as key we can simply delete it through the temporary node So currently if you see temp. next point to this current node so we need to Simply remove this link but if we remove this link then the node after current will also be removed therefore we need to assign temp's next value to current's next value so if you see temp next points to current and current next point to the node having value 16 therefore we'll simply assign current next value to Temp next so it would look something like this first this link will be removed and when we assign current next to Temp next it would look something like this so now you can see temp next points to the current next node and once this method get executed then as current is a list node on the stack it would be garbage collected and finally when we rearrange the link list it would look something like this so friends this for the demo of the algorithm so let's go to eclipse and see the working code we'll also see few of the ede cases there so friends in my previous link list tutorials I have created a class by name singly link list and this class has an instance variable list node by name head which holds the data into our singly link list and it has also a private inner class by name list note so this class is responsible for holding the data into the singly link list and if you want to see the working of this code you can watch my previous tutorials so in this tutorial we will simply code the algorithm which we saw in the slide so let's create a method public void delete node so I just created a method by name delete node and it will take a integer value say key key so based on this key we'll remove that node which holds the value of key so in first line we'll just create a list node by name current and we'll assign the value head to it then we'll create a list node by name Temp and assign a null value to it we need to quote an hge case which we not saw in the slide so that H case for if suppose head data matched with the key then we need to handle it separately so we can write if so in if condition we can say if let's say current is not equal to null and current do data equals key so it means that we are handling the case where head data is matching with the key so in that case we need to Simply shift the head by one node so to head we'll assign the value as current. next and we'll simply return from the method so moving ahead we'll now create a while loop which we saw in the slide and the condition would be current should not be equal to null and current. data should not be equal to key so in First Step we'll simply assign temp the value of current because this temporary node will hold the position of the previous node to current and now we'll simply Traverse current to its next node and after the while loop will give a check whether if current is equal to null that means we haven't found the key in the singly link list so we'll simply return and suppose if current is not equal to null then then current points to the node having the data equal to key therefore we need to remove that node so the temp node is just the node previous two current so we'll assign current. next value to Temp next so what this will do temp. next currently points to current but as we need to delete this current note we'll simply assign current next value to Temp next now in our main method let's see it's working so I've created a link list which we saw in the slide and if I run the program now you can see that link list has five notes as 1 8 10 11 16 now let's say We'll delete the node having the key is1 and we'll again print the link list so if I run the code now so here you can see initially there are five notes and after deleting the node having the key as 11 you can see the link list become as 1 18 10 16 and the node which was in between 10 and 16 was removed so friends this was the tutorial based on deleting a node with a specific key I hope you have liked this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to detect a loop in a link list in Java let's suppose we are given a link list having six notes say 1 2 3 4 5 6 and which contains a loop so here if you see the head points to the first note first note points to the second second points to third third points to fourth fourth points to Fifth Fifth point to 6th and six point to third therefore you can see that this link list contains a loop as 3.2 4 4.2 5 5.26 and 6.23 and again it goes on and if you see below is the algorithm to detect whether a link list contains a loop or not so let's see the demonstration of this algorithm step by step now in the first step we are simply creating the reference of list node by name fast pointer which is pointing to head so it looks something like this so here you see as head points to this first node now fast pointer will be referring to this first node moving ahead we'll also create one slow pointer which will refer to the head so it would look something like this moving ahead now friends we are encountering here a while loop so the basic idea behind this algorithm is in order to detect this particular Loop in a link list so what we are doing here is we know that fast pointer and slow pointer both are pointing to head so therefore they are at the start position now the basic idea behind this algorithm here is we will move slow pointer one step and we will move fast pointer two steps and if suppose the link list doesn't contain the loop then we know that the last node should point to null therefore we are traversing fast pointer two steps and slow pointer One Step because because if link list contains a loop then there will be a situation as slow pointer is moving slowly and fast pointer is moving fast so the fast pointer will never encounter null value and there will be a situation where fast pointer will meet the slow pointer because of the loop nature so here in while loop we are placing a condition as fast pointer should not be null and fast pointer next should not be null now here we know that as the link list contains a loop therefore the fast pointer will never be null and we are checking that fast poter next is not equal to null because as we are traversing fast pointer by two positions we need to make sure that fast pointer next is also not equal to null and in while lo you can see we are assigning a value of fast pointer next next to fast pointer as we are traversing it two steps so we need to make sure that fast pointer next should not be null because if it is null then we will encounter null pointer exception therefore the condition we are placing is fast pointer should not be equal to null and fast pointer next also should not be equal to null So currently if you see fast pointer is pointing to the node first having data is one and its next is also not null therefore the condition in while loop comes out to be true so in the first step what we are doing we are just reversing fast pointer to two steps so here if you see we are assigning fast pointer next next value to fast pointer so here fast pointer is pointing to the first Noe its next is pointing to the second node and it next is pointing to the third node therefore here we are simply traversing fast pointer by two positions so it would look something like this so we have simply Traverse fast pointer by two positions moving ahead now here we are simply traversing slow pointer by one position so we are assigning slow pointer next value to slow pointer so slow pointer is currently pointing the first node and it next is pointing to the second node so we are simply traversing it by one position so it would look something like this and then we are simply checking that whether slow pointer is equal to fast pointer or not so we are doing this step is because there will be situation where fast pointer will Traverse all the node and again meet the slow pointer because the link list contains a loop and there is no end to the link list so currently slow pointer is pointing to the node second and fast pointer is pointing to the node third therefore they are not equal so the condition in if blog comes out to be false and now we'll again check that whether fast pointer is equal to null or not and its next is equal to null or not so fast pointer is pointing to third node therefore it's not equal and fast pointer next is pointing to Fourth node therefore it's not equal so the condition in while loop comes out to be true and then in the first step we simply traversing fast pointer by two positions so here if you see fast pointer next is pointing to the fourth Noe and its next is pointing to fifth note so we are simply traversing fast pointer from third position to fifth position by assigning fast pointer next next value to fast pointer so it would look something like this moving ahead then we are simply traversing slow pointer by one position by assigning slow pointer next value to slow pointer so it would look something like this moving ahead now we are again checking whether slow pointer is equal equal to fast pointer or not so you can see slow pointer is pointing to third node and fast pointer is pointing to fifth node therefore they are not equal hence the condition in if blog comes out to be false now we'll again check the condition in while loop so fast pointer is currently pointing to fifth node therefore it's not null and fast pointer next which is sixth node is also not null therefore condition in while loop comes out to be true so in the first step we are simply traversing fast pointer by two position and here you can see we are assigning fast pointer next next position to fast pointer so fast pointer next is six and its next is three so we are simply traversing the fast pointer from fifth position to third position so it would look something like this moving ahead now here we are simply traversing slow pointer by one position by assigning slow pointer next value to slow pointer so slow pointer is pointing to third node and its next is pointing to Fourth node so we are simply traversing it by one position so it would look something like this moving ahead we are again checking whether slow pointer is equal to fast pointer or not so fast pointer is pointing to third node slow pointer is pointing to Fourth note therefore they are not equal so the condition in if blog comes out to be false and now we are again checking in the while loop that fast pointer is equal to null or not so fast pointer is pointing to third node therefore it's not equal and fast pointer next which is fourth node which is also not null therefore the condition in y Loop comes out to be true now we are simply Trav in fast pointer by two positions by assigning fast pointer next next value to fast pointer so here fast pointer is currently pointing to third node and its next is pointing to Fourth node and its next is pointing to fifth node so we are simply traversing fast pointer from third position to fifth position so it would look something like this moving ahead now we are simply traversing slow pointer by one position by assigning the slow pointer next value to slow pointer so slow pointer is pointing to Fourth note and it's next is pointing to fifth therefore we are simply traversing it by one position so it would look something like this moving ahead and now we are checking whether slow pointer is equal to fast pointer or not so friends here slow pointer is equal to fast pointer therefore we are very much sure that this link list contains a loop so the condition you see in the fog comes out to be true and we simply return true because we have identified that this link list contains a loop so friends here we saw the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial I had created one class by name singly link list now this class has a list note by name head which is the instance variable and we also created one inner class by name list node you can watch my previous tutorials in order to understand more about how to implement a singly link list so in this tutorial we will write a code which we saw in the slide and see it's working so first I I will create one method as public Boolean and let's say I give method name is contains Loop so basically I will write the code inside this method contains Loop and it will return me back a Boolean value that whether the link list contains a loop or not so in the first step we'll create a fast pointer reference variable and we'll assign the value of head to it in the Second Step we'll create a slow pointer and we'll assign the value of head to it moving ahead now we'll create one while loop which we saw in the slide and we'll provide condition as fast pointer should not be equal to null and fast pointer next should not be equal to null and in the while loop we'll Traverse fast pointer by two positions so we are simply assigning fast pointer next to next value to fast pointer so we are simply traversing fast pointer by two positions and then we are simply traversing slow pointer by one position so we are assigning slow pointer next value to slow pointer and then we are providing an if check that if slow pointer is equal to fast pointer then simply return true and it means we have identified that the link list contains a loop and after the while loop if suppose we haven't found any Loop then we simply return false so friend this is the algorithm which detects whether the link list contains a loop or not now we also create one more method which will actually create a link list having a loop so public void create a loop in linked list so in this method we'll create few notes we'll assign them in such a way that it will create a loop inside a link list so friends in the slide we saw an example where the link list contains six notes and which was forming a loop so I will simply replicate that example here so for that I will create list node say first equals new list node and I give value as one now I'll create five more list noes so I'll just give them Valu as 2 3 4 5 six and I'll change the name as second third fourth fifth sixth now as we saw in the slide that head points to the first note therefore we'll simply assign value of first to head and we also know that first next was second second next is third third next is fourth fourth next is Fifth Fifth next is Sixth and in order to create a loop the example we saw in the slide was sixth node next refer to the third node so here we simply assign value of third to six next so 6 do next and we'll assign value of third to it so this will create a link list containing a loop where first is pointing to second second is pointing to third third is pointing to fourth fourth is pointing to Fifth Fifth is pointing to sixth and sixth is pointing to third so it will create a loop now in the main method Let's test the working of this algorithm so in the first step we have simply created an instance of singly Link list in the second step I will call this method create a loop in link list so create so after this method get executed the head will be pointing to a link list containing a loop so in the third step we'll simply print the output of contains loop on the console so here so here we'll simply call contains Loop method and whatever the outcome of contains Loop is we'll simply print it on the console So currently you can see the link list which we have created in this create a loop in link list method has a loop so the contains Loop method should return true so if I run the code so you can see it returned true because the link list which we created in this method had a loop now here suppose I don't assign the value of third to 6. next so if I commment this line then we know that this link list is not containing a loop so if I run the code now you can see it returned false because here we have break the link in the link list which was actually making a loop so friends this was the algorithm to detect whether a link list contains a loop or not I hope you like this video thanks have a nice day hello everyone so in our previous video we discussed about that how we can detect a loop in a singly link list now in this video we will see that how we can find the starting point of that Loop so for example so here you can see that let's suppose we are given with the singly link list which contains six notes 1 2 3 4 5 and 6 but here you can see that from three it goes to four and from four it goes to five from five it goes to 6 and from six it again goes back to three so here you can see that there is a loop in this singly link list so in our previous video we saw an algorithm where we detected the loop in a singly link list so this is the code for that now in this video we will see that how we can find the starting point of that Loop So currently if you take this example then three is the starting point of that Loop because from three Loop starts and ends at three only so our task is to find the starting node from where the loop starts so friend this algorithm contains two parts one is the detection of the loop and the second part part is to actually find the starting point of the loop so the first part of detecting the loop we discussed in our previous video so in this video we will see that how we can find the starting node of the loop in a singly link list so friend let's see the demonstration of this algorithm step by step but before we begin in case if you're new to my channel then please subscribe to my channel so that you never miss any update so friends here you can see this is the first part which we already discussed in our previous video where what we did was we created two pointers one was the fast pointer and another was the slow pointer we started both the pointers from the head and in order to detect that whether the singly link list contains a loop what we did was we moved fast pointer two steps and we moved slow pointer one step so why we actually do that is because in case if the singly link list doesn't have the loop the fast pointer is moving twice the speed of slow pointer so fast pointer will reach to the end of the singly link list but if the singly link list contains the loop then as slow pointer is moving slowly fast pointer will cross over this Loop perform n number of cycles and it will meet slow pointer in one of these nodes because there is no end to the singly link list once the point reaches beyond the starting of this Loop so in our previous video in this file Loop if slow pointer meets fast pointer we actually returned a Boolean value true stating that we detected a loop in this singly link list and we actually return from this method but in this algorithm when we find that slow pointer is meeting to fast pointer inside this Loop then we actually called yet another method which provides us the starting node of the loop so this demonstration of detecting the loop and finding the meeting point of slow pointer and fast pointer as we already discussed in a previous video so here I will be quickly demonstrating it so here we will start fast pointer and slow pointer from head and now in while loop we are providing two conditions that fast pointer not equals to null and fast pointer next is not equal to null so why we are providing this condition is because if fast pointer equals null then it means the singly link list doesn't have any Loop and there is a end to this singly link list because we are traversing fast pointer inside this while loop and at some point fast pointer is pointing to null it means that we have reached to the end of the singly link list and the next condition fast pointers next should also be not equal to null because here if you see in this line we are traversing fast pointer two places by assigning fast pointers next next so here if fast pointers next becomes null then we'll encounter a null pointer exception here so here we are providing this condition to Simply check that whether fast pointer next also should not be equal to null So currently fast pointer is not equal to null it's next is also not equal to null so this condition comes out to be true in the first step we are moving fast pointer by two nodes by assigning fast pointer next next value to fast pointer so fast pointer next will make it reach here and its next will make it reach here so it would look something like this moving ahead and as we discussed that we are moving slow pointer by one position so we are simply assigning slow Pointer's next value to slow pointer so slow pointer will come here moving ahead currently so pointer is not pointing to fast pointer because here you can see fast pointer is pointing to three slow pointer is pointing to two therefore the condition in IFL comes out to be false we again reach to the while loop where we'll check whether fast pointer is equal to null or not so fast pointer is not equal to null and its next is also not equal to null so the condition in while loop comes out to be true now we move fast pointer by two steps by assigning fast pointer next next so fast pointer will reach to node 5 and slow point will reach to node three slow pointer is not equal to fast pointer this condition is false fast pointer is not equal to null and its next is also not equal to null we move fast fter by two steps by assigning fast pointer next next to fast pointer so fast poter will reach to node three and we'll move slow pointer by one step so it will reach node four this condition is false because slow pointer is pointing to four and fast pointer is pointing to three fast poter is not equal to null and its NEX is also not equal to null we move fast pointer by two steps by assigning fast pointer next next value so fast pointer next is four and its next is five so it came here we'll move slow pointer by one step so slow pointer will reach here so friends now here you can see that slope pointer is met to fast pointer at this node so it means we have detected a cycle inside the singly link list by using two pointers fast pointer and slow pointer so friend this algorithm is also known as floid cycle detection algorithm now when we get the meeting point of slow pointer and fast pointer we go into the if condition and here we will call a method as get starting node and will pass pass the slow pointer there so now it would look something like this that call will reach to this method where we'll still have the reference to slow pointer which is pointing to the meeting point of slow pointer and fast pointer so friends the idea behind this algorithm to find the starting node of the loop is at the first step what we do we again create a temporary list Noe we start started from the head and we already have reference to the meeting point of slow pointer and fast pointer so now what we do is we simply provide a while loop we move slow pointer by one step and we move temporary node by one step and in the while loop we provide the condition that perform these steps till slow pointer is equal to Temp so when slow pointer will be equal to temp this file Loop will terminate and when slow pointer will equal to Temp at whichever node this condition comes out to be true that will be our starting node of the loop so here we will move slow pointer by one step and we will move temp by one step So currently here you can see slow pointer is not equal to Temp because slow pointer is pointing to five and temp is pointing to node one so this condition comes out to be true now inside this while loop as we discussed we move both the pointers one one step so first we move the temporary node by assigning temp do next to Temp so now temp will come here and then we'll assign slow Pointer's next value to slow pointer so slow pointer is pointing to five its next is pointing to six so now slow pointer will point to six we check whether slow pointer is equal to Temp or Not So Slow pointer is not equal to Temp CU temp is pointing to two and slow pointer is pointing to six so the condition in the while block comes out to be true we move time by one step so it will reach three we move slow pointer by one step by assigning slow pointers next to slow pointer so it will reach here we check whether slow pointer is equal to Temp or not so here you can see that slow pointer is equal to Temp because they are pointing to the same node so this condition comes out to be false and at the last you can see that we have actually found the starting node of this Loop which is three so wherever temp and this slow pointer will meet that node will be our starting node of the loop so from this method we'll simply return this node which is three so from this algorithm is Floyd's cycle detection algorithm so now one question comes to our mind is that when we found the meeting point of the fast pointer and slow pointer and we created two pointers temp and slow pointer and made them move one one step in this file Loop and when they actually met we are simply saying that that is our starting node of the loop but what's the proof that this cycle detection algorithm given by Floyd works so friends in our next video we will see that why this algorithm works because currently we have simply demonstrated the algorithm and we have find our starting in point of the loop but we don't have any proof that whether this algorithm actually works or not so in our next video we will see that why Floyd's cycle detection algorithm works so friends I hope you have liked this video and in case if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in our previous video we discussed about the Floyd's cycle detection algorithm where we saw that how we can detect a loop in a singly link list and how we can find the starting node of the loop so friends here if you see that in one of our previous video we saw the algorithm of finding a loop in a singly link list where we use these two pointers fast pointer and slow pointer and we made fast pointer move two steps and slow pointer by one step and we provided this condition that fast pointer should not be equal to null and fast pointer NE should not be equal to null so in case if the singly link list doesn't have this Loop then fast pointer must have reached to the end of the singly link list but if the singly link list contains a loop then inside this V Loop there will be a point that fast pointer will meet slope pointer because of the loop so here we returned true if the singly link list had the loop or else we returned false so now in this video our task is to find the starting node of the loop so here you can see I'll simply copy this method and as the algorithm of the first part Remains the Same here we need to return back the starting node of the loop we can give any name but here I'm giving start node in a loop and here when the fast pointer will meet slow pointer so our previous video where we saw the animation this meeting point is very important so let's say if there is no Loop so here we simply return return as null and if there is any Loop because slow pointer is meeting to the fast pointer then we'll call one method here which will return return as the starting node of the loop and we'll pass the slow pointer to it because this meeting point is very important so I will create one method so friends now here in order to get the starting node of the loop what we do is as we already have this meeting point so this becomes our first node and we also create one temporary node and we point it to the head so now here we have two nodes one is the slow pointer and other is the temporary node where temporary node is pointing to the head of the singly link list and slow pointer is pointing to the meeting point of slow pointer and fast pointer which we saw here and that point will be inside the loop so friends here now what we do is we move slow pointer by one step and we move temporary node by one step and that we do in the while loop so we make them move one one step till they meet and wherever they meet meet that node where they meet will be our starting node of the loop so here in while loop we provide the condition that keep on iterating and moving temporary node and the slow pointer by one one step till slow pointer is equal to Temp so if they are not equal to each other then we are simply moving 10 by one position and similarly we are moving slow pointer by one position and when temp and slow pointer value will point to each other this condition will come out to be false and at the end we'll simply return the temporary node so this temporary node will be our starting node of the loop so this is what Floyd cycle detection algorithm states that wherever this temporary node and slow pointer will meet that node will be our the starting node of the loop so friends why this algorithm works we will discuss in our upcoming video but for time being you just think that this algorithm works so here now we'll call this method and we'll test its working so here you can see that in one of our previous video we already created a loop using Create a loop in link list method where first point to second second pointed to third third pointed to fourth fourth pointed to Fifth Fifth pointed to sixth and here you can see sixth pointed to third it means there is a loop and this is the same example which we discussed in our previous slide as well so so here we know that there is a loop in a singly link list if we call create a loop in singly link list so from head this singly link list will start and there will be a loop so I'll just comment this part so here I have simply uncommented and we are simply calling create a loop in link list and let's say we also call the contains Loop method so that will return return us a Boolean value so first I will simply run that part and here you can see that it return returned true so it means there is a loop in that singly link list now what we'll do here we know that the starting point of the loop is list note third having data as three so after we figure out that there is a loop what we do is we simply call the method start node in a loop here what we do is we simply print the data of the returning node so here can it printed three which is the data of the node from where the loop starts so friends here the only idea we need to remember is after finding the meeting point of slow pointer and fast pointer we keep the slow pointer at that position only and we create a temporary pointer which will start from the head and in the while loop we simply move both the pointers by one one step and keep checking that whether temp is equal to slow pointer or not so when temp will equal to slow pointer this file Loop will terminate and that node where these both the pointers will meet will be our starting node of the loop so friend currently we haven't seen that why this algorithm Works in our next video we will see the mathematical proof that why this algorithm Works which is named as Floyd cycle detection algorithm so friends I hope you have liked this video and in case if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in this video we will discuss that why Floyd cycle detection algorithm works so friends in our previous video we saw that how we can detect a loop in a singly link list and we also saw that how we can find the starting node of that Loop so the algorithm which we saw it was just a code which usually works but there was no proof that why this algorithm works so in this video we will see that why floid cycle detection algorithm works so friend let's suppose we are given with this singly link list so here you can see that singly link list contains nine notes 1 2 3 4 5 6 7 8 9 and if you see that from the sixth node the loop starts and the last node points to the sixth node so therefore this Loop starts from here so basically in order to detect that whether this singly linklist contains a loop what we do is we simply create two pointers one is the slow pointer and another is the fast pointer and we usually start it from the head now what we do as the name suggest the fast pointer moves two steps and slow pointer moves one step and we perform this steps in iteration that fast pointer moves two steps then slow pointer move one step so friend if this singly link list doesn't contain Loop then fast pointer will reach to the end of the singly link list where last node next will point to null and if there is a loop then fast pointer will keep on traversing here and slowly slow pointer will enter the loop and fast pointer will meet the slow pointer somewhere in the loop so first let's see how it works we moved fast pointer by two steps slow pointer by one step we moved fast pointer by two steps slow pointer by one step fast pointer by two steps slow pointer by one step now here from here fast pointer reached here because this is the first step this is the second step slow pointer by one step fast pointer by two steps so friends here you can see that slow pointer is still completing this tail of the singly link list but the fast pointer has already completed one Circle and based on number of notes and the size of the loop there can be possibility that when slow pointer will enter the loop fast pointer must have completed X number of Cycles so here you can see now we'll move slow pointer then we move fast pointer by two steps so it will reach here slow pointer here now as we started our algorithm with fast pointer so we are moving fast pointer by two steps and then our iteration will end with slow pointer with one step so slow pointer will reach here then we'll again do a while loop and fast pointer will reach here and then our iteration will end when slow pointer will reach here so friends here you can see whenever iteration will end with the slow pointer we see that now slow pointer and fast pointer are meeting at this node so friends there could be a possibility that based on number of nodes and the size of loop there could be a possibility that before meeting the slow pointer fast pointer must have completed this Cycles X number of times and similarly slow pointer must have completed this cycle let's say y number of times before meeting at this node so the first part of the algorithm is detecting this Loop in case if fast pointer meets slow pointer then we know that there is a loop so this is the first part of Floyd cycle detection algorithm the other part is to find the starting node of this Loop so after finding the meeting point of fast pointer and slow pointer what we do is we keep slow pointer here and we move a temporary pointer from the head and now this time we move slow pointer one step and temp also by one step so what this algorithm will tell us is if we move both the pointers one one step when temp will reach to the start of the node slow pointer also will reach to that particular node and basically in code when they meet to any node that node will be our starting point of the loop so let's see how we move time by one step we move slow pointer by one step we again move 10 by one step slow pointer by one step we move 10 by one step slow pointer by one step then again we move time by one step and slow pointer by one step so friends here you can see that based on number of notes Here in the tail and in the loop you saw that slow pointer started from here and it completed one cycle and reached to the same point here and now if we move Time by one step it will reach here and if we move slow pointer by one step it will reach here so this algorithm tells that at whichever node these two pointers will meet that would be our starting point of the loop or the starting node of the loop so now there are two parts of the algorithm one is of detecting the loop that is the meeting point of the slow pointer and fast pointer and other is the finding of this starting node so here if we draw this singly link list let's say something like this that this is a tail and this is the loop and let's say they meet at this point so here you can see we are denoting this tail with a value M and fast pointer comes inside the loop it goes and performs two cycles and reach here and slow pointer also performs of less lesser number of cycles and finally meet it here or it could be possible that slope and doesn't complete any cycle and simply meets here so we are giving this distance as K and the complete length of this Loop let's say we are denoting it by n so this is the current picture from where we will start our proof so let's say we are assuming that fast pointer and slow pointer meet here if they meet here then this singly must be containing a loop at the start we are simply assuming that let's say they meet here so the distance traveled by fast pointer would be let's say we denoted by DF so the fast pointer will start from here it moves M distance and there could be possibility that fast pointer travels this Loop let's say x number of times and once it performs The Loop it will come to the starting point only and then it goes K distance and meet the slow pointer so we can simply write the distance traveled by fast pointer as M plus the N is the length of this Loop and CF is an integer which can be like 1 2 3 4 5 so we are not sure that how many cycles fast pointer will perform so we are denoting it by a constant CF which would be an integer so it can make one cycle it can make two cycles it can make three Cycles so in order to calculate distance we are multiplying n by CF plus K so if the cycle starts from here it will reach back here and then it goes K distance so this is the K distance and similarly distance traveled by slow pointer let's say we denote a DS it would be M plus let's say the slow pointer also performs some of the cycles around this Loop and we don't know how many cycles it performs so we denote it by CS so this is also a constant basically an integer value multiplied by the length of the loop plus so if it starts looping from here then it performs one Loop or let's say CS loops and then it will travel K distance and meet the fast pointer here so plus K so now as we know that both the pointers are starting at same point and meeting at this point so the time travel by both the pointers will be same and as fast pointer is moving two steps and slow pointer is moving One Step so the distance traveled by fast pointer will be twice the distance traveled by slow pointer so let's say distance travel by slow pointer is X so if the fast pointer is moving twice the speed of slow pointer then the distance travel by fast pointer will be 2x so if we substitute these values in X and 2x it would be something like this x will be equal to m + n CS + K and 2x will be m + n CF + K so here the constants are different CF and CS which are nothing but the integer values so m + n into CF + K now what we do is we simply subtract X from 2x so we simply subtract this equation from this equation so what we get is this x will get cancel out with this x so only 1 x will remain so here you can see M will cancel out K will cancel out and if we do n into CF minus n into CS taking n common it would look something like this n into CF minus CS so this would be the equation which will be coming out so friends here you can see that based on the what equation came out if we closely observe this equation then here you can see that this x is equal to n into cfus CS so here you can see n is constant because this length of the loop will remain the same and CF minus CS are nothing but integers so there will be a value for CF and CS when multiplied by n will give us a distance X so here you can see that if we substitute some of the values in the left left hand side and in the right hand side let's say for CF and Cs and x and N so you will find that this equation is solvable so which proves that this equation is derived when we assume that they will meet at this point and if they are meeting at this point then there will be a loop inside the singly link list so you can try to substitute many values here and you will see that you will find the solution of these equations so this proves our first point that how we detect that there is a loop in a singly link list now we'll see that let's say this is the meeting point and if we move the slow pointer by one step and temporary pointer One Step then why they actually meet at the starting point of the loop so this will be our second part of the algorithm which we need to prove so here we go by same analogy the distance travel by fast pointer is DF m plus n CF + K and distance Trav by slope point will be m + NCS + K now here what we do is this is also we discussed that distance traveled by fast pointer will be twice the distance traveled by slow pointer so which means DF will be twice DS because fast pointer is moving twice the speed of slow pointer so the distance traveled by fast pointer will be twice the distance traveled by slow pointer so if we sub substitute these values we will get M plus ncf + k equal 2 into m + NCS + K now we'll multiply two inside this and we'll get 2 m + 2 N CS + 2 K now what we do is we'll take M this side so it will so if we take it this side it will become Min - M and minus K and here we have 2 m and 2 K so 1 1 m M and K will be subtracted and here if we take 2 N CS here so it will be ncf minus 2 NCS so this equation after solving it will look something like this that ncf minus because we are taking this this side so it will become minus 2 N CS this m we took it here so it became 2 m minus M so it gave M and K we took it here so it became 2 K minus K which gave us a value k so friends here you can see that m is the length of the tail of the singly link list and K is the distance from the starting node to a point where the fast pointer and slow pointer meet and N is the length of the loop so friends here you can see we'll take n common so it would look something like this and here you can see from the starting point till this point this value is K and total value of this Loop is n so if we denote this small semicircle as or the arc as let's say R like this so over this equation what we do is we take K this side so it becomes n into cf- 2 CS minus K so friends to K what we can write is so here you can see that k + r will be equal to n because K is till this point and R is still this point and if we add them we will get n so what would be the value of K it would be n minus r so if we denote n minus r instead of K it would look something like this n minus r came here now we'll multiply minus into this bracket so it would look something like this Min - n + r and now it if we take n common from these two terms we will get something like this cf- 2 CS minus n so we are taking n common so it will become minus1 braet + r = m so friends here you can see that this n is the length of the loop and CF - 2 CS minus 1 here CF is an integer CS is also an integer and minus1 is a constant and so so what is equation denotes so here you can see M which would be the Distance by the temp and it will reach the starting point and here you can see that if you have starting slow pointer here then this equation if we travel this much part n into some integer value so that would be the number of Loops where n will be multiplied by let's say some integer value or it can come out to be zero so for timing let's suppose this equation comes out to be one so it means if you're starting slow pointer here it will perform one Loop and will reach to the same point and let's say if if this equation comes out to be zero so it will stay at this point only because this complete part will be zero and if we take this Valu at 2 3 4 and if you are starting it from here so it will travel like this but it will always reach to this this point only because it is starting from this point so so this part is telling us that if we are starting the slow pointer here and whatever the value this part this equation comes in the bracket it will always make it reach to the this point only and here you can see if we travel plus r after making few Cycles by this equation slow pointer will reach here only and if it travels plus r then it will meet the temporary because here you can see m is equal to some Loops plus r if temp will move M steps the slow pointer will has moved some number of cycles and it it would have reached here and it and then it would have moved plus r so it would have meet temp here so which means that based on our values here from this point if slow pointer travels let's say one cycle two cycles three Cycles it will reach here only and meanwhile M would have reached somewhere here because they are moving at same speed one one step and finally when it would have traveled R it would have met it somewhere here which would be the starting node of our Loop so this equation tells that m is equals to Some Loops by the slow pointer plus r so if we are starting from this meeting point the slow pointer it would have performed Some Loops and it would have reached here only and then based on our this length which is R it would have traveled R then it would have reach the starting point of the node and it would have met temp so this equation is telling that if we are dividing our Loop in K and R terms and the total length of this Loop is n so we need to Simply prove that slow pointer if it is starting from here then whatever distance as it travels it should meet the temporary node when temp has performed M steps so here you can see when temp has performed M steps which is this part of the equation that would be equal to n into an integer multiple so it would be it is starting from here it makes few Cycles it reach to the same point and then it is traveling simply plus r so if it is traveling plus r it would reach to the starting point of the loop and where it will simply meet M because m is equal to this equation so friend this proves that from the meeting point of the slow pointer and fast pointer if we travel slow pointer by one step and temp by one step so wherever they will meet that will be our starting point of the loop so friend this proves that why Floyd cycle detection algorithm Works in case you have find this information useful then please like this video and if you new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in this video we will discuss that how we can remove a loop from a singly link list so friends in our previous videos we saw that how we can detect a loop in a singly link list and after detecting the loop we also saw that how we can find the starting node of the loop and we demonstrated both the algorithms using Floyd cycle detection algorithm and we also saw the proof of Floyd cycle detection algorithm that why it works so based on similar concept we will see that how we can remove the loop from the singly link list so before we start in case if you new to my channel then please subscribe to my channel so that you never miss any update so friends here you can see let's suppose we are given with this singly link list which is having a loop starting from node 3 so here three is pointing to four four is pointing to node five and five is pointing to node 6 and node 6 is again pointing to node 3 so here you can see that there is a loop and our task is to remove this Loop so the only way in which we can remove this loopus if somehow we reach to this node and we break this link and once we break this link and if we assign it to null then it will become a singly link list which will not have any Loop so friends the idea behind this algorithm is it's very much similar to what we discussed in our previous videos that we create two pointers we name them fast pointer and slow pointer both starting from the head from here and then we provide a while loop so inside this while loop what we do is we move fast pointer by two steps so here you can see we are assigning fast pointer next next so for example if suppose fast pointer is here its next is this node and its next is this node so we are moving fast pointer by two steps and we are moving slow pointer by one step so once they will reach inside this cycle and if the singly link list contains a cycle there will be a situation when slow pointer and fast pointer will point to the same node which will prove that there is a loop in the singly link list so this idea we have already discussed in two of our videos so the first part is to find that meeting point of slow pointer and fast pointer so we'll quickly go over the algorithm to find the meeting point of slow pointer and fast pointer so here we are starting both fast pointer and slow poter pointer from head and we are providing a condition in while loop as fast pointer should not be equal to null and fast pointer next should not be equal to null because here we are traversing fast pointer by two steps we have to provide this check because if fast pointer next comes out to be null then here we'll get a null pointer exception so we are providing this safe check here so currently fast pter is not equal to and next is also not equal to null so we'll quickly go over this demonstration because we have already seen it in our previous videos we have moved fast pointer by two steps and we will move slow pointer by one step and after we perform one iteration we simply check that whether they are pointing to the same node or Not So currently they are not so after second iteration this is the situation and still they are not pointing to the same node still slow pointer and fast pointer are pointing to different nodes so friends now here you can see that both slow pointer and fast pointer are pointing to node five it means that there is a loop and our if condition slow pointers equals fast pointer comes out to be true now which will signify that there is a loop so in the second part of the algorithm which is what we want to remove the loop so here now we will call remove Loop method and we'll pass in the slow pointer and once this method will end this Loop will be removed and we'll simply return from this method so here as we have passed low pointer so it will still point to node 5 because this is the meeting point of the fast pointer and slow pointer so friends in one of our previous video we discussed that how we can find the starting node of this Loop where what we did was we created a temporary variable we started it from head and then we had moved 10 by one step slow pointer by one step and where they would have met that was our starting point of the loop and we also proved Pro the algorithm mathematically that why moving temp by one step and slow pointer by one step in a while loop will make them meet at the starting point of the node so this algorithm we proved in our previous videos so you can watch those videos so here we'll apply the same analogy we start from the head which would be our temporary variable and slow pointer from the meeting point of slow pointer and fast pointer now here we are providing a while loop so when we were actually finding the starting node of the loop our while loop condition was that perform the iteration till slow pointer meets the temporary node and inside this value we were moving both the pointers one one step but now here you can see that as singly link list contains a loop and we want to break this link so we don't have to go the till the starting point we have to go a note before that and we have to remove this link so the only way to reach node 6 is instead of comparing slow pointer with temp here we are simply comparing slow pointers next to Temp next because we know that when slow pointer will reach at Noe 6 temp will reach at note two and the both pointers next will point to the starting node of the loop so therefore we have to break this while loop at dead point because we have reached slow pointer to a node which is just before the starting point of the loop so let's see how So currently slow pointers next is not equal to Temp next because temp next is pointing to Note 2 and slow pointer next is pointing to node 6 so the condition in V block comes out to be true we move move temp by one step so temp goes to his next node where we assign temp. next value to Temp and similarly we will move slow pointer by one step by assigning slow pointers next to slow pointer so slow pointer next is Note 6 so now slow pointer will point to Note 6 now friends here we again check whether slow pointer next is equal to temp next or Not So Slow pointer next is node three and temp next is also node three so therefore this condition comes out to be false because slow pointer next is equal to Temp next so this is the only minor difference between finding the starting point of the loop and finding a node before the starting point of the loop and why we need a node before the starting point of the loop because we need to break this link and the only way to break this link is if we have reference to this node so therefore here the only difference between the two algorithm is this condition if you want to find the starting point of the loop then this while loop condition becomes slow pointer not equal to Temp and if you want to find a node before that then you have to provide this condition that slow pointer next is not equal to Temp do next so here this condition comes out to be false and why Loop will terminate so at the end in order to break this link what we'll do is we simply assign null value to slow pointers next so it would look something like this that slow pointer next is pointing to node 3 so this link will go away and now it will point to null so friend after this assignment you can see that our singly link list which had a loop in between now it will end with a null value so friend this was the demonstration of the algorithm step by step I hope you have find this information useful and in case you have find this information useful then please like this video and if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in our previous video we discussed about that how we can remove a loop from a singly link list we saw an animation of the algorithm so in this video we'll write the code for that and we'll test its working in the main method so here in our singly link list class which has this instance variable head of type list node so here inside this class I have demonstrated so many algorithms related to singly link list so here you can see the last algorithm we discussed was how to find the starting node of the loop where we first created the loop then we simply checked that whether there is any Loop or not and once we found that there is a loop we wrote the algorithm for finding the starting node of the loop and we printed its data on the console so here you can see that we use used a simple example which we also saw in our previous slide that we have created six notes 1 2 third fourth fifth 6th where all the nodes are connected to each other and the last node is connected to node third so node six was connected to node third which created the loop in the singly link list so head pointed to First node first pointed to second second pointed to third third pointed to fourth fourth pointed to Fifth Fifth pointed to sixth and sixth pointed back to third so there was a loop and the starting point of that Loop was node third so if I run the code now which we already discussed in our previous videos so here you can see the starting point of that Loop was at node 3 where we printed its data on the console so in this video we'll look into algorithm where we'll simply break the loop Loop which means that from node 6 to node third will break this link and then sixth node will point to null so let's code the algorithm so friends here you can see that this algorithm of removing the loop from the singly link list has two parts one is to detect the loop and part two is to actually remove the loop so here in our previous videos we already discussed that how we can detect a loop in a singly link list using Floyd cycle detection algorithm and we also saw the proof for that algorithm so here when fast pointer will meet the slow pointer then instead of going and finding the starting note what we'll do is we will remove the loop so the first part of algorithm is pretty much the same I'll paste the code here and instead of returning the list node as we are not returning anything we will make it void we'll name the method as remove Loop and rest of the part remains same till the cycle is detected where fast pointer is equal to slow pointer which we already discussed in our previous videos we'll remove this return null and here instead of going and finding the starting node of the loop what we'll do we'll simply create a method as remove Loop and we pass in the slow pointer and once we remove the loop we'll simply return from this while loop or we can break the while loop so here I'll be creating one private method as remove Loop which will take in a list node slow pointer which is we are calling this method from here and inside this method we'll actually write the code to remove the loop we also discussed that how we can find the starting node of the loop so the idea of finding the starting node of the loop and to remove the loop is pretty much the same with only small changes so I'll copy this part so here we have the slow pointer which is nothing but the meeting point of fast pointer and slow pointer and we pass slow pointer into this method so we have this slow pointer here and inside this remove Loop method we are creating this temporary variable which will start from head so friends when we discussed that how we can find the starting node what we did was we made slow pointer move one step and we made temporary pointer move one step inside this while loop and when they met so temp became equal to slow pointer so at whichever node this both pointer met that node was our starting node of the loop and we proved this algorithm in our previous videos so similar concept is applied here here the only change we do is we simply check whether temp do next should not be equal to slow pointers next so why we have provided this condition is here this condition will make us reach to the starting point of the loop but we don't want to go till the starting point of the loop we have to just go a node before that because as it is a singly link list in order to break this chain we have to go a node before the starting point of the loop and once we reach there we can simply Break the Chain by assigning something like slow pointer do next equals null so friend this condition is important if we remove this next from both the sides then this value will make slow pointer and temporary pointer to reach to the starting point of the loop but we don't want to go to the starting point of the loop we have to go just before that so wherever these both the pointers are we are simply comparing its next value so if both the pointers next value becomes equal then we know that slow pointer is just before the starting point of the loop and once this condition comes out to be false we know that slow pointer is just before the starting point of the loop so friends here you can see that why this condition is important if we don't provide do next value in both these pointers then this V Loop will make us reach to the starting point of the loop Loop and we don't want to reach to the starting point of the loop because if we reach to the starting point of the loop then we won't able to break the cycle so what we do is we simply try to reach a node before the starting point of the loop so here instead of comparing temp with slow pointer we are simply comparing both the pointers next so that when slow pointer will be a node before the starting point of the loop its next will point to the starting point of the loop and temp next will also point to that node so this condition will come out to be false which means our slow pointer will be a node before the starting point of the loop and then at the last step we'll simply assign null value to slow pointers next so this will break the cycle of the loop which is inside the singly link list so here what we do is in the main method we simply call the remove Loop method so this will take this singly link list which contains the loop and then we'll simply call display method which will print the singly link list and if the singly link list will contain a loop then here you can see that display method will keep on running because it won't break because there won't be any null value and this will keep on going but here as we know that we are removing this Loop here if I run the code now so here you can see that from third node it pointed to Fourth then fifth then sixth and sixth again pointed to node 3 which we saw here 6 next is poed to third but when we' called remove Loop method here the loop was removed and when we printed the singly link list on the console this step made the six next to null instead of pointing to three so it simply removed the cycle from the singly link list and it printed it on the console where the last node was now six pointing to null so friend this was all about that how we can remove a loop from a singly link list I hope you have find this information useful and in case if you find this information useful then please like this video and if you new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss that how we can merge two sorted singly link list so let's see what this problem is and how to solve this so here if you see that we are given with two sorted singly link list the first singly link list has three notes 1 4 and 8 and the first note is being referenced by head one similarly the singly link list two has Notes 3 6 and 7 the first note being referenced by head two now if you see both this singly link link list are sorted in ascending order now our task is to merge them in such a way that resulting singly link list is also sorted so here you can see that when we merge these two singly link list the resulting singly link list has six notes three from list one and three from list two so total notes are six and here if you see that we have merged it in such a way that the resulting singly link list is also sorted and de to in ascending order so at the start we have 1 then 3 4 6 7 8 so one is added by list one three from list two four from list one 6 7 from list 2 and finally eight being the largest value from list one so the resulting singly link list is also sorted so let's move ahead and see the demonstration of the algorithm step by step so here you can see that we are given with two singly link list which are sorted let's say they are referred by A and B and we are calling this merge method and this merge method will return us the head of the merged sorted singly link list so here if you visualize this merge method on the call stack let's say we have the stack memory and Heap memory so stack memory usually have the calls to over methods so let's say after certain calls there is a merge call and we pass a and b as our list so here if you see that whatever the notes a will hold and B will hold they will hold in the Heap memory so these are the objects which are of type list node and a and b are references to these objects so in Heap memory it will look like this and now we need to merge these two list in such a way that the resulting singly link list is also sorted so just keep this thing in mind because it will be useful later so here is the algorithm to merge two sorted singly link list A and B so friends before we start if you want to master data structures and algorithms you can subscribe to my channel and click the Bell icon so so that you never miss any update let's say we call this merge method we pass two list A and B so here you can see A and B are usually on the stack and they are and they are referencing these objects on the Heap and a and b both the singly link list are sorted in ascending order now our task is to merge these two sorted singly link list such that the resulting singly link list is also sorted so at the start what we do is we first create a dummy node so this dummy list node will refer a list node on the Heap with a value as zero so this dummy list node can have any value this value doesn't contribute in our algorithm so we can provide any value so it would look something like this that dummy is on the stack and it is referencing one list node in the Heap memory having value is zero and next pointing to null so this is a concrete object in the Heap now why we are creating this dummy list node we will see later so one such uses of dummy is when we will compare the values of these two list so one by one we will take out the notes and add it to this dummy list node so instead of null one one value will keep on coming and at the end after this V Loop will terminate and this logic will end all the list note of both the list will be added to the list being referred by this dummy node so here dummy list node will hold our final list which we will be returning it from this method merge method so it will hold our result list which is merged and sorted the second point of creating this dummy list node is it will help us in avoiding errors like null pointer exceptions so we will see this point later that how it helps in preventing nil pointer exception so for timing you can just think that we have created one dummy list node now this list node will keep on adding one one node from both the list such that when the both the list will be exhausted all the list notes will become part of this list referred by this dummy node moving ahead now here you can see that as we have created this dummy node this dummy node will refer to this node and our task is to merge this two sorted singly link list by taking one one element and adding it after the dummy node so dummy node stays at this place what we do is we create a tail list node and which will point to dummy so it looks like this now this tail will help us in adding the nodes after the dummy node and after adding one one node the tail will move ahead and it will keep on adding till all the nodes are exhausted so that we will see in the while loop how it does now we are providing a while loop where the conditions are a should not be equal to null and B should not be equal to null so here you can see this end oper operator tells that if any of the list is exhausted or their references A and B reach to the end of the list we have to break from this while loop and why we are doing this is because so here if I take an example let's say a is referring to 1 4 and then it and B to 3 and 6 so if I see the resulting list it will be like this 1 then 3 then four then six so once six will be placed here you can see this b list will have it all the notes in the resulting list and let's say after it we have like 9 11 15 so after 6 B has got exhausted so it means that after 6 there are no more notes which can be compared with the rest of the elements of a like 8 9 11 11 and 15 so what we do is we simply break from this V Loop because one of the list got exhausted so there would be a point when either of the list can get exhausted we will see this when we will execute the while loop So currently a is not equal to null B is not equal to null so the condition in V block comes out to be true so the while block will execute now we provide if and else condition and here what we are doing is as we want to merge these two sorted singly link list such that the resulting list is also sorted what we do is we compare the data of A and B and we check which data is less so in this if condition we are checking that a data whether it is less than equal to B's data or not so here you can see 1 is less than three we are comparing 1 with three so 1 is less than three so this condition comes out to be true which means we are starting from the first node of both the list and we have found one node whose value is smaller among all the elements in the both the list because they are sorted in ascending order so your list node which is data as one being referred by a will be the first node of our resulting sorted singly link list one should come at the start so here you can see now what we do is tail is actually pointing to this dummy node and our task is to add this much node into the dummy list currently here you can see Tails next is pointing to null so if we assign a to Tails next it would look something like this the tail next which is pointing to null it will now point to a list node which is being referred by a so here this assignment will add this list node having data as one into this list whose head is dummy so we are taking the help of tail pointer to add this node so after we add this node we know that we have used one value of list a so so we simply Traverse a to its next node because the next comparison should be between 3 and four because we have compared 1 and three 1 was lesser than three so we added this list node into this list so now we simply move a to its next node so there are two reasons why we are moving it to its next node one is in the next iteration of while loop now we will compare four with three so therefore we need a reference to this node and the second point we will see in the next iteration so after this assignment a do next a next which is node four we will assign that value to a so a will come to this node now like this and here in this step as tail has added one node here now the other node will come after one because this node is added and we have to add more nodes and tail will help us in doing that so we also Traverse tail ahead by assigning tail dot next to tail so tail next is node one so now tail will reach here like this because next node will be added after one now a is not equal to null B is not equal to null so the condition in while block comes out to be true now we again compare the data of A and B so here we are simply comparing in this if blog is whether 4 is less than equal to 3 or not so 4 is actually greater than three so this condition comes out to be false and the lse block will be executed I'll just remove this so in the lse block we know that among four and three three was the Lesser value so now we have to add this node after one and how we can do that is B is referring to this list node and now we have to add this list node after one so we are taking the help of tail we assign B to Tails next here if you see tells next is pointing to this node now so we have to break this link and point it to this node so by this assignment the first thing it will happen is this link will go away and as tail next was pointing to this node now tail next will point to B which is node three like this and also friends in previous Val Loop we moved a to its next so one reason was that we are comparing four with three the other reason is we have removed this reference from here and now it is pointing to this node so as soon as we remove this reference we need something to hold this two list notes from the stack which is being done by a so therefore this is the another reason we are moving a to its next and now after this assignment we do the same this value is used up and now it is part of this list so here you can see dummy is pointing to list node having value is zero it is pointing to a node having value as one and one is pointing to a node having value as three so now we have used this value so we move B to its next node so by assigning B do next to B so B next is this node when we will assign B do next to b b will come here like this I'll remove this and similarly we also move Tail ahead because the next node will be added after three now so we have to somehow reach here and we can only reach here is by assigning Tails next to tail so Tails next which is node three we will assign it to tail so tail will come here now like this a is not equal to null B is not equal to null so the condition in V block comes out to be true now a do data which is 4 B do data which is 6 so we are comparing 4 and 6 and we are checking whether four is less than equal to 6 or not so this condition comes out to be true because 4 is less than 6 and as 4 is less than 6 the next node after three would be four so in the first step what we are doing is tail is pointing to node three Tails next is pointing to six so first we need to remove this link and how we can remove this link is two tells next we are assigning a so tells next we remove this node and we assign a which is node 4 four so it would look something like this after this assignment we have used four also so we move a to its next node by assigning a do next to a a do next is 8 so a will come to 8 via this reference and as we have added four here the next node will come after four and we are adding node based on our tail so we have to move Tail also one node ahead so we are assigning tail do next to tail so tail will come here like this via this assignment a is not equal to null B is not equal to null so the condition in V block comes out to be true and now we are comparing a data and B data we are comparing 6 and 8 and here we are checking whether 8 is less than equal to 6 or not in this if block so this condition comes out to be false because 8 is greater than 6 so we execute the else part so here this if condition is telling that between 6 and 8 6 is smaller so six should be added first to the sorted singly link list which we want to merge so therefore that happens in the lse block so this if block is dealing with a list and lse block is dealing with b list and here we are doing the same thing we need to add this node referred by B after four and after four means Tails next value so we are assigning B to Tails next so first we are removing this node like this and after this assignment Tails next will point to B like this and then we will move B to its next because we have used six also now so B will move to his next and here you can see B next was null so now B is referring to null we have added six now so the next node will be added after six so tail should come here and tail will only come here when we will assign Tails next to tail so tail is pointing to four its next is pointing to six so when we will assign tail dot next to tail tail will point to six like this so friends here you can see that when we are traversing this file Loop there will be a moment M that one of the list will become empty both the list cannot become empty because as we are adding one one node from each of the list there will be a point when one of the list will become empty so it could be b or a any list can become empty so if any of the list becomes empty we break from this file Loop like this and after this file Loop we have this eels block now why we have provided this eels block is B got exhausted but there could be a chance that in a there could be elements left so currently here we have only one element there could be a possibility that its next should point to let's say 9 then 10 20 like this so our task is to add this remaining nodes as well after six because tail is pointing to six and 8 should come after six via this tail node so we check that which list list got empty so here in this if blog we are checking that which list got empty whether it was a or b so here you can see B is actually pointing to null it means B got exhausted a is not equal to null a is actually referring to a node so this condition comes out to be false and the else part will be executed so here you can see if a got exhausted B comes into picture and we assign all the nodes of B to tail next if B got exhausted then we are adding all the notes of a to tells next so here B got exhausted and we need to put let's say this node into the list so at the last step what we do is we assign a to Tails next tail is pointing to six it next is pointing to null so if we assign a to it this will go away and there will be a link from Tails next to a like this via this assignment and here you can see as we need to merge these two sorted singly link list in such a way that the resulting list is also sorted we don't have to do anything with the rest of the elements of a let's say it had 9 10 20 like this because they are already sorted so via this reference all the notes will be part of now this complete list so our task will be done here so here you can see this dummy list node has built one chain which is actually our resulting list so here you can see it goes like this like this so here one thing to note here is this dummy list node was created by us therefore we don't have to include this so therefore at the end we are returning dummy. next dummy is pointing to this list node it was actually a dummy list node which we created here so at the end we need to return dummy. next so dumy next is this node so we are returning a list node which is holding this list like this from this method so the method which is calling this merge will get a list note let's say if it is called like this so our head will be pointing to one and it goes like 3 4 6 and 8 and so on so this head will be in the stack and this will be in the Heap all the notes so so we are returning dummy. next because we have to discard this dummy because all the nodes which we added using our tail we after the dummy node so we have to discard this so here if you see if I If We Hold This pointer and if we stretch it ahead this nodes will be stretched out and it will look like this so dummy was our node which we created it has no significance we return dummy. next so dummy next is this so this is our final sorted singly link list which actually has all the elements of A and B so friends here you can see that we use dummy list node and we saw that it help us in building up this list because this is one concrete node in the Heap and this is on the stack so Dum is referencing one concrete node on the Heap and then we are simply adding the rest of the nodes after dummy so this was the one case where we are actually creating this dummy list node the other thing we saw was that it helped us in avoiding null pointer exceptions so here let's say if we are not using this dummy list node so here we are not using this line instead of this dummy list node we have to create one head which we can return from this method so we have to do something like this like this instead of this in this tail instead of dummy it should point to head and instead of dummy. next we should return head because this list note head will be holding our the merged sorted singly link list but here you can see that once we execute this line and we are not creating this dummy is not so it would look something like this after this line head will point to null and when we will execute this line we are assigning value of head to tail because this tail will help us in adding of the notes in this while loop so here it would look something like this tail will refer to a value which is being held by head why this assignment so tail will also start from null now here you can see in this V block we have provided if and else block and let's say when we compare 1 and three for the first time we know that 1 is less than three so this condition would have been true because a data is less than b data so here you can see when this line would have gone executed here we are assigning a to Tails next but when this line will be executed tail is pointing to null and if you're doing this dot next it means we are accessing a variable which is being referred by tail so there should have been one concrete object in the Heap on that we have to call next but here tail is pointing to null so here you can see it will give us a null pointer exception because tail is pointing to null it doesn't have any object in the Heap on which we can call next similarly here also we would have got an error so we will get null pointer exception so this is one of the use case we are creating this dummy list node because we need this concrete object so that we can use tail and add this remaining notes so this is one important thing to remember that we usually create this dummy list node to avoid the null pointer exceptions now let's say if we are told that we don't have to use this dummy list note we want to merge this two sorted singly link list using the normal noes so we can also solve the problem that way this dummy list node is actually helping us in avoiding this errors and the checks but what if you want to merge this two list without the dummy notes so how we can approach that is now here you can see that head is starting from null now what if Head Start From a concrete list node in the Heap and it doesn't start from null so if I just remove this line so you can think before this assignment of head to tail we have to write some logic to handle this condition so that this errors are avoided what we need to do is the things which we are doing in while loop in one shot that we are comparing all the notes using this if and else condition what we do is for the first time we just check for one of the notes so this check which we are doing in the while block we have to do for the first comparison so that we can get one concrete node in the Heap so we have to write some extra logic so what we do is here you can see before while block and this tail assignment we have to write some logic like this here you can see this conditions are very much similar to this V block so here what we are doing is as we need one concrete object in the Heap and we don't have to use this dummy object what we do is to get one of the concrete objects from this tool list we do the first comparison out of this V block here we do a do data and check whether it is less than b do data and if a do data is less than b do data So currently 1 is less than three so what we do is we simply treat this node as our starting node and we directly assign head to it via this assignment and as we have used this node so we simply Traverse a to this node by assigning a do next to a so this if and else block is very much similar conditions here but for getting one of the concrete notes we do this one check out of this V block and rest of the code is pretty much the same this a not equal to null and B not equal to null a not equal to n will start from this node so when we had created this dummy list node this code we don't have to write and all the logic would have been compared in this V block so first node of a and first node of B would have been checked in the v block but if we don't want to use this domain list node we somehow need a concrete node so for getting this first node we are doing this check outside the while block here so that we can get a conrete head so rest of the logic is similar once we get head here tail will point to head like this and now in the while block if we do tail. next we actually have a concrete object here we had a null object but here now we have a concrete object so therefore this error won't come and at the end we can simply return head so friend this is how we actually merge two sorted singly link list so that resulting list is also sorted you need to be very careful while merging this two list using this dummy node it will make your code easy and simple to write but if you don't want to use this dummy node the first thing you need to do is to identify the actual starting point of the head which is our resulting list so we have to do this comparison first to get our first head and then we can provide this V block and do the similar stuff which we already discussed and at the end instead of doing w. next we are returning head so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw an animation in which we discussed that how we can merge two sorted singly link list so in this video we will actually code the algorithm and we will test its working in the main method so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in our previous videos we have created one class as singly link list so in the same class we will actually code the algorithm so here let's say I give the method name is public merge so this merge method will take two list node A and B so these two list Noe represent two sorted singly link list and now our task is to merge these two sorted singly link list and return it back from this method so here as we need to merge these two sorted singly link list the first step we do is we create a dummy list node and we provide a dummy value to it now this dummy list note will actually hold our merge sorted singly link list and in our previous video we have saw that why we are creating this dummy list node it is actually providing us a concrete object in the Heap so that we can avoid the null pointer exceptions now as this dummy list node will hold our merged sorted singly link list we will create a list node let's say by name tail and this tail will actually point to this dumy list node so the dumy list node will actually hold the complete list and we will use this t list note and we will add one one element from the both the list using this tail pointer we will see that later now after that we will provide a while loop now as we need to merge these two sorted singly link list we have to compare their respective elements with each other so that we will do in the while loop so the condition we provide is a should not be equal to null and B should not be equal to null so here as we are comparing one one element from both the list with each other there will be a time that either A or B get exhausted so if any of the list get exhausted we will exit from the while loop now inside this V loop as we are merging this two sorted singly link list and we want the resultant list also sorted let's say if I give an example so here let's say a has three notes 1 3 5 and B has three noes 2 4 and 6 now when we will merge this two sorted singly link list the resultant list will be like it will also be sorted so here in this V Loop what we are doing is we are comparing the elements of both the list first we compare 1 with two we know that 1 is less than two so one will be inserted first then after inserting one we move to three and then we compare two with three and we know that 2 is less than three so the next element comes as two so we move to four and then we compare three with four 3 is less than four so three will come here and we keep on doing that till one of the list get exhausted so here we provide if condition because we need to find the smallest element among the both the list for the current iteration so here what we do is we simply compare a data and see whether it is less than or equal to B's data so if A's data is less than equal to B's data it means to Tails next we will assign a and then we will simply move a to its next node so here when we compared 1 with two 1 is less than two so we added one to the resultant list via this assignment and then we move to 3 so we did a equal to a do next and similarly if B's data is less than A's data what we do is we simply add B to Tails next and then we move B to its next node so here 1 is less than two so we added 1 and we move to three and in the next iteration We compare two with three so 2 was less than three so we added two here and then we moved to four so that in the next iteration we compare three with four and why we are doing this comparison because we need to get this list and it should be sorted so in this while loop we are comparing each and every element of A and B and whichever element is less we are simply adding that node into tailes next and then we are simply moving the respective references to its next node so that we can compare the next element and here we also need to move Tail to its next node so here let's say first we added one so initially tail must have been here so we have used tail do next and added one so the two will come after one so we have to move Tail also ahead so that in the next iteration if we do tail do next two will come here and then we'll simply move Tail to two and we keep on moving tail ahead till there are notes in A and B so this step is also important that we need to move Tail also ahead so that in the next iteration we are adding a different element to Tails next so after this V Loop there will be two possibilities either a will get exhausted or B will get exhausted so here let's say if I copy this part so let's say instead of five we have like this and here we have so here you can see in the result list first we will add one then two will come then three 4 so after four a will get exhausted and as we need to merge this two sorted singly link list these elements should also become the part of the result list so one property here to notice as both the list are sorted and as one of the list get exhausted we can directly append the rest of the list after four so we can directly do this after the while loop like this and this will actually merge both the list and will also be sorted so here what we do is we simply check if a is equal to null because here in the while loop as we are moving a to its next and B to its next either a will get exhausted first that a will point to null or B will get exhausted that b will point to null so if a is equal to null then here we saw that we have directly appended B to the result list so here what we do is we do B else if B is equal to null we directly append a and after this FS block we know that we have merged both the list so at the end what we do is we need to return the head of this resultant list so we will will simply do dummy. nextt and we will return it so while we are doing dummy. next here you can see this dummy is a list note we created and whatever the notes we added we added after this dummy using tailes next we started with dummy node and we used tailes next and added the notes so the actual head would be dummies next because the first node was inserted in Tails next and tail was pointing to dummy so at the end we need to return return dummies next so friend this is the algorithm to merge two sorted singly link list now let's test it's working in the main method so in the main method we will create two singly link list and we will add few notes to it we do insert last and let's say if we add the noes in the sorted form so we first add one and let's say we add four and8 so this node should be in sorted form first node will be one then it will be four and then it will be a now we'll create one more singly link list and here let's say if I give value as 3 5 [Music] 8 and let's say 9 14 so here after8 this list will get exhausted and we can directly place the remaining list via this F Els block so if I do do display So currently if I run the code so here you can see see we have this two singly link list which are sorted 1 4 8 3 5 8 9 14 and 18 like this so now we'll call the merge method and as we need to pass the head of a and b what we'll do do head so we have passed the head of both the list because this method is taking a list node and this method will return us a list node representing a singly link list which is merged and sorted so here we will create one more singly link list we'll give a name as result and let's say whatever list node this merge method will return we will simply add it to results head like this and we will simply do result do display so when we will merge this two sorted singly link list this head will actually hold that list and then here we are calling the display method to print the contents of the final list so if I run the code now so here you can see that the resultant list which we got is the combination of these two list and it is also sorted so 1 3 4 5 8 8 because we have 28 here then 9 14 18 so after this list got exhausted 8 9 14 and 18 were directly added here so friend this was all about that how we can merge to sorted singly link list here we have used the idea of dummy pointers which we have discussed in Greater detail in our previous video and using a tail we are adding one one node in this V loop after comparing A's data and B's data and at the end if any of the lists got exhausted we are simply appending the opposite list to Tails next and at the end we are returning dummy. next because this dummy we actually created to get a concrete object and all the notes were added just just after the dummy node so at the end we simply return dummy next so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem that how we can add two singly link list so let's move on and see what this problem is and how to solve this so here in this problem we are given with this two singly link list which are non empty so we have this two singly link list A and B they actually represent a number which is a positive number the digits are stored in reverse order and each of their notes contains a single digit so as this is a number each node in the list have a single digit and this complete number is stored in reverse order so if you want to know the number you have to read it from end so here the number is 3 4 3 so 3 4 3 for this list it would be 4 6 5 because they are stored in reverse order now our task is to we need to add these two numbers and return the sum as a link list like this so here you can see if we add this two numbers using a plain maths here you will get 8 4 and 6 will give 10 so 0 will will come here and 1 will be carried over 4 and 3 will give 7 7 + 1 8 so our answer would be 8 08 so we need to return return 808 which is the sum of these two numbers in the form of a singly link list here we are given that two numbers does not contain any leading zero so for example here we won't have something like this because those are leading zeros the zero can only come so here let's say if we are given a singly link like this so this is a valid singly link list because the complete number is zero so now let's move ahead and see the demonstration of this algorithm step by step so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here we are given this method add we pass to singly link list A and B like this now we need to do the sum of these two numbers and return the sum in the form of singly Link list only where each node will have only one digit so here you can see the numbers are stored in reverse order so the number we are trying to add is 9 4 7 because the number is stored in reverse order we are adding 65 to it like this so 7 + 5 will give 12 2 will come here 1 will be carried over here 6 + 4 will give 10 10 + 1 will be 11 so 1 will come here and another one will be carried over 9 + 1 will give 10 so our answer is 1012 so here this 1012 should be written in the form of a singly link list where each digit should be in the respective notes so for the result singly link list we have to first create a dummy list node which will have a dummy value 0 so friends in our previous videos we have discussed the idea of dummy list node that why we actually create this dummy list node it basically help us in avoiding the null pointer exceptions and also it actually provides a concrete object in the Heap or else what we need to do is we need to write some extra logic to just evaluate the first list node and then proceed from there on so in order to learn more about dummy list node you can watch my previous videos to it so here at the step one we will create a dummy list node so friends in this algorithm what we are trying to do is we will take one one single digit from both the list we will add them and whatever will be the sum that sum we will create a list node and add just after the dummy list node So currently dummy's next is pointing to null but after we do the sum of each node from both the list whatever there some will be we will create a list node and we will add to this dummy list so for that we are creating a tail list node like this it is referring to dummy list node we will use this tail to add the list node into this singly link list 1 by one so that stuff we will be seeing in the while loop moving ahead so here you can see that one list node can have only one digit so the maximum value this list node will have is from 0 to 9 and let's say if we are adding 7 + 5 so we'll get answer is 12 so we can only store one digit so usually when we do plane maths what we do is we store two here and one is carried over so this one we will be keeping track via carry so at the start carry is zero because we haven't started our addition so carry is zero now we'll provide a while loop where the condition are a is not equal to null or B is not equal to null so in this V Loop what we are doing is we are taking one one node from both the list and we will do their sum but there could be a chance that one list gets exhausted before the other and as we need to do the sum of this complete to singly link list the condition we provide is a should not be equal to null or B should not be equal to null so even if B is equal to null let's say B reached here and a reached here so B is equal to null but a is not equal to null so therefore this while loop will run one more time to take the sum of this this last digit and add that sum into our result list so even if one list is not empty this while loop will keep on running so at the start a is not equal to null and B is not equal to null so the condition in while loop comes out to be true now here what we are doing is even if one condition comes out to be true the while loop will execute so there could be a chance that a is not equal to null but B is equal to null or a is equal to n n but B is not equal to null so we need to take this value 7 + 5 but before taking those values we need to check whether A and B are actually pointing to null or not so here we have used a tary operator where we are checking whether a is not equal to null so if a is not equal to null we take A's value but if a is equal to null then we take the value at zero because zero won't affect the sum so this tary operator condition states that if a is not equal to null So currently a is not equal to null so we will take the value a do well which is 7 and that will be assigned to X like this similarly we have to take this value because we are adding the first digits so we are first checking whether B is equal to null or not so if B is not equal to null it means there is a digit we need to add so we are simply taking B do well which is five and that will be assigned to Y like this so here we have taken out the values in X and Y and now what we do is we do the sum so at the start we have a carry as zero so here carry is zero we are taking the first digit 7 which is X second digit 5 which is our Y and we are doing the sum of these three numbers so 0 + 7 + 5 will give 12 so sum will become 12 like this so friends here you can see we need to store this sum in such a way that only one digit can come in the list node and when we actually do the maths we get sum as 12 we put two here and we carry our one to the next digit so how we can perform this mathematical addition is we take the help of division and modulus operator so if we take sums 12 the maximum value each note can have its single digit so if you take sus 12 if you divide it by the first two-digit number which is 10 we'll get 1 and if we do 12 mod 10 this will give us remainder which is two so here you can see we can use this properties where we take the remainder like this which is our two and we can take the carry by dividing it by 10 so here we are first evaluating carry for the next addition so sum is 12 if we do divided by 10 carry will become one because we need to put two here and send one to the next addition and now as we are putting two here this property will help us in taking out two from the sum so we are doing sum mod 10 which will give us two and that two will be our single digit and we need to return this result in the form of a singly link list list so we will create this list node and we have to add it in the dummy list so we'll take the help of tail so to tail next which is null we'll create a list node provide a value as two and add it to Tails next so after executing this line tail next was pointing to null so now it will point to a list node having value as two which is our first value of the addition moving ahead now after putting two if it look into the digits the next digit will come one so that will come after this two so in the next iteration we will be using tail to put one so for that we have to move Tail to the next node so that we can still use this condition tail do next and add the new list node so after adding two we'll move the tail to its next node by assigning tail do next to tail so it would look something like this because in the next iteration we are doing the sum of the second digits and we will put after two using the Tails next so friends after we perform the sum of first two digits we need to move a to its next and B to its next to take the next two digits so for that we have to first check whether a or b are actually pointing to null or not so if a is not equal to null we can safely go towards this next by assigning a do next to a so at the first step it would look something like this a will now come towards next because a next is pointing to this node so now a will point to this node similarly we will move B to its next because B is also not equal to null so it would look something like this B next is this node so now B will point to this node I'll remove everything so here you can see a is not equal to null a is pointing to the second node B is not equal to null B is also pointing to the second node so the condition in while loop comes out to be true so first we will evaluate X we first check whether a is not equal to null so a is not equal to null so we simply do a do well it means we are taking this value out four and assign to X so X become four then we will evaluate whether B is equal to null or not so B is not equal to null so we will take B do well and assign to Y so we'll assign 6 to Y like this and we know that after the first addition the carry was one so we will do the sum of carry X and Y so here if you see 9 4 7 6 5 if you are adding it we get two and one is our carry 4 + 6 is 10 + 1 will give 11 so 1 will come here and 1 will be over carry 9 + 1 will give 10 0 will come here and one will be our carry so the addition will give 1 0 1 2 so we have done with the first addition which is two here 1 became our carry and X and Y are actually denoting 4 and 6 so we are doing Su of this three digits Now 1 + 4 + 6 so carry + x + y so sum will become 11 so if you look at the sum we can only store one digit and another one will be the carryover so first we will evaluate the carry for the next addition so 11 divided by 10 will give the value as 1 because when we will divide 11 by 10 we get value as 1 so our carry will become one and the digit we want to store here is will be given by the remainder so 11 mod 10 whatever value it gives here it is 1 so that will be stored here and how it can be stored we have to stored in the form of a list node so sum mod 10 will give the remainder as one so we will create this new list node and we will assign it to tailes next so Tails next is pointing to null so this will go away and one will come here which is this one moving ahead so now we have to move Tail to this node because when we will perform the Third Edition that node will come after this one so tail should go to this node so we will assign tail do next to tail so tail next is pointing to this node so now tail will come to this node via this assignment we are done with processing of second nodes so now we have to move a and b to its next node so first we will check whether a is equal to null or not so if a is not equal to null we can safely move to its next node by assigning a do next to a so a do next is this node so now a will come to this node B is not equal to null so we will assign B do next to B so B do next is pointing to null so now B will point to null so friends here you can see the singly link list B got exhausted and we have reached to the end of the singly link list but as we are performing the sum of this two singly link list we have to take the sum of this nine as well so here B is equal to null so this condition comes out to be false but a is not equal to null because there is one more node left so this condition comes out to be true and there is a or so therefore the condition in while loop comes comes out to be true a is not equal to null so we will take a do well which is 9 we will assign it to x x become 9 here you can see B is actually equal to null so we can't do B do well because this will give us null pointer exception because B is not pointing to null so therefore what we do is if B is not equal to null we take B do well if B is equal to null we take the value of y as zero this because when we will do sum of x + y + carry y will be zero and it won't affect the sum so here if we do 1 + 9 + 0 so it won't affect the sum so therefore we need to put this check that if B is equal to null we take the value of y as Z like this and now we will do sum of carry + x + y so carry was 1 x is 9 Y is 0 if we do their sum we get sum as 10 now we get the sum as 10 so we put zero here and one will be our carry over which is here so first we will evaluate the carry by doing 10 divided 10 so the answer will be 1 so carry will become one like this and then we have to take this value zero so if we do su mod 10 which is 10 mod 10 we get remainder as zero so this will become zero we will create a list node and we will add it to Tales next like this so via this assignment we are adding this new list node having value is zero this using T's next we will move tell to its next like this and here you can see see that with this addition we have used this value and this value so a is not equal to null we have to move to its next so a is not equal to null here we assign a do next to a so now a will point to [Music] null we check whether B is equal to null or not so actually B is equal to null so we don't perform this B do next to B Because B is already pointing to null so so now here you can see a is equal to null and B is equal to null so therefore both the condition in while loop comes out to be false because a is equal to null and B is equal to null so this V Loop will terminate so friends one thing to note here is we have simply done the sum of first three digits 2 1 and 0er but the actual addition result is 1012 so this one which was our carryover so we will check here whether carry is greater than Z or not so if carry is zero we do nothing but here value of carry is 1 which is greater than zero so we have to add one more node to Tails next to encounter for this carry also so currently carry is greater than zero we will create a list node by passing in the value as carry which is one and we are simply assigning it to Tails next so Tails next is pointing to null so now it will point to a node having Val is one which is the value of our carry so friends here you can see that we have done the sum of this two singly link list the digits were in reverse order so our sum is also in reverse order so 947 if we add to 65 so 9 4 7 if we add to 65 we get answer is 1 0 1 2 so here at the end end we simply return dummy. next because this dummy is pointing to a list node which actually we created so this is a dummy value so we'll simply return dummy. next which is a list starting from this list node so it would look something like this that we have dummy list like this and we are returning dummy. next so the method which called this add method will get like this this would be our answer 2 1 0 one so friends this was all about that how we can add to singly link list I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to represent W link list in Java so friends in my previous tutorials I discussed about singly link list so in this tutorial I will be discussing about W link list so friends when we discussed about singly link list so it was a one-way link list it had only two things one was the data and another was the pointer to next list node but if you see in W link list it is actually a two-way link list so if you see a w link list we have this list node which has basically three things one is the actual data which it holds and other is the next pointer so this next pointer points to the node which is just after it and it also has a previous pointer which points to a node just before it so this way it's a two-way link list so in W link list suppose if you are given any particular node then we can use that node to navigate the list in both forward and backward direction if you would have watched my previous tutorial on singly link list then we saw that we could only move in forward Direction in singly link list so it's not possible to move in backward Direction when we are using the singly link list but with W link list we can move forward and backward in the both Direction and one another difference between singly link list and dou Link list is like a node in singly link list can only be deleted if we have a pointer to its previous node but in W link list we can delete the note even if we don't have pointer to its previous noes so as you saw the singly linkl moves in forward Direction so in order to break any chain or any node in between the singly link list we usually need a pointer to its previous node to delete the node after it but in W link list as we have this two pointers which helps us in traversing forward and backward then we don't need any pointer to its previous node so friend W link list implement the the list node with a slight different way than singly link list so the list node and singly Link list had data and a pointer to the next list node but in W link list the list node has data a pointer to the next list node and a pointer to the previous list node so you can see this is how we represent a list node in W link list so if you want to represent a w link list then it's something like usually we have this head and tail pointers so the head points to the first node and the tail points to the last node so you can see each list node has data a pointer to its next node and the pointer to its previous node so usually the head points to the first node and its previous is is null and the tail points to the last node whose next pointer points to null so it's like a two-way link list where each node has one next and one previous so this is how the form is chain where each node refer to other node next to it and a node previous to it so the traversing becomes easier in forward and backward Direction so let's say suppose we have a pointer to this third node then if you want to Traverse to the forward then we can use this next pointer and Traverse forward and if suppose if you want to Traverse backwards then we can use this previous pointer to Traverse backwards so this is a basically advantage of w link list over singly link list so friends in this tutorial we discussed about how to represent a w link list in Java and in my next tutor I will be discussing the way to implement the W link list in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to implement W link list in Java so friends in my previous tutorial I discussed how to represent a w link list so here if you see a w link list is basically a head and a tail pointer so the head points to the first node and the tail points to the last node so we also discussed that list node has a next pointer which points to the node after it and has a previous pointer which points to the node just before it and we also discussed that a w link list is a two-way link list that is it we can Traverse the W link list in both forward and a backward Direction so a list node which is a next pointer and previous pointer help us in traversing in forward and backward Direction so this is a basically advantage of singly Link list we also saw that how to represent list node in W link list so a list node in singly link list had only data and a next pointer which points to the node after it but in W link list the list node has data a next pointer which points to the list Noe just after it and also a previous pointer which points to the list note just before it so friends let's go to eclipse and see how we can Implement a w link list so friends in my previous tutorials I discussed about singly link list so in this tutorial we will see how to implement a w link list in Java so here I have just created a class by name W link list so this class will hold the implementation for w link list so in order to implement a w link list we need list node class so we'll create an inner class by name list node so basically this list note class will hold the pointers to next and the previous notes so as we discuss in the slide that list note contains three things private int data so it contains data and this data can be any generic type as well but here I will be taking it as integer it holds a pointer to the next list node it also holds the pointer to its previous noes so the three things are data a pointer to the next node a pointer to the previous node we'll also create one Constructor so this Constructor we'll take the data part and we'll simply assign data to this. data so this is how we represent our list node and we also saw in the slide that W link list had a head pointer and a tail pointer so we'll create two instance variable of list node one is head and another one is tail so basically the head will hold the first note of the W link list and the tail will hold the last node of the W link list here we also create a integer variable by name length so this integer variable will hold the length of w link list so it will just return return the count of number of notes in the W link list so we'll also create one Constructor for w link list class so here we'll assign the values of these three instance variables so this do head equals senal this do tail n so basically when we initialize W link list the list is empty so the head and tail will point to null and length of the W link list is zero we'll also create one method by name is empty so this method will return as a Boolean value which will signify whether our W linkage is empty or not so we can simply return length so suppose the length of w link list is zero therefore the list is empty so it will return return true we can also return something like head is null so even if head is null then the list is empty so we can use either of the two statements we'll also create one more method which will return back as the length of w link list so friend this is how we represent a w link list in Java so in this tutorial I just created an inner class list node two methods is empty and length so in my upcoming tutorial we will discuss how we can insert the node and W link list and how we can delete the node and W link list so friends I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to print elements of a w link list in Java so let's say we are given a w link list having four notes say 1 10 15 and 25 and as you can see head points to the first node which is one and tail points to the last node which is 25 and each node in W link list has one next and one previous pointer so the next pointer points to the node just after it and previous pointer points to node just before it so friends in W link list we can Traverse the list in forward and as well as in backward Direction So Below is the algorithm to Traverse the W link list in forward Direction so let's see demo of it's working so first we'll create a list note by name Temp and we'll assign the value of head to it so as head points to First node now temp fill point to the first node moving ahead so friends the basic idea behind the algorithm is we have this temporary node so using this temporary node we'll visit each and every element of w link list and we'll print the data on the console so this while loop helps us in traversing the W link list and also printing the data so we'll Traverse this temporary list note till it becomes null So currently has 10 points to the first node and it's it's not null therefore the condition in while loop comes out to be true we'll print the data associated with this temporary node and then simply we'll move temporary node to its next node by assigning the temp. next value to Temp So currently you see temp points to First node at next point to the second node therefore we'll assign the temp. next value to Temp so it will look something like this moving ahead now it's temp points to Second node and it's not null therefore condition in while loop comes out to be true so we'll print the data associated with it and then we simply move temp to its next node by assigning temp. next value to Temp moving ahead now as the temp is pointing to third node and it's not null therefore condition in while loop comes out to be true so we'll simply print a data associated with this list node which is 15 and we'll simply Traverse the time to its next Noe by assigning time dot next value to Temp now your temp points to the fourth node and it's not null therefore condition in while loop comes out to be true we'll print the data associated with the fourth node which is 25 and we'll simply assign the value of temp. next to Temp so temp. next points to null so we'll assign null value through temp so it will look something like this now if you see 10 points to null therefore the condition in while loop comes out to be false and therefore the while loop breaks out now as we have reached the end of the list therefore we are simply printing the null so friend this was the algorithm to Traverse the W link list in forward Direction now let's see how we'll Traverse this W link list in backward Direction So Below is the algorithm to Traverse the W link list in backward Direction now we'll create a temporary node but this time it will point to the tail because we need to print the elements in backward Direction so now time points to the last node which is tail we will Traverse this temporary node till it becomes null now here we'll print the data associated with this temporary node which is 25 so in order to Traverse the W link list backward we will assign the value of temp previous nodes to Temp so it would look something like this moving ahead now as temp points to third node therefore it's not null so the condition in while loop comes out to be true we'll simply print the data associated with this temporary node and then we'll assign temp. previous value to time so we'll move one note backwards now as time points to the second note therefore it's not null so the condition in while loop comes out to be true we'll print the data associated with this temporary note which is 10 and we'll assign temp. previous value to Temp so we are traversing temp one step backwards so here temp points through first note which is not null therefore condition in while loop comes out to be true we'll print the data associated with this this temporary node which is one and then we'll simply asend temp previous value to Temp so it will look something like this so currently temp points to null therefore this condition in while loop comes out to be false and while loop breaks out so in the last St we'll print null because temp is currently pointing to null so friends this was the algorithm to Traverse the W link list backwards so let's move to eclipse and see the working code so friends in my previous tutorial I had created one class by named W link list and in this W link list I had created few instance variable one was pointing to the head of the link list and another was pointing to the the tail of the W link list I also created a integer variable which stored the length of the W link list and I also created one inner class which was actually list node class which had data a pointer to next node and a pointer to previous node so friends let's write a method which could print the W link list in forward Direction so Public public void display forward so here I have created method name is display forward so it will display the W link list in forward Direction so first we'll say if head is null then return return so here if suppose the head is null so so w link list is empty therefore we'll simply return moving ahead first we'll create a temporary node by name Temp and we'll assign the value of head to it then we'll create a while loop and we'll Traverse the temporary node in a loop till it becomes null so inside this V Loop we'll we'll print tam. data and we'll simply Traverse temp to its next node by assigning temp. next value to temp and at last we'll simply print null so friend this is the algorithm to Traverse the W link list in forward Direction so now we'll write a method to Traverse the W link list in backward Direction so let's create a method public so we'll give a condition as if if tail is null then simply return so here tail is null then we'll simply return from this method moving ahead we'll create a list node temp which will point to tail then we'll create a while loop and we'll Traverse this temp node till it becomes null so I'll just copy this complete part and here instead of traversing to the next node we just Traverse to previous node so friends this is the code to display the W link list in backward Direction so now let's see it's working so here in the main method I have created one method which inserts the node into W link list so this is the method we insert the node into W link list so this algorithm I will be covering in my next tutorial so for now just think that this method insert the node into W link list so currently I have inserted four nodes 1 10 15 25 so let's first print this W link list in forward Direction so I'll do dll do display forward and if I run the code so you can see it prints 1 10 15 25 and null so this is what it displays in forward Direction now let's display the W link list in backward Direction so we will call display backward and we'll run the code so here you see it simply prints the W link list in backward direction as 25 15 10 1 and then null so friends in this tutorial we simply discussed how to Traverse the W link list in forward and backward Direction and print the data in the notes on the console so friends I hope you like this video please like like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to insert node at the beginning of a w link list in Java so friends let's suppose we are given a w link list having four notes say 1 10 15 and 65 so here you see head points to the first note and tail points to the last node and if we want to insert a node at the beginning of w link list we usually manipulate the head pointer and in that case tail pointer doesn't play any much role the only case where tail points comes into picture when the list is empty so when the list is empty usually head and tail both points to null and when we want to insert and note at the beginning of w link list therefore after it insertion the W link list has only one node so therefore head and tail both points to that node so we need to consider that case so in the algorithm if you see if the list is empty then the tail pointer comes into picture so we'll see the demonstration of this algorithm in next slide so friends below is the algorithm to insert a node into a w link list at the beginning so let's see the demo of this algorithm So currently if you see then in W link list we have this head note and tail Noe so the head points to the first Noe and the tail points to the last note So currently the list is empty therefore head and tail points to null and let's say we want to insert a node having a value one so first we'll create a new node and we'll assign the value to it the new node variable will point to a node which has data as one and whose next and previous points to null moving ahead we'll check whether W link list is empty or Not So currently as head and tail points to null so list is empty therefore the condition in if statement comes out to be true and in order to insert this new node at the beginning of a w link list will'll first assign the value of new node to tail So currently tail points to null so after this statement it will point to the node to which the new node points so here if you see new node next points to null therefore we'll assign the value of head to new nodes next pointer so here head points to null therefore new node next will also point to null moving ahead and then we'll simply assign new notes value to head so as head points to null we'll Simply Now make it point to the new node so here as list was empty so after insertion of this new note both tail and head will point to it because this is the only note in the W link list now let's say we want to insert a node having a value 10 into a w link list having the first node as one so here first we'll create a new list node having the value as 10 so this would look something like this that new node points to a list node having the data as 10 now we'll check whether W link list is empty or Not So currently it's not empty because head and tail is is pointing to the list node having data as one therefore the condition in if block comes out to be false and the else part will be executed so as we want to insert this new note at the beginning of this W link list so in order to insert this new note into the beginning of w link list we will assign the value of new node to heads previous so if you see the head points to the node having value as one and it previous points to null therefore we'll simply break this pointer and we'll assign this previous pointer to the new node so it would look something like this so in the first step we assigned head previous to the new node and in order to make it a two-way link list or a w link list we need to assign new notes next to the head so here we assign the value of head to new notes next because in W link list the nodes refer to each other so the node which comes first refer to other through the next pointer and the node which comes after refer to first one through the previous pointer so here in the lse part we saw that head. previous refer to new note and here we saw that new notes next refer to now the head so moving ahead so in the last step we'll simply assign the value of new node to head so here currently head points to a list note having data as one but as we have inserted his new note into the beginning therefore now head should point to this new Noe so friend this was the algorithm to insert a node into the beginning of w link list so friends let's move to eclipse and see the working code so friends in my previous tutorial I created one class by name W link list head of type list note which points to the first node of a w link list and tail which points to the last node of a w link list and a length which which return us back the actual size of the W link list then we also created one inner class by name list node which had the data a pointer to next node and a pointer to the previous node and in my last tutorial I discussed how to print the elements of this W link list in forward and backward Direction so in this tutorial we will write the code to insert a node at the beginning of a w link list so public void insert first so this method takes in a integer value so this integer value will be a part of the new node which we want to insert into W link list so first we'll create a list node by name new node and we'll simply assign the value to it moving ahead we'll create a f block and here we'll provide a condition as is empty so here we are checking whether the W link list empty or Not So currently when we initialize the W link list head and tail points to null and the length is zero so is empty method returns us a Boolean value and checks whether the W link list is empty or not so if the W link list is empty then First Step we'll do is we assign new node value to tail and in the else part and if suppose the list is not empty then we'll assign the new noes value to heads previous so head previous and then we'll simply point the new noes next pointer to head and as the node is inserted now head will point to the new node so we'll simply assign the value of new node to head after we insert the note into the beginning of this W link list we'll simply increment the length by one now in main method let's run this code so first I have created and Stand Out w link list so initially head and tail points to null and length is zero so if I call insert first and I pass value as one and then I simply say display it forward and display it backward and so if I run the code node is inserted with a value of one and we have printed it both forward and backward so it prints out the same because head and tail points to the first node and if suppose I insert one more node as insert first and provide a value as 10 and now I run the code so you see initially there was one node having data is one so when we inserted the new node at the beginning of a w link list so now it printed out 10 and one in the forward Direction so you see that currently head is pointing to 10 and tail is pointing to one so friends in this tutorial we saw how to insert a node into a beginning of a w link list I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to insert node at the end of a w link list in Java so friends suppose we are given a w link list having four notes say 1 10 15 and 65 so usually in W link list head points to the first Noe and tail points to the last Noe so if you want to insert a note at the end of w link list usually we do the manipulation with the tail pointer and in that case head pointer doesn't play any much role the only case in which head pointer comes into picture is when the list is empty so if the list is empty then head and tail both points to null and after we insert a note at the end of w link list so the list contains only one node therefore the head and tail both needs to point to that particular node so here in this algorithm we need to cover that case when the list is empty so when the list is empty then head pointer comes into picture so we'll see the demonstration of this algorithm in next slide so friends below is the algorithm to insert a note at the end of a w link list so let's see a demo of this algorithm step by step so let's say currently the W link list is empty therefore head and tail both will be pointing to null and let's say we want to insert a list node into this W link list having a value of 1 one so in step one we'll first create a list node and we'll provide value to it so here if you see the new node will point to this list node having data as one and the pointers to next and previous node will point to null moving ahead then we'll provide F statement and and in this if we'll check whether the list is empty or Not So currently the list is empty because head and tail both are pointing to null therefore the condition in if block comes out to be true and this statement will be executed so as we want to insert this new node at the end of a w link list and currently this W link list is empty therefore when we'll insert this new note so this would be the only node in the W link list and we know that head points to the first node so therefore we'll assign new noes where value to head so you will see that now head points to new node moving ahead so as this W link is currently has one node and we also know that head points to the first node and tail points to the last node but this W link l has only one node therefore head and tail will point to this node so the last statement would be we need to assign new notes value to tail So currently tail is pointing to null and after this statement tail will point to this new node so friends after the insert of this list note at the end of The W link list we see head and tail both point to this node because this is the only node in the W link list now let's say we want to insert one more node having the value as 10 so this algorithm will be executed again in so in order to do that we need to First create a list node having the value as 10 so it would look something like this that new note points to a list note having the data s 10 and the next and previous pointers pointing to null moving ahead and in this if blog we'll check whether this W link list is empty or not so if you see head and tail points to this node having the data as one so list is not empty the before the condition in if block comes out to be false and the else part will be executed so in order to insert this new node at the end of The W link list we know that W link list has currently one node and if you want to insert this new node it would come just after this first node therefore in order to insert this new node into W link list first we need to point 10 next pointer to this new node and then we need to point new noes previous to tail node because the adjacent nodes and W link list refer each other so therefore in the first step what we do we assign new notes value to tell next So currently new note points to the note which we want to insert and tell. next points to null therefore when we assign new node value to tell next it would look something like this so now tell not next will point to this new node moving ahead and after this step we need to Point new noes previous to the tail node so in this step we'll assign the value of tail to new noes previous so it would look something like this so currently the adjacent notes and W link list are referring to each other such that the first node is pointing to the node which we wanted to insert and the node which we wanted to insert is referring it back so moving ahead so the final step is we need to assign new notes value to tell so if you see in a w link list the head points to the first note and the tail points to the last note so initially there was only one note therefore head and tail pointed to the same node but after the insertion of this new node tail should point to this new node so in order to do that we need to assign new noes value to tell and it would look something like this so friends this was the demonstration of inserting a list note at the end of w link list now let's go to eclipse and see the working code so friends in my previous tutorial I had created this W link list class and in the last tutorial we saw how to insert the note at the beginning of a w link list so in this tutorial we will code how to insert a note at the end of a w link list so for this first time I will create a method public void insert last and this method will take an integer value now in the first step we'll create this new node based on the value we are passing to the method and the first step will be we'll provide a if check that whether the list is empty or not and if the list is empty we need to assign new Noe value to the head so friends if the list is not empty then we need to insert his new node at the end of w link list so we know that the tail points to the last node in the w link list so in order to insert this node we need to use tell. next pointer and to tell. next will assign value of new node therefore the tell node next will point to Now new node and similarly to new node previous we will assign the value of tail so in the lse part we are doing this because this new node and the tail will refer each other and once they refer each other the new node is the part of w link list and finally in the last step we'll reassign tail to point this new node so it would be tail we'll now point to new node and at the last we'll increment the length of w link list by one so friend this is the code for inserting an list node at the end of w link list so let's test this method in the main method so here I have created one instance of w link list class now let's say I insert say one and then I print the W link list say in the forward Direction and if I run the program so you will see as the initially the W link was empty therefore when we inserted a new note it by default became in the first node and got inserted at the very beginning of w link list now let's say if I insert value 10 now when I run this program so when we'll print this W link list so this 10 should insert after the node having data is one so you see the 10 got inserted at the last position so so initially there was not having data as one but but when we inserted 10 it got inserted at the end of w link list so friends if suppose I insert one more node say having value is 15 and if I now run the program so you see the 15 got inserted at the end of w link list so initially there was node having data as one then we inserted 10 and then we inserted 15 so friends this was a tutorial to demonstrate how to insert a list node at the end of w link list I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to delete first node in a w link list in Java so friends let's suppose we are given a w link list having three notes say 1 10 15 and if you see below is the algorithm to delete the first node in a w link list so friends as you know that in W link list head points the first node and tail points to the last Noe so in order to delete the first note in the W link list we usually manipulate the head pointer and if you see as tail points the last node in a w link list therefore tail node doesn't play any much Ro in deletion of the first node but there is a case where tail nodes comes into picture when there is only a single node so if a w link list contains only one node then head and tail node both points to that particular node therefore the tail node comes into picture because we need to delete that particular single node so the only place sir tail node comes into picture when head is equal to tail that is the W link list has only one node and both head and tail points to it so we'll see the demonstration of this algorithm step by step so suppose we need to delete the first node so in the algorithm First Step would be we need to check whether the list is empty or not so if the list is empty it means there is no Noe to delete therefore we may throw no such element exception so if we take above example example then this W link list has three noes therefore the W link list is not empty so the condition in if statement comes out to be false so the first step would be we need to create a temporary node which will point to head as we want to delete the first node then we will create a temporary node which will point to the Head moving ahead now we'll check whether head is equal to tail or Not So currently head points to the first node and the tail points to the third node therefore they are not equal so the condition comes out to be false and the F part will be executed so friends we need to remove this first node now so in order to delete this first note from the W link list we need to do two things first first we need to break this next pointer which which is pointed by the temporary node so if you see temp next points to the second node so we need to remove this and if you see second note points back to Temporary note and we need to break this link so these two links we need to break so in the L part we'll first break the link which is pointed by the second Noe to the temporary note so in order to break this link We knowed head points with first note which we want to remove and its next points to the second note so here what we'll do we'll say head. next so when we do head. next we reach to the second node and and if we do do previous then this is the link So currently this previous points to the first node and when we assign null so this link breaks up so so it would be something like this so what we are doing in this line is we are traversing from head to its next and then to its previous so from head we Traverse to the next node and then we Travers back to previous so we broke this link here and we assigned a null value to it so we removed one link moving ahead so friends now we know the temporary notes points to head which is the first note which we want to delete therefore when the first node is removed head will be pointing to the second node because after its removal second node will become our new head therefore we need to Traverse this head to its next note so to head will assign the value of head do next So currently head points to the node which we want to delete and head next point to the second node and once this node is removed we know that now head will point to the second node because second node becomes the head of the W link list so in order to do that we need to Traverse head to its next position by assigning head. next value to head so it would look something like this moving ahead and we know that temporary note refers to Second node so we need to break this link as well so to break this link we'll simply do temp. next equals null so temp do next point to Second node and we'll assign a null value to it so it would look something like this so now as you see temporary node is an individual node where previous points n and next points to null so so in the last step we simply return the temp because this is the first node which we deleted so friends now w link list contains two nodes where head points to the first node and tail points to the second node now suppose if you again call this algorithm to delete the first note then it would be something like first we will check whether list is empty so list is not empty so friends we'll create one temporary variable which will point to head and as we know that head points the first node of a w link list therefore in order to delete this first node we'll point the temporary node to the Head moving ahead we'll check whether head is equal to tail or not so head is not equal to tail because head point to First node tail points to the second node so the else part will be executed now here we'll do the same thing we'll first break this previous link which is pointed by the second node to the first node so in order to reach this Noe we'll use head. next and to assign null value to previous we'll use head. next. previous so when we'll do head. next we reach here and when we'll do previous this is the link and we'll assign a null value to it so it would look something like this now we have removed one link moving ahead and now we'll simply Traverse head to its next note now once this node is removed we know that head should point to the next node in the W link list because because now that node will become our new head so we'll simply Traverse head to next position by assigning head. next value to head moving ahead and we'll simply assign a null value to temp. next because we need to remove this link as well so so now temp. next points to null and in the last step we simply return return the deleted Noe so friends now you see W link list has only one node where head and tail both points should at particular node so when we will call this below algorithm again to delete the first node then first it will be checked that whether the list is empty or Not So currently list has one node therefore it's not empty then we'll create a temporary node which will be pointing to head because head points to the first node in the W link list moving ahead we will check whether head is equal to tail or Not So currently if you see head and tail both points to that particular node therefore they are equal so the condition in if statement comes out to be true therefore if blog will be executed so friend this is the only node left in the W link list and we want to remove that therefore we need to remove this both pointers head and tail because they are referring to this node so in the first step we'll assign a null value to tail so it would look something like this so now tail would be pointing to null and then we'll simply assign head do next value to head so it simply means we are assigning null value to head so now head will be pointing to null and we'll simply assign null value to temp. next but if you see 10. next is pointing to null value only therefore we just simply return the temporary node in the last step so friends you saw there was only one node remaining and we removed that node as well now if you see tail and head both points to null so if we call this algorithm again so it will be checked whether list is empty or not not so if you see head and tail both points to null therefore the W link list is empty therefore if you call this algorithm then an exception will be thrown so we can throw an exception saying that there is no such element left so friends this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial I created one class by name W link list and we implemented the W link list into that class so this class has basically an head node and a tail node and an integer variable by name length which stores the size of the W link list you can watch my previous tutorials to understand those Concepts so in this tutorial we'll just code a method which will delete the first node in a w link list so I'll create a method as public list node delete first now this method will return us back the deleted node so the return type is list node so first we'll provide a if check and in if blog will provide a condition as whether W link list is empty or not so if W link list is empty we'll throw an except moving ahead then we'll create a list node by name temp and we'll assign a value of head to it as head points to the first node of w link list therefore we'll assign value of head to this temporary node and then we'll check if if head is equal to tail or not so when head is equal to tail it means w link list has only one node so in that case we'll assign null to tail because we need to break the reference of tail pointing to that particular node which we want to delete and if head is not equal to tail then in else blog will write head. next. previous and we'll assign a null value to it we are assigning a null value to head. next. previous because we need to break the previous link which is coming from the second node and then we'll simply assign head. next value to head now we also need to break the next link which temporary node is pointing to the second node therefore we'll do temp. next and assign a null value to it and finally this temporary node is removed therefore therefore we know that size of length is reduced by one therefore we'll do length so here we are decrementing the length by one because we have removed one node and in the last St will simply return the temporary node because this temporary node is pointing to the first node of w link list so friend this is the algorithm to remove the first node in a w link list now let's test it's working so friends in my previous tutorial we saw how to insert the notes in W link list so here I have added three notes by data as 1 10 and 15 and if I print the W link list in the forward Direction so you can see 1 points to 10 10 points to 15 and 15 points to null so totally there are three notes now let's delete the first node in the W link list so we'll call delete first and let's display the W link list again so I'll will call display forward and if I run the code so you'll see initially W link list had nodes as 1 10 and 15 and the node having data as one was the first node so when we call delete first the node at first place got removed and the W link list became 1015 now let's say I again call delete first and if I run the program so you see when delete first was called first time one was removed and when we call delete first again so 10 was remoted because 10 became our new head and finally if I call delete first again and I run the program so you see all the notes are removed and nothing got printed because because in display forward we have kept a condition if head is null then simply return return so when all the three nodes got removed had pointed to null and nothing was printed but if I call delete first again as head and tail both are pointing to null and if I call delete first again so you can see we are getting an exception as no such element exception because list is empty and there is no element left to be removed so friends this was the tutorial to remove the first node in a w link list I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to delete last node in a w link list in Java so friend let's suppose we are given a w link list having three notes with data is 1 10 and 15 so here you see below is the algorithm to delete the last node in a w link list so friends the basic idea behind this algorithm is as we want to delete the last node in a w link list we will use basically this tail pointer to remove the last node in the W link list because in the W link list head points to the first node and the tail points to the last node and we want to remove the last node in the W link list therefore we'll manipulate and play with this tail pointer to remove the last note from the W link list so head pointer doesn't play much role in deleting the last note from a w link list the only case where head pointer comes into picture is when there is only one node in a w link list because if there is only one node in a w link list then head and tail both will point to that particular node and if you want to remove that single node from the W link list we need to manipulate head pointer as well so friends let's see the demonstration of this algorithm so in the first step we will check whether the list W link list is empty or not so if W link list is empty we'll throw an exception saying that there are no more elements left to be removed So currently W link list has three notes therefore the list is not empty so the condition in if block comes out to be false now as you want to remove the last node from a w link list will create one temporary Noe which will be pointing to the tail so now temp points to tail because when we remove the last node from a w link list it will be removed using this temporary node moving ahead so here in the blog we'll check whether head is equal to tail or Not So currently head points the first node and tail points the third node therefore they are not equal so the condition comes out to be false and the lse part will be executed now friends in order to remove this last node from W link list we need to remove this two pointers because once we remove this two pointers this this node will be freed and it will be removed from the W link list so first we'll remove this next pointer because this last node is being referred by the second last note so we need to remove this link so in order to remove this link we need to Traverse to the second last node and then assign a null value to its next node so in order to Traverse to the second last note we'll use this tail pointer we'll first go to its previous by calling tail. previous and then to its next we'll assign a value of null so in this line what we are doing we are assigning a null value to tail. previous do nextt so it simply means we are first traversing to the previous and to the next we are assigning the value as null so it would look something like this so this link will be removed and then it will point to the null value moving ahead so friends once we remove this last node of a w link list we see tail points to that node so after its removal tail should point to the second last node because that second last last node upon removal becomes the last node of the W link list therefore we need to Traverse tail to its second last Noe so we'll simply assign tail do previous value to tail so it would look something like this moving ahead and then we'll simply break this link and we'll assign a null value to it so we know that temporary node is pointing to this last node and we need to assign a null to its previous therefore we'll simply assign a null value to Temp previous so it would look something like this so in the final step we know that the last node which is pointed by temporary node has been removed from W link list we'll simply return this temporary node so friends after removal of this last note only two notes are left so head is pointing to the first note and tail is pointing to the last node now if you want to again remove the last node from this W link list we call this algorithm again we check whether list is empty or not so list is not empty and as you want to remove this last node we'll create one temporary node and we'll assign the value of tail to it moving ahead we will check whether head is equal to tail or not so head is not equal to tail because head points to First node and tail is pointing to the second node therefore the lse part will be executed and in the lse part we'll do the same as we need to remove this link so we will Traverse a node back and we'll assign a null value to its next so we'll simply do tail. previous do next and assign a null value to it so tail points to the second Noe and when we do tail. previous we are reaching to the first node and then to its next we are assigning the null value so it would look something like this so the link which was referring to this note we have removed it moving ahead and as as we know that this is the last node of the W link list because once the last node is remove moved the tail should point to its previous node because that becomes the last node in the W link list therefore we'll simply assign tail do previous to tail so it would look something like this so now head and tail both are pointing to the first node moving ahead and we need to break this link and that link is referred by temps previous so we'll simply assign null value to temp M previous so it would look something like this so as we know that this node is freed therefore we'll simply return this temporary node so friends now in W link list only one node is left where head and tail both are pointing to that particular node so let's call this algorithm again so first we will check whether list is empty or not so list has node therefore it's not empty then as we know that there is only one node left and we want to delete the last node therefore this is the only node that needs to be removed so we'll simply create one temporary node and we'll assign the value of tail to it moving ahead now here is the case where head is equal to tail because both are pointing to this first node therefore in order to remove this node we need to break this both links because head is pointing to this node and tail is also pointing to this node and we need to break this both link so that this node can become free to be removed so in the If part we'll simply assign a null value to head so we have removed one link moving ahead and then we'll simply Traverse tail to its previous node by assigning tail previous to tail so you see tail previous is pointing to null therefore we are simply assigning a null value to tail so it would look something like this so now tail will point to null and now we'll simply assign a null value to Temp previous so you see temp previous is already pointing to null therefore we do nothing and simply in the last St we'll return this temporary note so you see now head and tail both are pointing to null and there are no notes left in the list therefore the list is empty so if you call this algorithm again then First Step will check whether list is empty or not so we know that list is empty and there are no notes left to be removed therefore we can therefore we can throw and no such element exception because there are no notes left to be removed so friends this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial I had created one class by name W link list and we implemented a w link list into that class so this class is head and a tail node and it also has a integer variable by name length which stores the size of the W link list so if you want to understand the working of w link list you can watch my previous tutorials so in this tutorial we will discuss how to delete the last node of a w link list so first I will create the method as public list node delete last so this method will remove the last element and will simply return it back therefore the return type is of list node so first we'll provide a if check as if the W link list is empty or not so if it is empty then we'll simply throw a exception say no such Element no such element exception moving ahead we'll create a list node by name temp and we'll assign a value of tail to it because we need to remove the last node from the W link list therefore we are using this tail pointer to remove that last node then we'll provide an if check if head is equals tail then we'll simply assign null value to head because when head is equal to tail there is only one node left in the W link list so we need to break both the reference head and tail in order to free that node so we'll simply assign a null value to head and in the else part we'll do tail dot previous do next and assign null value to it moving ahead then we'll simply Traverse tail to its previous node because once the last node is removed now tail will point to the node just before it and we'll assign null to temp. previous because we need to break that link as well and finally as we delete this note we need to reduce the length of W link list by one therefore we decrement the length by one and last we'll simply return the temp so friends we saw the algorithm to remove the last node of a w link list now let's test this working in main method so in my previous tutorial we just discussed how to remove the first node of a w link list so here I will just call delete last so here if you see we have inserted three nodes by data is 1 10 and 15 and first we are removing the last node so if I run the code you see first it printed 1 10 15 and null so when we call delete last so it printed 1 10 and 15 got removed and if I call this method again and then I run the program so you see we called delete last two times so in the first time 15 got removed and the second time 10 got removed and if I call it again so if I called it again so one was also removed and nothing got printed because in display forward we have kept in condition that if head is null then simply return and we know that we inserted three notes and we removed three notes so list got empty and head pointed to null therefore display forward printed nothing and if I call delete last one more time then as we know that list is empty and there are no notes left to be removed therefore you see an except was thrown because because there was no node left to be removed so friends in this tutorial we discussed how to remove the last node of a w link list I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to represent a circular singly link list in Java so friends what is a circular singly link list so if you see this is how we represent singly link list and this is how we represent a circular singly link list so the structure wise circular singly link list is very much similar to singly link list and here you can see in singly link list we have this notes which form a chain and we keep a head note which points to the first note and the last note next point to the null so the only difference between singly link list and circular singly link list is that in circular singly link list the last note points to the first note and not null so here if you see in singly link list the last node next is pointing to null but in circular singly link list the last no next is pointing to the first note again and not null so therefore this property makes circular singly link list circular in nature where if you see 1 points to 8 8 points to 10 10 points to 16 and 16 again points to 1 so therefore it's a circular in nature and one more difference is like in singly Ling list we keep the track of the head node which is pointing to the first node but in circular singly Ling list we keep the track of the last node so in cular singly Ling list we keep the track of the last note because it helps us in insertion and deletion of the notes in constant time so here if you see as head points to the first node and suppose if you want to insert a node in a singly link list at the end so we need to Traverse each and every node in the singly link list to reach the last node and then add the particular node but here in circular singly englist we are keeping the track of the last node and if if suppose we want to insert a note at the end so we can directly use this last pointer and add the note at the end and suppose if you want to insert a node at the beginning then we know that as circular singly link is is circular in nature therefore when we do last. next we reach to the first node so we can directly add node at the beginning in constant time so friend this is how we represent a circular singly link list where we keep the track of the last node and last node next part points to the first node so friends let's see a demonstration of circular singly link list below you can see that circular singly link list has three nodes having data is 1 8 and 10 and the node having data is 10 has been referred by the last node and you can see it's a last node in a circular singly link list where its next is pointing to the first node so let's see a small demo how we can create this circular singly link list so suppose we initialize a circular singly link list so we know that the list is empty so therefore the last will point to null so when the list is empty the last node is pointing to null now let's suppose we are inserting this node having the data as one so it's a simple node having data as one and next is pointing to null so if you want to insert this node into the circular singly link list and as the list is empty we'll simply assign the value of temp into last so that last points to this node so it would look something like this so now the last node is pointing to the node having data as one and we also know that circular singly link list has property that last next points to the first node of a circular singly link list but here if you see there is only one node so basically this node is the last node of a circular singly link list and also the first node so last NE should Point through this node only so it would look something like this so when we insert a node into a empty circular singly link list last points to that particular node and and its next points to the node itself now let's suppose you want to add one more node having data as eight so here you can see the temp is pointing to this node having data as it and it next is pointing to null so in order to insert this node into the circular singly link list having data as one and last is pointing to one so what we do is when we insert this node with a value eight we know that its next should point to the first node so therefore what we do is we simply break this link and we point pointed to the first node so it would look something like this as temp next is pointing to the first node and here if you see the first node is pointing to the second node therefore we need to break this link and we need to point it to the second node so it would look something like this so now you can see that node one is pointing to node 8 and node 8 is again pointing in to node one so they are circular in nature and one last step we need to do is as we have inserted is node 8 and we know that this is the last note therefore we'll simply assign the value of temp to last so it would look something like this so after the insertion of node having data as it the circular singly link list looks like this where node having data as it is pointed by the last node and its next points to the the first node therefore it's maintain a circular property and let's suppose we want to add one more node having data as 10 so here if you see the node next is pointing to this first node so in the first step what we'll do we'll simply remove this link and we'll point it to the first node so it would look something like this so now temp next is pointing to the first node and here you can see that second node is pointing to the third node so but here second node is pointing to the first node so we need to Simply break this link and we need to point it to the third node so it would look something like this and one last step we need to do is when we have inserted this node having data as 10 we know this is the last note therefore we simply need to refer the value of temp to the last so it would look something like this so friends here if you see we inserted three nodes and we knew that node one is the first node and node having data as 10 is the last node and here the last Noe is pointing back to this first note so therefore we saw how circular singly link list is created and and how they maintain a circular property so friends in this tutorial we discuss how we can replace present a circular singly link list in Java in my next tutorial we will see how we can Implement circular singly link list in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to implement a circular singly link list in Java so friends in my previous tutorial we discussed how we can represent a circular singly link list we discussed that it's very similar to singly link list with a slight difference that in singly link list the last note points to null but in circular singly link list the last node points to the first node which makes this data structure circular in nature we also discussed that we use head note to keep the track of singly linklist but in circular sing link list we usually keep the track of the last node so friends in my previous tutorial we discussed about the circular singly link list representation so in this tutorial we will discuss how we can Implement a circular singly link list in Java so let's go to eclipse and see the working code so friends in order to implement a circular singly link list I have created one class by name circular singly link list so in this class we will write the code for circular singly link list implementation now here we'll first create few instance variable so private so here we have created an instance variable of type list node by name last so this list node will help us in keeping the track of the last node of a circular singly link list we will also create one more instance variable so here we have created an integer variable by name length so this length variable will hold the size of this circular singly link list and inside this circular singly link list we'll create a private class of list node so as this is this is very similar to singly link list which we saw in our previous slide so I will just code what's required in list node so private list no next so here list note contains the data part and a reference to the next list node we'll create one Constructor now this Constructor will take the data part moving ahead we'll create a Constructor for this circular singly link list class so friends when we initialize circular singly link list we know that last points to null and as the list is empty therefore length would be zero so here we also create one more method public int length so when we call this method it should return us back the side of circular singly link list so we simply return length we'll also create one Boolean method by name is empty now this method will return us back whether the circular singly link list is empty or not so we'll simply return that when length is zero then return true and when length is not zero then simply return false so let's say in our main method I create the instance of circular singly link list so friends here we will write one more method which can create the circular singly link list so we'll simply create one method as public void create circular linked list so here we'll first create few notes say first let's I give data as one I'll copy this let's say I give data as 5 10 15 and I will change the name as second third so friends we have created this four notes now we'll interconnect them so first should point to Second so we'll do first do next and assign a value of second to it and similarly second dot next and assign a value of third to it and similarly third dot next and assign a value of fourth to it now friends here you see first points to second second points to Third and third points to Fourth but fourth is pointing to null therefore in order to make this link list circular we'll simply do fourth do next and assign first to it so therefore now fourth node will point to First node again so it will make it in circular in nature and in last what we'll do the instance variable which which we created last it should point to the last node therefore we'll assign the value of fourth to last so friend this is how we represent a circular singly link list in Java and if you if you want to call this method we can simply do CS l. create so this will create a circular singly link list of four nodes where first will point to second second will point to Third third will point to Fourth and fourth will again point to First and we can track those changes using the last list node so friend this is how we Implement a circular singly link list in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to Traverse and print a circular singly link list in Java so friends in my previous tutorial we discussed how we can represent a circular singly link list and we also saw how we can implement the circular singly link list in Java so in this tutorial we will discuss how we can Traverse and print the elements of a circular singly link list in Java so here you see below is the algorithm to Travers the the circular singly link list and print the elements data so here let's see an example when the circular singly link list is completely empty and last is pointing to null so friends we know that when the circular singly link list is empty therefore there are no elements and last will point to null so here when the last points to null we know that there are no notes inside the circular singly linked list to Traverse therefore we are keeping one condition as when the last points to null then simply return so here we know that last is pointing to null so we will simply return from it so friends let's see the demonstration of the algorithm with a circular singly link list having four notes say 1 8 10 and 16 where 16 is the last node and its next is pointing to this first node now let's see how we can Traverse each element inside this circular singly link list and print the data with the respective node so here first we'll check whether last is null or not so as last is pointing to this fourth Noe therefore it's not null so the condition in if blog comes out to be false so we move ahead now friends as we know that we are keeping the track of this last node which is the fourth node and suppose if we want to Traverse each and every node and and print the data so we need to start with the first node and then we can print the data accordingly but as here we are only keeping the track of the last node so therefore in order to reach this first node we know that the last node next points to the first node and we need to travel circular singly link list from the first to the last node so therefore we'll create this first node and we'll assign the the value of last dot next to it so it would look something like this moving ahead so friends we know that circular singly link list is basically circular in nature where first note points to second second points to third third points to Fourth and fourth points to the first again so we need to provide a while loop to Traverse each and every node and we need to take a special care while placing the condition in file Loop because if we place some wrong condition then we know that as it is circular in nature therefore this file Loop may enter into an infinite Loop so here as we want to Traverse each and every node and and print the data into the respective node so we'll Traverse till we have reached the last node so the condition in value we'll put as we'll iterate till first is not equal to last because when first is equal to last we know that we have Traverse each and every node So currently first is pointing to this first node and last is pointing to this fourth node therefore first is not equal to last so the condition in while loop comes out to be true so in the first step we'll simply print the data associated with this first node moving ahead so friends as we have traversed this Noe now we need to just move to its next node so in order to move this first node to its next we'll simply assign the value of first. next to first so here if you see first is pointing to this first node and its next is pointing to the second node therefore we are simply assigning the value of first. next to first so it would look something like this so it simply traverses first to its next position by this statement moving ahead now again first is not equal to last therefore condition in while loop comes out to be true so we'll simply print the data associated with the first node moving ahead now as we have traversed the second note so we'll move to the next note so in order to move this first to its next we'll simply assign first. next value to First so first do next points to the third note so after this statement it would look something like this moving ahead now again first is not equal to last therefore the condition in y Loop comes out to be true so in First Step we'll simply print a data associated with this third node and in the Second Step we'll simply Traverse first to its next by assigning first. next value to first so it would look something like this moving ahead so friends now here you see first and last both are pointing to this fourth note the therefore first is equal to last so the condition in while loop comes out to be false so therefore the while loop breaks out so friends here you can see that we had this pointer to this last node and we started traversing and printing of the elements from the first note so here if you see the circular singly link has four nodes and we have Traverse three notes by printing 1 8 and 10 and then in the while loop when we Traverse to the last node we know that condition in while loop came out to be false as first is equal to last therefore we have reached to this node but we haven't printed the data for this last element so therefore in the last step we simply print the data associated with this fourth note so when we print the data associated with fourth note we are sure that we have traversed all the notes and we have print the data associated with the respective nodes so friends we saw that demonstration of the algorithm now let's move to eclipse and see the working of the code so friends in my previous tutorial I created one class by name circular singly link list and we saw the implementation of circular singly link list in that tutorial we basically created few instance variable by name length and last so this last node was used to keep the track of the last node in circular singly link list we also saw how we can create a circular singly link list and we added this four notes 1 5 10 and 15 and we made this link list circular by assigning this fourth note again to the first so friends in this tutorial we will write the code to Traverse and print the elements of a circular singly link list so we'll create a method as public void we give the name as display so this method will simply Traverse each and every element in a circular singly link list and print the data with the respective node so here first we'll provide a condition as if last equals null so it means that if circular singly link list is empty or not so if circular singly link list is empty then we'll simply return and do nothing moving ahead we'll create a list node by name first and we'll assign the value of last do next to it so this thing we are doing because we need to Traverse the circular singly link list from first position to the last position and we know that last do next points to first so we are simply creating a list node by name first and we are assign the value of last dot next to it and then we'll create a while loop so inside this V Loop we will Traverse each and every node of circular singly link list using this first node so the condition we provide in while loop is we will Traverse this first till it becomes last and in the while loop we'll simply first print the data associated with the first node and in The Next Step we'll simply Traverse first to its next node by assigning first. next value to first so here in this V Loop what we are doing is we are printing the data associated with the first node and then we are simply traversing first to its next node by assigning first do next value to first so when we are reaching to the last note we need to print the data associated with the last node as well so we'll simply print first. data now in main method let's see the demonstration of this display method so here first we'll create the instance of circular singly link list and then we'll create the circular singly link list by calling create circular link list method so in this method we are simply creating four notes where first is pointing to second second is pointing to Third and third is pointing to Fourth and as fourth is the last note therefore fourth will Point again back to the first node and in the last step we are simply assigning the value of four to last because we are holding this circular singly link list through this last instance variable now let's say we are calling this display method and if I run the code so friends here you see it prints 1 5 10 15 which are actually the four notes in our circular singly link list so friends in this tutorial we discussed how we can Traverse a circular singly link list and print the data associated with respect to nodes I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to insert note at the beginning of a circular singly link list in Java so friends in my previous tutorial we discussed about circular singly link list so here if you see below is the algorithm to insert a node at the beginning of a circular singly link list so here if you see when the circular singly link list is empty the last note points to null because there are no notes inside the circular singly link list and you see the length is zero so friends let's see the demonstration of this algorithm let's suppose we want to insert a node at the beginning of a circular singly link list so in the first step what we are doing is we are creating a list node by name Temp and we are passing in the data which we actually want to insert so it looks something like this so your temp variable is pointing to this list node having data as one and whose next is pointing to null moving ahead now in the second statement we usually check whether this circular singly link list is empty or not so we provide a condition that whether last is equal to null or not so here if you see last is pointing to null therefore the circular singly linkage is empty so the condition comes out to be true so in order to insert this temporary node into the circular singly link list at the beginning the first step we do is we assign the value of temp to last so it looks something like this and after this step Temp and last both point to this particular node as this circular singly link l is empty and we want to insert this node at the beginning so when we insert this particular node we know that the circular singly link list has only one node the last node points to that particular node so therefore we have assigned the value of time to last moving ahead now after the F block what we do is we simply assign the value of temp to last. next now why we are doing this step is because here we know that we are basically inserting a node at the beginning of a circular singly link list and we also know that circular singly link list has property that the last node usually refers to the first node and as we are inserting a node at the beginning we know that the last neck should point to this particular node and here if you see when we are inserting a node into an empty circular singly link list we know that after an insertion there is only one note which is the first and the last note both and we want to make make the last do next point to First note so in order to do that what we are doing is we are assigning last do next value to the node itself and here we know that temp is pointing to this particular node so it looks something like this so this link is gone and then it will refer to itself because temp is pointing to this node only so after this step last next will point to the node itself and here if you see it is also fulfilling the property of circular singly link list as last node is pointing to the first node and since this is the only dode in the circular singly link list therefore last node and the first node is the node itself therefore here it is referring to itself moving ahead so after we insert the note into circular singly link list we usually increment the length by one because we know that now circular singly link list has size one so now the value stored in the length will be one so when the method gets executed circular singly link list looks like this so friends let's insert one more note into the circular singly link list having the length as one so usually in the first step we create this temporary list note having the data which we want to pass so let's say we are taking a node having data as it and the temporary node is pointing to it and its next is pointing to null so this node we want to insert at the beginning of this circular singly link list therefore we need to insert the node just before the node having the data as one so let's see the demonstration step by step so in the first step we usually check whe whether the circular singly link is empty or not so we make an if check that whether last is pointing to null or not so here last is pointing to this note therefore the circular singly link list is not empty so the condition comes out to be false so therefore the lse block will be executed so in the lse block what we do is we assign the value of last dot next to temp. next so here if you see last. next is point to the node itself and temp do next is pointing to null so why we are doing this step is because we want to insert the node at the beginning so therefore this node should come just before this so when this node will be inserted this would be the first node and this would be the last node and as this would be the first node its neck should point to this node so in order to do that we need to break this link and we need to assign this link to last. next so so here if you see last do next is pointing to the last node itself and we want to insert this note just before this therefore we need to assign the value of last. next to temp. next so it looks something like this so now temp. next is pointing to last. next moving ahead and then what we do is we simply assign the value of temp to last. next so friends in this step what we are doing is once we insert this node this node would be the part of circular singly link list and this would be the first node and we also know that circular singly link list is property that last node will always point to the first node therefore last next should point to this node because that is the circular singly link list property so in order to do that we are simp simply assigning the value of temp to last. next so it would look something like this and as we want to insert this node at the beginning of a circular singly link list we know that last. next should point to this node because after insertion this node will become our first node we increment the length by one so after the method executed we know that circular singly linklist has two nodes and length is two now friends let's suppose we want to insert one more node so in the first step we'll create the list node by name temp so here it would look something like this the temp is pointing to the node having data as 10 and its next is pointing to null now this node we want to insert at the beginning therefore we know that this node should come come just before it and once this node is inserted this node will become our first node so let's see the demonstration of algorithm so first we'll check whether list is empty or not so as last is pointing to the node having data is one therefore the list is not empty so in the lse block we are simply assigning value of last do next to Temp next so friends as we want to insert this temporary node at the beginning of a circular singly link list and the first node is having the data as eight therefore when we want to insert this temporary note just before that then we need to make this pointer point to this particular node and in order to reach this particular node we know that we are keeping the track of the last node and when we do last do next we are reaching to the first node therefore we are simply assigning the value of last. next to Temp next so it would look something like this now your temp. next is pointing to the first note of a circular singly link list moving ahead and the last step we do is as we want to insert this temporary node so once this node is inserted we know that this would become our first node and we know that circular singly link list has property that last node next should point to the first first note therefore here we are simply assigning the value of temp to last. next so it would look something like this and the final step we are incrementing the length by one currently the circular singly link has three nodes where first node has data is 10 second node has data is 8 and the last node is data is one and last next is pointing to the first node so after the method get executed the circular singly link list looks like this so friends here we inserted three notes having data is 1 8 and 10 at the beginning of a circular singly link list now let's go to eclipse and see the working code so friends in my previous tutorial we discussed about circular singly link list and its implementation we created one class by name circular singly link list so in this tutorial we will write a method which will insert the node at the beginning of a circular singly link list so let's say I give the name of method as public void insert first so here I have created one method by name insert first so this this method we'll take the data part which is of integer type so in the first step we'll create a list node by name temp and here we pass the data into the Constructor so therefore in this step we are simply creating a list node of the data which we have passed into the method now in the next step we are Prov providing a if check that last is equal to null or not so if the circular singly link list is empty therefore in the if statement we are simply assigning the value of temp to last so last equals temp moving ahead and if the circular singly link list is not empty then we are simply assigning value of last. next to temp. next and after the if else block we are assigning the value of temp to last. next so last do next equals temp and then we are simply incrementing the size of circular link list by one so friend this is the code for insertion of a node into the beginning of a circular singly link list so here we first create the list node then we check whether the list is empty or not so if the circular singly link is empty then we simply assign the value of this temporary note to last and if the circular singly link is not empty then we simply assign the value of last. next to temp. next which we saw in the slide and the last step we usually assign the value of temp to last. next and then we increment the length by one now in the main method Let's test the working of this insert first method so in my previous tutorial in the main method we created the instance of circular singly link list and let's say using that instance we call insert first and we provide the data as 10 and finally we call the display method so if I run the code so you see it printed value as 10 now let's say I call this method again and provide data as 15 and if I run the program so you see it printed 15 and then 10 so here when the circular singly link list was empty we called insert first and pass value as 10 so the node having data is 10 was the only node into the circular single link list and when we inserted 15 so here we are inserting 15 at the beginning of a circular singly link list so this circular singly link list had only node having data is 10 so when we inserted 15 it got inserted just before the node having data is 10 so if you want to insert one more node say of data 25 so this 25 will be inserted just before the node having data is 15 so if I run the code so you see it printed 25 15 and then 10 so friends in this tutorial we discussed how to insert a node at the beginning of a circular singly link list in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to insert node at the end of a circular singly link list in Java so friends let's suppose we are given an empty circular singly link list so when the circular singly link is empty we know that the last node points to null and in order to understand what this last node is you need to watch my previous tutorials so in this tutorial we will be discussing how to insert a note at the end of a circular singly link list in Java so let's see the demonstration of this algorithm step by step so we also know that when the circular singly linked is empty length is zero now in order to insert a note in a circular singly link list at the end the first step we do is we basically create a node and we'll pass the data so here we have created one node having the data as one and which is being referred by by this temp node and whose next is pointing to null now we want to insert this node at the end of a circular singly Ling list so moving ahead so the first step we check is whether the last is equal to null or not so if the last is equal to null then we know that circular singly length is empty so therefore the condition in if FL comes out to be true so here the first step we do is we simply assign the value of temp to last now as the circular singly link list is empty so therefore there are no notes and as we want to insert this temporary note at the end of the circular singly link list so when we insert this temporary node into the empty list we know that after it insertion this would be the only node in the circular singly link list therefore last should point to this node so in the first step we are simply assigning value of temp to to last so it would look something like this moving ahead now in the second step we are assigning value of last to last do next so why we are doing this step is we need to fulfill circular singly link list property that last next should point to First node and as we know that this is the only node in the circular singly link list therefore the last and the first node is the node itself so we are assigning value of last to last. next so it would look something like this so this link is gone and now this last. next will refer to the node itself so it would look something like this and in the last step we'll simply increment the length by one because we have successfully inserted the node at the end of a circular singly link list so friends once this algorithm executed we know that initially circular singly link list was empty and now it contains only one node so it is referred by last because this is the only node and its next is pointing to the first node which is the node itself so now if we call this algorithm again and we want to insert one more note so let's see the demonstration of the algorithm now in the first step we'll simply create the list node and provide the data which we have passed into the method so it would look something like this that temp is pointing to the node having data as it and whose next is pointing to null now let's say we want to insert this node at the end of a circular singly link list so let's see the demonstration step by step so we check whether last is equal to null or not so now the last is pointing to one node therefore it's not equal to null therefore the condition in if block comes out to be false so the else part will be executed so in the else block the first step we do is we assign the value of last. next to temp. next so here why we are doing this step is as you want to insert this temporary node at the end of a circular singly link list we know that after it insertion the the node which is referred by temp would be the last node so if it is a last node then its NE should point to the first node and how to reach to the first node we know that currently the node which is referred by last its next is the first node therefore we are simply assigning last. next value to temp. next so it would look something like this so this link will be removed and it would refer to the first node and in order to reach the first node we know that last next refers the first node therefore temp next will now refer to the node having data as one so so it would look something like this so currently you see we have two notes where temporary next is pointing to this first note so moving ahead and in the second step we are assigning value of temp to last. next now here you can see last. next is referring to itself and we know that when we insert this Noe last NE should refer to this Noe because then it will form a chain so we are simply assigning value of temp to last. next so it would look something like this so now this link will be gone and now it should refer to this temp node so moving ahead and in the last step we are simply assigning value of temp to last now we are doing this step is because we have inserted the node at the end of a circular singly link list and we know that we are keeping track of of this last pointer so after this temporary node is inserted into circular singly link list we know that this becomes the last node therefore we need to assign the value of time to last so that last refers to the last node of a circular singly link list so it would look something like this so in the final step we'll simply increment the length by one the circular singly link list has two notes and we can also see that the last next is referring to this first node now friends let's suppose we want to insert one more node into this circular singly link list so we'll execute this algorithm again and we'll pass the data into the method so let's see the demonstration of this algorithm step by step so in the first step we'll simply create a list node and we'll refer it to by temporary variable so here you can see we have simply created a temporary node having data as 10 and whose next is pointing to null and now we want to insert this note at the end of the circular singly link list so let's see the demonstration of this algorithm step by step now the first step will check whether last is equal to null or Not So currently last is pointing to the second node therefore it's not null so the condition in if block comes out to be false so the else part will be executed so the first step in else part we do is we simply assign the value of last dot next to temp. next so here you can see last. next is pointing to this first note and temp. next is pointing to null and as we want to insert this node at the end of a circular singly link list we know that after it insertion this temporary node becomes the last node therefore its next should point to the first node and in order to reach this first note we know that last next is referring to it therefore we'll simply assign value of last. next to temp. next so it would look something like this so now you can see temp next is pointing to this first node moving ahead in the second step we simply assign value of temp to last. next so here in order to insert this note at the end of a circular singly link list we know that initially this list contains two notes and in order to insert this third note we need to break temp. next link which is referring to First note and we need to assign it to the temp node because then this third node will be a part of a chain so in this step we are simply assigning value of temp to last. next so it would look something like this so this link is broken and now it will point to this temporary node moving ahead in the final step we know that as we have inserted this note which is at the last position we'll simply assign value of temp to last so it would look something like this and now in the last step we'll simply increment the length by one so friends here you can see the length of the circular singly link list is of size three as you have three notes where data is 1 8 and 10 and the last Noe next is pointing to the first node so friend this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial I created one class by name circular singly link list and we implemented circular singly link list into the class so in this tutorial we will simply write a method which would insert a note at the end of a circular singly link list so I'll create one method as public void insert last and to this method I will pass an integer value which will actually hold the data of the list node so in the first step we'll simply create the list node by name temp and we'll pass the data into the Constructor and then we'll provide an if else block so in the if we'll provide a condition as whether list is empty or not so we'll simply check whether last is equal to null or not or we can also call is empty method which we have discussed in my previous tutorials so friends if the list is empty then we'll simply assign value of temp to last and in the Second Step we'll simply assign value of last to last. next which we discussed in the slide and in the lse part so in the first step what we do is we assign the value of last. next to temp. Next in the second step we assign the value of temp to last. next and finally we assign the value of temp to last and as we discussed in the slide once we insert the note at the end of the circular singly link list we increment the length by one so length Plus+ so friend this is the code to insert the note at the end of a circular singly link list now let's test this method into the main method so in the main method I have created an instance of circular singly link list so let's add few note at the end of the circular singly link list so here we will add the notes which we saw in the slide so insert last and let's say I provide data as one and if I print the circular singly link list by calling display method you can see when I run the code it prints one because initially circular singly link is empty and when we insert one node at the end of the circular singly link list we only get this one node now let's insert one more node and I provide data as8 and when when I run this code you can see it printed one and then it so therefore it inserted it at the end of the circular singly link list now let's say I insert one more node having data is 10 and if I run this code you can see it printed 10 so friends here we inserted three notes at the end of the circular singly link list so first first we inserted one then we inserted eight so eight was inserted at the last position and finally we inserted 10 so you can see the 10 is inserted just after it and which is the last node so friends in this tutorial we discussed how to insert a note at the end of a circular singly link list I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to welc to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to remove first node from a circular singly link list in Java so friends let's suppose we are given a circular singly link list having three notes say 1 8 and 10 whose length is three so friends in our previous tutorial we discussed that we are keeping the track of the last node of the circuit singly link list through the last instance variable so friends below is the algorithm to remove the first node from a circular singly link list in Java so let's see the demonstration of this algorithm step by step so the first thing we here we do is we check whether the circular singly link list is empty or not so if you see circular singly link list has three notes and length is three therefore it's not empty so the condition in if block comes out to be false moving ahead now in order to remove the first node from a circular singly link list we know that we are keeping the track of the last node and in the circular singly link list last node next points to the first node so therefore here we are creating a temp node and we are assigning the value of last dot next to it so this time will point to the first node because in the circular singly link list last next points to the first node so it would look something like this moving ahead so here we have providing an F El block and in the if block we are checking that whether last. next is equal to last or not so this condition comes into picture when the circular singly link list has only one node left so in this case last next point to the last because the circular singly link list has only one element where first and the last node is the node itself so here you can see last next is pointing to this first node and therefore it's not equal to last so the condition in if blog comes out to be false and the else part will be executed so in the else part the first step we do is we assign the value of temp. next to last. next now friends as we want to remove this first node we need to do two things first we need to break this link which is being referred by last. next to the first node so in order to remove this link what we are doing we are simply assigning the value of temp. next to last. nextt so friends here if you see when we remove this first node from the circular singly link list the node having the data as 8 becomes the first node because this node is removed and we also know that circular singly link list has property that last next points to the first node so in this step we are simply assigning the value of temp next to last do next now why we are doing this step is because once the first node is removed the second node becomes the first node so there therefore last. next should point to the second node so when this step is executed it looks something like this that last. next is removed and we will assign the value of temp. next to last. next so it would look something like this so we are breaking the link of last dot next to the first node and then we are assigning it to the second node because when the first node is removed the second node becomes our new first node moving ahead and after the fs block we simply assign the value of null to temp. next so friends as we are removing this first note and returning it from the method therefore we need to break this link as well so in order to break this link we are simply assigning null value to temp. next so it would look something like this moving ahead and then we are decrementing the length by one because we know that we have removed this node from the Circ singly link list so initially the length was three so now it will become two moving ahead and then we are simply returning this temp node because we already removed it from the circular singly link list so it would look something like this so friend as soon as we have removed this link we know that we are currently left with two nodes and here you can see the node having the data as 8 becomes our new first node and you can also so see last next is pointing to this node therefore if we again call this algorithm and we want to remove the first node of a circular singly link list the algorithm goes as follows so again first we check whether the circular singly link is empty or not so here you can see circular singly link list has two notes therefore it's not empty so the condition in if blog comes out to be false and the first step we are simply creating the temp node and assigning the value of last dot next to it so friends here as we track the last node of the circular singly link list and we want to remove the first node therefore in order to reach the first node what we do we simply do last. next so this value we are assigning to a temp node and it would look something like this so here you can see last do next is pointing to this first node and we are assigning that value to Temp so now temp will find to the node having data as it moving ahead and then in the if blog we are checking that whether last. next is equal to last or Not So currently last. next is pointing to this first node therefore last. next is not equal to last so the condition in if block comes out to be false and the else part will be executed so friends in the lse part what we are doing we are simply assigning the value of temp. next to last. next so in order to remove the node having data as 8 we need to first break this link which is being referred by last. next and we also know that when we remove this particular node from the circular singly link list we are left with only one node so therefore last. next should point to that particular node so friends here we are assigning the value of temp. next to last. next so we know that we have to remove this link and when we remove this particular node having data as it we know that now 10 will become our first and the last node both therefore we are simp assigning the value of temp next which is the node having data is 10 to last next so it would look something like this so here you can see the link is removed and then we are assigning temp next to last next so it would look something like this so friends here we have removed the link which is referring to this particular node which we want to remove moving ahead and then we are simply assigning the value of null to temp. next because as we are returning this complete note we need to break this link so it would look something like this so now temp. next instead of pointing the node having data as 10 it is now pointing to null and as we have removed this node from the circular singly link list we will decrement the length so now length is one because we have only one node left and in the final step we are simply returning the temp so it would look something like this so friends after the method get executed we are left with only one node which is the first and the last node both because we are keeping the track of the last node and when the circular sign link list has only one element left we know that that particular node is the last node and if it Traverse to its next then it will refer to itself because this is the first node and the last node both and if you call this algorithm again in order to remove this last last node from the circular singly link list so the demonstration of the algorithm is as follow so first we check whether the list is empty or Not So currently circular singly link list has one node therefore it's not empty so the condition in if blog comes out to be false and as we want to remove the first node of the circular singly link list we assign the value of last. next to Temp but here you can see we are only left with one node therefore the last dot next is pointing to that part particular node only so after this line gets executed it would look something like this so here you can see temp is pointing to last do next which is the node itself moving ahead and now we are checking whether last do next is equal to last or not so as we discussed earlier this condition will come only into picture when we are left with one node So currently here you can see last next is pointing to the last node itself therefore the condition in if blog comes out to be true so the if blog will be executed so friend in this step we are assigning null to last because in order to remove this node we have to break this link if you break this link then this node will be freed up so when this statement will be executed it would look something like this that now last will point to null and as we have broke this link now now this note can be removed easily so after the if statement the last step we do is we simply assign the value of null to temp. next So currently here you see temp next is pointing to Temp itself therefore we need to break this link so your temp next is pointing to null moving ahead and then we are simply decrementing the length by one because we have successfully removed the node so now length becomes zero and here you can see last is now pointing to null and in the final step we are simply returning the temp so it would look something like this so friends after we remove all the elements now if you again call this algorithm so in the first step we'll check whether the circular singly link is empty or not so here you can see the length is zero and last is pointing to null therefore the circular singly link list is empty so the condition in if blog comes out to be true and as we know that when the circular singly link is empty there are no notes left to be removed so therefore we can throw a no such element exception because there are no notes left to be removed so friends here we saw the demonstration of the algorithm now let's go to eclipse and see the working code so so friends in my previous tutorial we created one class by name circular singly link list and we implemented the code for the circular singly link list into that particular class so in order to understand the working of circular singly link list you can watch my previous tutorials and here you can see we are keeping the track of the last node through the instance variable list node so in this tutorial we will write the code to remove the first note from the circular singly link list so here let's suppose we give the method name is public list node remove first so friends here I have given the method name as remove first and whose return type is of list node so this method will remove the first note from the circular singly link list and we'll return it back to us so in the first step as as we saw in the slide we are checking that whether circular singly link list is empty or not so is empty so if the circular singly link is empty we will throw no such element exception and here we provide a string as circular singly link list is already empty and if the circular singly link is not empty then the first step we do is we create a temp list node and we'll assign the value of last dot next to it and then we'll provide an if else block so in the F block we provide a condition as that whether last. next is equal to last or not so if the last. next is equal to last then we'll simply assign null value to last because we know that this condition comes into picture when there is only one node left into the circular singly link list and in that case if you want to remove that particular node we need to Simply assign the null value to last because this last is referring to that particular node and in the else part we are simply assigning temp next value to last. next and after Fels block we are simply assigning null value to Temp next and then we are reducing the length by one and in the final step we are simply returning the 10 temp node so friends this is the algorithm to remove the first node from the circular singly link list now let's test it's working in the main method so friends in my previous tutorial we discussed how we can insert the node into the circular singly link list so we inserted three notes in my previous tutorial with the data is 1 8 and 10 and we also created One display method which could display the entire circular singly link list so if I run the code now you can see it printed 1 8 and 10 because there are three notes in the circular singly link list 1 8 and 10 now let's say we are removing the first note from the circular singly link list and we are calling the display method again now if I run the code again so here you can see initially it printed 1 8 and 10 because we have three notes in the circular singly link list and when we removed the first note so one got removed and it printed 8 and 10 now let's say again call remove first method and if I run the code now so you can see it removed one and then it removed eight and it finally printed 10 and if I call again remove first and if I run the code so you can see in the second line it printed nothing because it removed all the nodes from the circular singly link list and when we call display so here you can see in display method we are initially keeping a condition whether last is equal to null and if last is equal to null then we are simply returning from the method so therefore it printed nothing because when we have remove removed all the notes from the circular singly link list we know that last point to the null and now if I call again remove first and if I run the code so you can see it gave an exception as no such element exception and in printed messages circular singly link list is already empty so friends in this tutorial we discussed how to remove the first node from the circular singly link list in Java so friends usually we never return the list node from a method and we actually return the data part of the node which we want to remove so here if you are calling remove first so it should remove the node but it should return us back the data part of it so the code is similar what we need to do is we need to change the return return type to int because the data is of integer type and here after pointing to the first note by going through last. next we create an integer variable which stores the data of the first node so we simply assign tam. data to result integer variable so initially we were making temp. next point to null we were doing this step because we are only returning back the list node so now when we are returning back the data part of it we don't require this step because this node will be automatically garbage collected by Java and in the last step we are simply returning back the result so friends initially we removed the first first note from the circular singly link list and we returned it back and after some modification we are returning back the integer value so let's test the working of this method so here we'll just print the data which this remove first will return us back so here we will call remove first so here you can see there are three notes 1 8 and 10 and then we are removing the first note so therefore it should print the value as one because one is the first note of the circular singly link list and if I run the code so here you can see initially it printed the three notes with data is 1 8 and 10 and then it removed the first note which is one and it printed it on the console and when we did display again there were two notes left which is 8 and 10 so friends in this tutorial we discussed how to remove the first note from the circular singly link list in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to represent a stack in Java so friends what is a stack so stack is a linear data structure used for storing the data we call it a linear data structure because it can be represented by a link list or an array in which the notes are adjacent to each other therefore it's a linear data structure so the basic property of a stack is that it's an ordered list in which we insert and delete the note at one end which is called a stop so here if you see if suppose we are given a list and the first node is pointed by top so we make this list restrictive in nature in the way that we can insert and delete the node at one end which is represented by top and if you see this restrictive property makes it a Leo data structure so what is a Leo data structure the last element inserted is the first one to be deleted so here if you see when we insert a node in the stack at the beginning so that element becomes the first candidate to be deleted because we are only allowed to remove and add the notes at one end which is represented by the top moving ahead so friends let's see a demo of how Stacks looks and how the elements are stored and removed so initially if you see when the stack is empty so the top node points to null and usually we use push and pop operation to add and remove the elements from the stack so suppose if you want to push an element having the data as 10 so it would look something like this and once we push the element into the stack the top node points to that particular node inserted so suppose we want to push now node 15 so when the node is pushed into the stack the top points to that particular node and now suppose we want to push 20 so when the node is inserted top points to the last node inserted if you see the stack is basically a oneway list so here you can think that we are inserting node at the one end and the other end is blogged so there is only one end to push the elements and pop the elements so basically if you see when we inserted 20 the top pointed to De element so now if you want to pop an element we know that there is only one end where this notes will be removed so as we pop 20 so now top will point to the note just before it and let's say if you want to again pop an element so now top will point to the node just before it and finally if we again pop an element so you can see the 10 got removed and now top points to again null so friend this is how the stack works as you saw it's a last in first out data structure so you saw the element which was inserted the last was the first one to be removed so friends this is how we actually represent the stack I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to implement a stack in Java so friends in my previous tutorial I discussed how to represent a stack we saw that it is a Leo data structure which means that element which got inserted last would be the first one to be removed and we also discussed that the elements are inserted and removed at the one end which is represented by top so friends in this tutorial we will discuss how to implement a stack in Java we will discuss few of the methods which it implements such as push which actually inserts an element into the stack and we will also discuss pop method which removes the last note inserted from the stack so friends in this tutorial we will Implement a stack using a link list so friends as you know that link list is represented by a list node where it contains two things one is the data and other is the pointer to the next list node so when we Implement a stack class we usually keep two instance variables one is top and another one is length so in our previous tutorial we discussed that this top node is used to insert and remove the elements from the stack and here the instance variable length which represents the size of the stack so friends let's see the demonstration of this algorithm so friends when we initialize a stack first top points to null and the length is zero so here you can see top is pointing to null and as the stack is empty the length is zero now suppose we want to add an element having data as 10 so we'll call this push method and pass the data into it so when we call push and pass data as 10 we we know that data is 10 so let's see the execution of this method step by step so in order to push an element into a stack we first create a temporary list node having a data which we have passed as an argument so it would look something like this that we have created a list node having data as 10 and it's next pointing to null and you see the name of the list node is stamp and it's pointing to that particular node moving ahead now in order to insert this node into the stack the first step we do is we assign the value of top to temp. next so friends here you see temp points to this node and its next points to null and when the stack is empty we know the top is also pointing to null so in the first step we are simply assigning a null value to Temp next so it would look something like this so after this step temp next is pointing to null and top is also pointing to null moving ahead and then we'll assign the value of temp to top so here you see top points to null and when we'll assign the value of temp so temp is pointing to this node so after this step top will point to the temporary node so it would look something like this and in the final step as we know that we have inserted this temporary node we'll increment the length of the stack by one so here you see when this method gets executed the stack looks something like this the top is pointing to a node having the data which we passed into the push method and it's next is pointing to null and therefore the stack has one element therefore the length is one now suppose we again call Push method and pass data is 15 so let's see execution of this method step by step when length is one and top is already pointing to node so here when we have called push 15 so the data is 15 so here we'll create a temporary node and this temporary node will hold the data which we pass into this push method so here you see we have created this temporary node having data is 15 and it's next pointing to null moving ahead so friends the next step is we'll assign the value of top to temp. next So currently temp. next is pointing to null so in order to insert this node into the stack we are assigning the value of top to temp. next so we are doing something like this we are removing this link and we are pointing it to top so in this step we are assigning the value of top to temp. next so now temp. next is pointing to top moving ahead so as this node is now inserted now top should point to this node so therefore we are assigning the value of temp to top so it would look something like this so now top is pointing to the temporary node moving ahead and we'll simply increment the length by one because now the Stag has two elements so friends after this method get executed the stack looks something like this so here you see the top is pointing to the node which we inserted last so friend this is how we insert an element into the stack now let's see the pop operation in which we remove the last inserted element so so we'll take the previous example we know that first we inserted 10 and then we inserted 15 so in the pop the last element inserted will be the first one to be removed so let's see how this pop method works so in order to remove the last inserted node so what we'll do we'll simply capture top do data into integer variable aable by name result so we are storing the data inside this node into the integer variable result moving ahead now as we want to remove this last inserted node we we need to break this link so once this node is removed top should point to it next element so for that we'll simply assign top. next value to top so it would look something like this and as this node is not referred by top it would be garbage collected moving ahead now we have removed the node from the stack so we need to decrement the length by one so now length becomes one so we'll simply return the value 15 from this method now you see the stack contains only one element and the length length is one now if we again call the pop method so first we'll store the data inside this list node which is being pointed by the top so we are simply assigning top dot data into an integer variable result and as we need to remove this node we'll simply break this link and assign top to its next so we are simply assigning top. next value to top so top do next is is pointing to null so we are simply assigning a null value to top so it would look something like this and as this list Noe is not referred by top so it would be removed we'll decrement the length by one because the node is now removed from the stack and finally we'll return the result so friends here you can see when the stack is empty the length is zero and top points to null so friends here we saw the demonstration of how to implement a stag in Java so let's go to eclipse and see the working code so friends in order to implement a stack in Java I have just created one class by name stack so in this class we will implement the stack functionality so as we saw in the slide that stack contains few instance variables so we'll create one instance variable of type list node by name top so private list node top and we'll also create an integer variable by name length which will store the size of the stack so private and length so friends as you can see we are implementing a stack using a linked list which is represented by list node so we'll create a inner class of type list node so friends in our previous tutorial we discussed how we can represent a list node in Java so a list node contains two things one is the data so private end data and other is pointer to next list node so private list node next we'll also create one Constructor so this Constructor takes the data part so friends here we are implementing this tag using a link list so we have created a list node now once we initialize the stack we know that top points to null and length is zero so we'll create one Constructor for this tag class public stack and here we'll assign a null value to top and length S zero friends we will also create one method by name length which will return us back the length of the stack so public int length return length we'll create one Boolean method by name is empty which will return return as a Boolean value whether the stack is empty or not so public Boolean is empty so here we'll simply return return a Boolean value which will represent whether the stack is empty or not so in order to know that the stack is empty we'll simply check whether length is zero or not so if the length is zero we'll simply return true that stack is empty and if the length is not zero then we'll simply return a value of false that stack is not empty so we'll simply return length equals zero moving ahead so friends first we'll code the push method so public void push and in this push method will pass the data so this data will be inserted into the stack so in order to insert this data into the stack we'll first create a list node and we'll give name as temp and we'll create this list node and inside the Constructor we'll pass the data moving ahead on the next step we'll simply assign value of top to temp. next and then we'll simply assign the value of temp to top so so top equal temp and finally as the data is inserted we'll increment the length by one so friend this is the push method now we'll implement the pop method so public int pop so friend this method will return us back the value of last inserted node into the stack so here first we'll put an if check and the check would be is empty so friends if suppose the stack is empty then we can't pop an element from the stack so if the stack is empty we'll throw an exception we'll throw empty stack exception because we know that stack is empty and we cannot pop an element from an empty stack so friends if the stack is not empty then the first step we'll do we'll create an integer variable by name result and we'll assign the value of data stored in the top list node so we'll do top. data and as we have stored the data inside the top you can simply Traverse to next node by assigning top. next value to top and finally the top has moved to its next node so that node will be garbage collected and we can simply reduce the length of the stack by one and finally we'll return result so friend this is how we pop an element from a stack the stack also contains one more method by name Peak so what this peak method does is it simply return us back the value which top holds so it is nothing but returning a value of a last inserted node into the stack so we'll create a method by name Peak so public int PE Peak so we'll also provide a if check here that if the stack is empty we will throw empty stack exception and if the stack is not empty then we can return top. data because we know that top points to the last inserted node into the stack and if we do top. data we'll get the value stored in that particular list node so friends this is how we Implement a tag in Java now let's see the demonstration of these methods so in the main method first we'll create a stack so when we do new stack we know that top is pointing to null and length is zero so let's say we push few elements into the stack so stack do push and let's say we give data as 10 15 and 20 so friends here in stag we have pushed 10 15 and 20 and we know that initially top pointed to null and as we inserted the data 10 it pointed to 10 then as we pushed few notes that 10 15 and 20 so we know that top points to last inserted Noe so so if we print tack. Peak so if we are printing the peak value of the stack we know that it prints the value of last inserted node so if I run the program you see it prints 20 because 20 is the element which we last inserted and suppose I want to pop an element so so I will do stack. pop so we know the top points to the last inserted note so when we do a pop 20 will be removed and if I print stack. Peak and run the code so you can see it prints 15 the next time when we do stack. pop the last inserted element is the first element to be removed so the 20 is removed and stack contains 10 and 15 and 15 is at the peak portion so it printed 15 and if I simply copy paste this and run the code so you can see the third time it printed 10 because we removed 15 as well so here if you see we have implemented push and pop in such a way that it is resembling a Leo data structure which is the element inserted last is the first to be removed so friends in this tutorial we saw how we can Implement a stag in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day hello everyone so in this video we are going to discuss that how we can Implement a stack with an array in our previous video we saw how we can represent a stack and we also saw that how we can Implement a stack using a link list so in this video we will see that how we can Implement a stack with an array so friends before we start in case if you're new to my my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so in our previous videos we saw that stack is a Leo data structure which means last in first out now if this is a stack then here in this data structure there is only one end where the elements are inserted whilea push method and from the same end the elements are popped out using pop method so therefore the element which is last inserted it's first one to be removed so for example if we insert three then two and then one so first we inserted three then we inserted two and then we inserted one so the last element which got inserted was one so this would become the first element to be popped out so in this video we will see the implementation of push pop and Peak method with the help of an array and we will see that how we can implement the stack using an array so if we are implementing a stack using an array we need to provide the capacity to it so as the internal data structure is array this capacity will tell that we need an array of three elements which also signifies that stack at the start Can Only Hold three elements so internally it would look something like this that an array will be created of three elements having a default value of zero So currently it's an INT array therefore the default values are zero if it is an integer array then the default values would be null in our previous videos we also discussed that values are inserted into the stack using the top variable so here top is an integer variable which will Traverse this array and basically insert the elements based on the indexes so at the start top is actually pointing to minus one it means the stack is empty so now let's see how we can perform push and pop operation so let's suppose we want to push element 8 so usually what happens is we can insert eight into this array at zero index first index and second index now at the start top is pointing to minus one now whenever we do push we first increment Top by one so currently value of top is minus one when we increment it by one it becomes zero and as it is pointing to zero index what we do is we simply assign value 8 like this so 8 comes here and if we see the visual representation of Stack it looks something like this that this is the stack the element is pushed into the the stack and top is pointing to this element now similarly let's say if you push four so the first thing we do is we increment Top by one so top becomes one and four is inserted at index one like this so four comes here and here it looks something like this that four is pushed into the stack and now top is pointing to four so basically when we perform push we we do top Plus+ and then we perform array of top and we assign the value which is our data which we have passed into our push method so we perform these two steps in the push operation now let's say if we want to push three so first we increment top it becomes two and at array of two we assign three so so three comes here and in the stack it looks something like this that three is pushed and top is pointing to this three now let's say if we push one more element with the data as one so here you can see that initially when we created stack we provided a capacity of three it means the stack can hold only three elements now if we want to insert one more element we know that there is no more place into the stack so usually before this two stack we perform a check that whether stack is full or not so if stack is full we throw an exception so usually how we check whether stack is full or not we do array. length and we compare it with the size of the stack so there is a method size now here if you see aor do length will be three and if you calculate the size of the stack the the size of the stack is nothing but number of elements into the stack so we know that number of elements are three and array do length is also three so how we evaluate the size function is whatever the value is hold by top which is two we do something like top + 1 so usually this size method will return return top + 1 so here value of top is 2 if we do+ one we get three so aray dot length is three and size is also three so it means the stack is full and we can't insert more elements to it so we throw an exception now let's suppose our stack has three elements 8 4 3 and now we want to pop it so we know that we pushed elements like this and we know that the last inserted element will be first to be removed via pop method so when the pop method is called to whichever index stop is pointing that element was last inserted so now this will be the first one to be removed so we store this value into a temporary variable and at the end we return this value and what we do is we simply decrement top so we do top minus minus so it looks something like this that initial value of top was two not becomes one now here either we can provide a value zero or we can left this element as it is because whatever the insertion and deletion we are doing into this array is based on top so either we assign this value to zero or if it is a integer array then we can also assign a value of null to it and here in the stack it looks like three is popped out and now top is pointing to four now let's say if you again call Pop so now top is pointing to index one and the value is four so now this this four will be removed so we first store this four into a temporary variable and then we simply decrement top so top comes here and it looks like four is popped out and top is pointing to it and similarly if we call Pop again then it will be removed and we will decrement top so now top will become minus one and it will be popped out so here can see if the value of top is less than zero it means stack is empty and if we again call Pop method then we also check at the start whether value of top is less than zero or not if it is less than zero then we throw an exception that stack is empty and there are no more elements to be popped out so now let's move ahead and see the implementation of Stack using an array step by step so this is the code we have a class stack and as we discussed we have two variables top and the integer array and Via this integer array we are implementing stack we have a Constructor which takes in a capacity and this capacity is assigned to initialize our integer array and usually if we don't provide any value to our stack Constructor then the by default capacity is 10 so let's see the demonstration of this algorithm step by step so we will create a new stack we pass in the value as three which would be our capacity so the Constructor will be called capacity is three and we know that at the start when the stack is empty top is pointing to minus1 so value of top is minus1 and we will initialize the array with our capacity of three so it looks something like this that it has capacity to hold three elements with index 0 1 and two and if you visualize the stack it looks something like this so when we initialize stack at the start the stack looks something like this now let's discuss the push method so let's suppose we call Push method and we need to push a value8 so the data is8 which we need to push into the stack now before pushing a into the stack we first check whether our stack is full or not so by full we mean that internally it's an array and let's say the capacity of array is three so we check whether this array already contains three elements or not because if the array has three elements then we can't push it into the array so how we check whether stack is full or not we call this full method now is full method returns a Boolean value which is true or false which says that the stack is full or or not and inside this method how we check whether stack is full or not we simply compare AR's length which is three so array do length is three because the array contains a capacity of holding three elements so array do length is three and in the implementation of Stack we also provid a size method now this size method will actually give us an information that how many elements are currently into the stack so when we will call the size method it actually returns an integer value and what we actually return is top + one we are returning top + one because let's suppose we have filled all the elements into the array so top will be here and if top is at this index so the value of top will be two but if we see the size of the stack is it is actually holding three elements so we simply return top + one which actually tells what is the size of the stack so we simply return return top + one which says that how many elements are currently into the stack So currently value of top is minus1 if we add + one the value is zero it means currently in the stack there are no elements so it returns zero so 3 is not equal to zero it means this condition will be false and false will be written from this method so the condition in if blog comes out to be false that stack is not full so now we can push this data into the stack now the first thing we do is as top is pointing to minus one and we are inserting the elements into the stack using an array so the first place to insert is at zero index so at the start first we will increment top so value of top will become zero top will point to the zeroth index and then using array of top we will assign the data so here array of zero we will assign a value 8 so8 will come here like this and if you visualize the stack it looks that eight is pushed into the stack and top is pointing to it now let's say if you again push a value four so the data is four we check whether stack is full or not so array do length is three and then we will evaluate the size and currently we know that stack has one element which is8 so when we will do top + one value of top is zero so 0 + 1 will give one it states that the size of the stack currently is one because there is one Element so 3 is not equal to 1 so false value will be returned from here and the if blog won't get execute because is full will return false value now we will increment top because the next value we need to insert is here current value of top is zero so when we will increment it will become one and now to array of top we assign the data so array of one we assign the value as four so four will come here and if you visualize the stack it would look something like this that four is pushed into the stack and top is pointing to four now now let's say if you want to push a value three so data is three we check whether stack is full or not so array do length is three and size of the stack is two which is top + 1 so value of top is 1 1 + 1 is 2 which states that stack has two elements so this method will return two and 3 is not equal to two so this method will return a false value so this if blog won't get execute now the next value should come here because this space is occupied so we increment top top becomes two and at the second index we insert data which is three so three comes here so if you visualize stack it looks that three is pushed like this and top is pointing to it so now let's push one more element with the data as one so the push method will be called with the data as one now here you can see the initial capacity of the array was three and stack has three elements it means the array is completely occupied so when we will call is full method to check whether stack is full or not array do length is three and when we will call size method we know that current size of the stack is three it simply return stop plus one so value of top is two so it return 2 + 1 which is three so the size method will return return three and here we are comparing three with three so via this comparison we come to know that the stack has three elements and the capacity of our array is also three it means that stack is full so from his full method true will be return which signifies that stack is full so we can't push one into the stack and this if log will be executed so we simply throw an exception that stack is full like this and we can't push one into the stack so now let's look into the implementation of Pop method now let's suppose our current stack has three values 8 4 3 the demonstration we saw in our previous slide so value of top is two so when we will call Pop method usually with the help of top we actually push into the array and with the help of top we actually pop the elements from the array so in this stack it looks like that we are inserting element from one end and we are removing it from the same end and whatever the element was inserted last will be the first one to be removed so basically top is actually helping us in maintaining Leo property that the element inserted last is first one to be removed so three was inserted last because top is pointing to three so when we will call [Music] Pop the first thing we check is whether stag is empty or not because if stag is empty there are no Elements which we can pop so how we check whether stag is empty or not we call is empty method and we simply check whether top is less than zero or not so when we saw that initially when stop is pointing to minus1 the stack was empty the array actually had three values to be inserted because the capacity of array was three So currently value of top is two and it is not less than zero so therefore is Mt method will return false that stack is not empty so this if blog won't get executed and now as we need to pop three from the stack because three was the last element inserted into into the stack what we do is we create a temporary variable by name result and we assign value of array top which means that we are assigning it a value which is being hold by second index because value of top is two so we are assigning value three to result and after assigning this value now we can simply decrement top so top becomes one and it looks like that three is popped out from the stack and top is pointing to the element previous to it which is four and at the end we simply return result so value three is return return from this method now if you again call Pop so now four will be removed we check whether stag is empty or not so value of top is 1 1 one is not less than zero so the Stag is not empty so a false value will be returned and this if blog won't get executed first we will hold the value from the array index one because value of top is one so four is assigned to result then we will decrement top and top becomes zero so it looks like this and if you visualize the stack it looks like four is popped out and top is pointing to eight now which is index zero and we simply return value four that four is popped out from the stack let's say if we again call Pop now eight will be removed we check whether stack is empty or not so value of top is 0 0 is not less than 0o so false value will be returned so this if blog won't get executed we first hold the value of the zeroth index which is 8 because top is pointing to zero so result will have value eight we decrement top top becomes minus one like this and it looks like 8 is popped out from the stack and top is actually pointing to minus one and simply at the end we return result as eight that eight is popped out from the stack now here stag is empty so if we again call Pop method we first check whether stag is empty or not so here you can see value of top is minus one so top is actually less than zero which signifies that stack is empty so true will be returned and this if blog will get executed and we simply throw a runtime exception that stack is empty which signifies that there are no more elements to be popped from the stack so we actually saw pop method which actually removed the element from the stack but there is one more method Peak now what this method does is whatever the value is hold by top which actually is our last element inserted into the stack so if we don't want to remove this element and we just want to see what is the peak element or what is the last element inserted into the stack we usually call Peak method so when we call stack. Peak so let's say current condition of the stack is like this that there are two elements 8 and four and four was last element inserted into the stack so when we will call Peak the first thing we check whether stack is empty or not so value of top is 1 and one is not less than zero so false will be returned that stack has two elements so this if blog won't get execute so here instead of removing the element from the stack we are just returning the value stored at the top index which is at index one and the value is four so this peak method will give us information that which element was inserted last so value four will be returned from this peak method and the element will stay in the stack it won't get removed it is just giving us and information that which is the last element inserted into the stack which is our Peak element so friend this was all about implementation of Stack using an array I hope you must have liked this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to reverse a string using a stack in Java so friends friends below you can see an algorithm which would reverse a string using a stack in Java so friends let's see the demonstration of this algorithm step by step so friends let's suppose we are given a string whose value is a b c d so here we will see the demonstration of the algorithm which would reverse this string using a stack in Java so in the first step what we do is we actually create a stack now this stack will hold only the character values so an empty stack is created moving ahead now as we are given with this string AB CD we'll first convert it into and character array so in the string class there is a method two care array which returns back a character array so it would look something like this that we are now having a character array whose length is four and whose values are a b c and d moving ahead so friends here we know that a stack is a Leo data structure which means last in first out and we also discussed in our previous tutorial that how we can represent a stack and we also discussed the push and the pop methods of the stack so the general idea behind the working of Stack is the element which goes into the stack last becomes the first one to be removed so in this step what we are actually doing we are providing a for Loop which will iterate over each and every character of this car array and then it will simply push it into the stack so in the first iteration the value of C will become a and then we simply push the character a into the stack so it would look something like this that now a is into the stack and similarly now C becomes B we will push B into the stack moving ahead now C becomes the character C and we'll simply push the C into the stack and finally C becomes the last value which is D and we will push it into the stack so now as you have traversed each and every character of this car array there are no more elements left to be traversed so friends here now in this stack we have four elements the first element which we inserted was a then we inserted B then we inserted C and the last element we inserted is the D so friends now we'll again provide a for Loop which will iterate from the value I equal to 0 to a value lesser than string do length so initially value of I is z and here we can see that the length of the string is four So currently I is less than 4 so now what we do is we'll pop the elements from the stack and then we'll simply assign it to the respective index from 0 to 3 so friend as soon as we call stack. Pop the element which is last inserted which is nothing but D will be popped out so it would look something like this so now D is popped out and the value will be assigned to the car array at index zero which is this position so now it becomes D moving ahead now we'll increment the I so I becomes 1 and still the value of I is less than 4 now we'll again pop the element from the stack which is nothing but value C and we'll assign it to the car array at index one so the value of index one becomes C moving ahead now value of I becomes two 2 is less than 4 we now pop an element from the stack and this value we will assign to the character array at index 2 so now at index 2 we will assign the value B moving ahead we'll now increment the I so I becomes three and 3 is less than 4 so we'll pop in an element from the stack so now value a is popped out and it will be assigned to this scare array at index 3 because value of I is three so value of this SC at index 3 becomes a moving ahead now I becomes 4 and so four is not less than four so therefore the condition in for Loop comes out to be false and also friends here you can see that using this stack we have actually reversed this character array and the last step will simply return return this string by passing in the character array so now it will return a string having a value as d c b a so friends in this tutorial we saw how we can reverse a string using a stack in Java now let's go to eclipse and see the working of this code so friends in our previous tutorial we actually saw the demonstration of the algorithm to reverse a string using a stack now in this tutorial we'll actually code the algorithm and test the working of it so here I have created one class by name String reverse and inside this class I will create one static method which will return a string and whose name would be reverse now this reverse method will take in a string which we actually want to reverse so friends in our previous tutorial we discussed how we can reverse a string using a stack so here we will create an instance of stack and this stack will hold the character type elements we'll name it as stack and we will imported from java.util package and the next step what we do is as we are given this string we'll first convert it into character array we'll give name as cares and we'll call two care array method of string class which will actually convert this string into an character array and we'll assign it to this car array now we'll simply iterate over this SC array 1 by one and then we'll simply push the character into the stack so stack. push so whatever the string we have passed this for will iterate each and every character of this string and it will push it onto the stack so in the next step we'll again create a for Loop now this for Loop will iterate from value I equal to 0 to I less than strings length and inside this follow Loop what we'll simply do is we will pop the elements from stack and we will assign it to car SF at the respect to index from 0 to string length minus one so friends as we know that stack is a Leo data structure so the element which is inserted last will be the first to be popped out so as we have inserted all the character elements one by one into the stack so now when we'll pop it out it will be coming out in the reverse order and then we are simply storing it into the car array and finally we'll simply return a new new string by providing this car array into its Constructor so after this method gets executed whatever the string we have passed the character inside this string gets reversed so in the main method Let's test the working of this code so first we'll create a string we'll give it a value as a b c d which we actually discussed in the slide and then we'll simply print this r on the console so this would be before reverse and then we'll print the string after reverse so we'll simply call the reverse method and pass the string to it so whatever the value will be return return from this reverse method it will be printed on the console so let's run this code so friends here you can see before reversing the string it was a c d and after reversing the string it became dcba so friend in this tutorial we saw the algorithm to reverse a string using a stack in Java I hope hope you like this video thanks have a nice day hello everyone so in this video we are going to discuss a problem next greater element so let's see what this problem is and how to solve this so in this problem we are given an array of integers and for each element in the array we need to find its next greater element in that array so the next greater element is the first element towards right which is greater than the current element so let's see it by an example let's suppose we are given an array of integers 4 7 3 4 8 1 now for each element we need to find its next greater element and the next greater element is the first element towards its right which is greater than the current element so here for element 4 it will see in the right direction and it it will see which is the first element in right which is greater than four so here it sees that 7 is the first greater element than four so in the output array we are storing 7 here for index zero for index one we have 7 so 7 C is in this direction and it checks which is the first greater element whose value is greater than 7 so three is not greater four is not greater but eight is greater so we store eight here now for three it will look in this direction and it will see that 4 is greater than three and it's the first greater element so we simply store four here here we are storing it in the respect to indexes now four will see in this direction and it will see that 8 is the first element which is greater than four so we store eight here 8 will see in this direction and here 8 will find that no element is greater than 8 in the remaining array so we simply store minus one and similarly with one there are no elements left so therefore we directly store minus one so here for each index we are taking that particular ular value and we are finding the first element in the right direction which is greater than the current element so we are looking for the first element towards right so for example so for element 4 the first element which is greater than 4 is 7 8 is also greater than four but the first element is seven so we store seven here which corresponds to this particular index and and similarly for three four is the first element which is greater than three 8 is also greater but four is the first greater element so the problem is actually to find the next greater element in the array for any particular index and that should be the first element towards right which is greater than the current element so let's move ahead and see the demonstration of the algorithm step by step so friends before we start in in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update and I would request you to watch this video till the end so here is the algorithm where the method name is next greater element it takes in an array and it return returns an array so the array which is return stores the next greater element of each and every element in the array so let's say we call the next crer element we pass in the array and let's say we pass the array having six elements 4 7 3 4 8 1 not the first step we create the result array we need to return this result array so we are creating a new result array of the same length as of the given array so we call new int we pass array do length so the result array also has six elements so friends in order to solve this problem of finding the next greater element towards right we take the help of Stack data structure so we initialize a stack like this now this is the Leo data structure the element inserted last will be the first one to be removed so we will see that how we can use the stack data structure and find the next greater element for each and every element in the array so friend in this problem we need to iterate each and every element but we will iterate the array from the last index and go till the zeroth index so here we are traversing the array in this direction because this direction will help us in finding out the next greater element towards right so at the start the value of I will be array do length minus one so array do length is six because there are six elements if we do minus one we are starting from the fifth index so I will start from the fifth index so friends here you can see that as we are starting from the last index there is no greater element towards its right so therefore we first check whether our stack is empty or not because in the stack we will store some elements which will figure out that which is the greater element towards the right and which is the first greater element towards the right so at the first step we are checking whether stack is empty or not so you will understand this step more clear when we reach to the middle of the array so at the start stack is empty so this condition comes out to be false because stack is empty and then we provide a f Els we check whether stack is empty so stack is empty which signifies that there is no greater element for this index to its right so for one there is no element towards its right which is greater than 1 so we directly store minus1 into the result array at index I which is this index so minus1 comes here and at the end we just push one onto the stack so why we are pushing one onto the stack is because let's say at index 4 there could have been value as Zer so for 0er 1 would have been its next greater element so we can't discard this one directly we need to push it on the stack for the rest of the elements to compare so we simply push array of I which is one into the stack so one comes into the stack we will decrement I so I becomes 4 4 is greater than equal to Z so this condition is true now here we are checking whether stack is empty or not so stack is not empty so this condition comes out to be true so if stack is not empty that on the stack there could be an element which is greater than the current element we will see how so if this condition is true in the block we are providing a while loop and in the while loop we are providing two condition with an end that stack should not be empty which is true so here stack. Peak is one and the current element at area of I is 8 so 1 is less than equal to 8 and stack is not empty so therefore this condition comes out to be true so the while loop will execute so here this condition signifies that for 8 it will see that there is no element in the stack which is greater than 8 so therefore it simply removes one from the stack it does stack do pop and why it does stack. popop because it sees that in the stack whichever element is present it is actually lesser than the current element which is eight so it discards one because for the rest of the array eight would be the next greater element but one cannot be the next greater element so let's say for four 7 is the next greater element for Seven 8 could be the next greater element but for any of the element one cannot be the next greater element because we have found one element which is actually greater than 1 which is 8 so therefore it discards The Element one by popping it out so one gets popped out as it's a while loop it again checks whether stack is empty or not so stack is empty so this condition comes out to be false and this V Loop will terminate and for element 8 we first check whether stack is empty so yes stag is empty which signifies that for the value 8 there is no next greater element towards its right so therefore this condition is true and into the result array at index I we store minus one because for it there is no greater element towards its right and then we will simply push eight onto the stack because eight could be the next greater element for the remaining array we will decrement I I becomes three 3 is greater than equal to Z so for element at index 3 which is is four we check that whether stack is empty or not so if stack is not empty it means there could be a chance that the next great element will lie in the stack so this condition comes out to be true stack is not empty and then we will provide a while loop we first check whether stack is empty or not so stack is not empty so this condition is true and we will do stack. Peak which will return as the value 8 because 8 is the topmost element so stack. Peak returns 8 we will check whether it is less than or equal to the current element which is four so this condition comes out to be false because 8 is not less than equal to 4 so this F Loop will terminate so if the while loop terminates at this condition it signifies that there is one element on the stack left and stack is not empty so this if condition also comes out to be false because there is element on the stack which means that four was not able to pop out it and it was able to find an element which is the first greater element towards its right so whatever is at the top of the stack we will directly store into the result Direct so at T index of result array we will store stack. Peak which is 8 so8 comes here directly so for Value 4 8 is the first next greater element towards its Right Moving ahead we will keep it as it is on the stack we will not touch it because four was not able to remove it because if we remove it then for 7 we will not able to find which is the first next crer element towards its right so we will keep it on the stack and we will push four on the stack like this and why we are putting four on the stack is because let's say for three though eight is the next greater element towards its right but four is the first next greater element towards its right so so therefore we need to still put four on the stack and we don't have to discard it we will decrement I I becomes 2 2 is greater than equal to zero we check whether stack is empty or not so stack is not empty so this condition comes out to be true we provide a while loop the first condition is St should not be empty so stack is not empty so this condition is true and stack. Peak which is four we will check whether four is less than equal to the current element which is three so this condition comes out to be false so therefore this while loop will terminate so which signifies that three could not pop four out of the stack which signifies that if stack is not empty then whatever is at the top will be the first next greater element for this index which is two so we directly store stack. Peak at index 2 which is four so S3 was not able to pop four out so this is the top most element if we do stack. Peak we will get four and we directly store four here so for three four is the first greater element towards its right and then we push three on the stack because let's say If instead of seven if the value would have been two so for two three would have been the first greater element towards its right so we can't discard three so we simply push it on the stack we'll decrement I I becomes 1 1 is greater than or equal to Z stack is not empty in the while loop the first condition is stack is not empty which is true stack has three elements stack. Peak which is three we check whether it is less than or equal to the current element 7 so yes this condition is also true so what 7 is actually doing it is actually popping out the elements which are lesser than it so that it reaches to an element which is actually greater than it so this vile does that this both condition comes out to be true so first it pops out three because three is lesser than 7 and for seven it could not be the first greater element towards its right so it pops it out stack is not empty and stack. Peak which is four now is less than equal to 7 so this condition is also true so for seven it will pop four also out of the stack because four cannot be the next greater element of s towards its right so four gets popped out stack is still not empty and stack. Peak which is 8 is less than equal to 7 so this condition is false now because 8 is greater than 7 so this value will terminate leaving only 8 into the stack and if there is some element on the stack stack is still not empty which means that for index one and element 7 we have found one next greater element towards its right which is tag. Peak which is 8 so we directly put 8 here into the result array like this using this assignment operator so friends here we saw that s actually popped out three and four from the stack because if we go beyond 7 whatever element we encounter for those element 7 could be the next greater element three and four cannot be the next Setter element eight could be a possibility which is already already in the stack which we have stored it here but three and four cannot be the possibility for the remaining elements towards it left so we directly discard three and four and we simply push s on the stack because seven can be a possibility for the remaining elements that it can become the next greater element for the remaining elements we will decrement I I becomes Z and 0 is equal to 0 so this condition is still true stack is not empty so this condition is true we provide a while loop stack is not empty and stack. Peak which is 7 is less than equal to 4 so this condition is false because 7 is not less than or equal to 4 so this while loop will terminate and if stack would have been empty it means for four there would have been no element on its right which would have been greater than four but stack has two elements so therefore whichever element is on the top which is seven we will simply assign it to the result array at I index so for four 7 is the first greater element towards its right 8 is also greater than four but s is the first element which this stack help us to figure out so we directly assign seven here and then we simply push four on the stack as there are no more elements left for I to travel but still we push four on the stack we will decrement I so when we will decrement I I will become minus1 it will reach here so minus one is not greater than or equal to zero so this for Loop will terminate because this condition comes out to be false and at the end we will simply return the result array so friends here you saw that how we can solve the next crer element problem using a stack now as stack is last in first out it actually help us in finding out the next get element towards right for any particular index so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update also please like this video and share it with your friends and colleagues thanks have a nice day hello everyone so in this video we are going to discuss a problem of valid parenthesis so in this problem we are given a string s now this string only contains the brackets which are opening and closing brackets so we can have round square and curly brackets we need to determine whether the input string is valid or not so an input string is valid if Open brackets must be closed by same type of bracket brackets Open brackets must be closed in correct order so let's say we are given with the input string like this and we need to find out whether this input string is valid or not so the input string is valid if Open brackets must be closed by same type of brackets so here you can see this is opening curly bracket this is opening round bracket Open brackets must be closed in correct order so here we have opening curly bracket and then we are opening round bracket so if we go ahead we have a closing round bracket so this must part is valid because this opening round bracket is closed by same type of bracket and this is also in correct order and at the end we have one curly bracket so this opening curly bracket is being closed by the same type of bracket and that to in proper order so this complete string is Val now let's say we are given input string like this this is opening curly bracket but it is closed by a different type of bracket which is the square bracket so this is not a valid string now let's say if you have input string like this we have a opening curly bracket it is followed by a opening round bracket and then we have a closing round bracket so this much part is valid because this closing round bracket is being matched with the opening round bracket but after that we don't have any character so we are left with one opening curly bracket it doesn't have its closing bracket of same type so therefore this is a invalid string now let's say if we have string like this so at the start only we have a closing curly bracket so therefore we can directly say that it's a invalid string because uh input string is valid where Open brackets must be closed by the same type of brackets and these Open Bracket must be in correct order so this is invalid because at the start only we have a closing curly bracket so how we can solve this problem is we can use a stack data structure now let's see the demonstration of this algorithm step by step using a stack so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here here we have a method is valid which takes the input string and returns a Boolean value true or false which states that this string is valid or not so first we will see the negative scenarios where we are actually returning false one is here here and here if stack is not empty so if we call this valid method with passing in one closing curly bracket followed by a opening curly bracket so s will be this string we will first create a stack so your stack is Leo data structure where element which goes last will be the first one to be removed so you can watch my stag tutorials to understand more about this data structure so here the main idea is to iterate each and every character of this string so first we'll convert this string into character array and then we will iterate it through the variable C so when we will call two care array method we get something like this we get a character array where each character is stored at a particular index now this for Loop will start with the closing curly bracket so C becomes the closing curly bracket so here as we know that the string is valid we must have opening brackets at the beginning and whenever we encounter any opening brackets we simply push it on the stack So currently here you can see that we have a closing curly bracket so this if block conditions comes out to be false because C is not equal to any of this opening bracket so the else part will be executed now in the else part the first thing we simply check is whether stag is empty or not so why we are checking whether stag is empty because it simply signifies that there is no character in the stack which is opening bra bracket and we have reached to the lse block and we have found that stag is empty it means whatever value c will have it must be the closing bracket so therefore we can directly return false and which is actually true because C value is closing curly bracket because if we have opening bracket then that must be pushed on the stack and stack must have some elements in it but if C is not equal to the opening bracket so in the lse part the first step we check is whether stack is empty or not because if stack is empty then we have one closing bracket and there is no element on the stack which we can pop out and match it with the closing bracket so we can return return false you can understand more on this in our upcoming examples So currently we return false because the input string is not valid it is actually getting started from the closing bracket now let's say if we are given with this string so as becomes the opening curly bracket and the closing square bracket we create the stack we create the car array so for the first iteration C value will be the opening curly bracket so here you can see that for the first step till zero index the condition holds good because we have a opening bracket so C is actually equal to a opening curly bracket so we simply push C on the stack so this opening curly bracket comes on the stack now C moves to the next character which is closing square bracket C is not equal to any of this opening brackets so the else part will be executed now stack is not empty so this condition comes out to be false and the lse part will be executed so friends the main idea behind pushing the opening bracket onto the stack is in the lse part we will first Peak the topmost element so when we will call stack. Peak whichever element is on the top of the stack that value will be returned from this method So currently top will point to the opening curly bracket like this and why we are actually looking into the topmost element on the stack is because we need to check whether this opening bracket is actually closed by the same type of bracket or not so here you can see now we provide three conditions here separated by R so if any of the condition comes out to be true then this if block will be executed so here simply the condition is if on the top of the stack we have a round bracket and the current ly visiting element which is C is closing round bracket it means it's a match and similarly with the other two brackets so therefore we are looking for the topmost element in the stack because we have to match the brackets of the same type in correct order so here you can see top is equal to the opening curly bracket but C is equal to closing square bracket so therefore no condition comes out to be true so this overall if condition comes out to be false so the else part will be executed and we can return false because for this opening curly bracket the element which is next to it is closing square bracket which makes it a invalid string so therefore we can return false directly moving ahead let's say we are given with this string so s holds this string we will create a stack we will generate the car array like this so the first C value will be the opening curly bracket in the first if condition we are checking that if we have a opening bracket then we simply push it on the stack so C is actually equal to the opening curly bracket so we push it on the St stack now we have pushed something on the stack so in the next iteration c will become the opening round bracket now C is equal to opening round bracket so we know that we need to push it on the stack so this opening round bracket comes like this now C moves to the third character which is the closing round bracket so C is not equal to any of the opening bracket so this if condition comes out to be false in the else part we first check whether stack is empty or not so if stack is empty it means we are straight away getting one closing bracket and it is not having any of its opening bracket before that so we can directly return false if the stack is empty so currently on the stack we have two elements so the else part will be executed first we will check out for the top element by calling stack. Peak so if we see the top of the stack we will have a opening round bracket so top will be equal to opening round bracket now here you can see that top is equal to opening round bracket and C is equal to closing round bracket so therefore it's a match here you can see it's a match so the element on on the stack which is top is this and the current element C is this so it means we have found one matching brackets which are opening and closing and are in correct order so therefore the first if condition comes out to be true and the overall if condition comes out to be true because we have a r operator here so it means we have found one match which is the correct match so we can simply pop this element out because it's matching pair we have already found so it gets popped out so now here you can see that we have visited all the elements of this car array so this for Loop will terminate and here you can see at the end what we written is we check whether if stack is empty or not because if stack is empty it means we have found all the proper matching brackets and the string is valid but here here you can see in the stack we are left with one opening curly bracket for which we didn't find its same type of bracket so therefore stack is not empty so stack. empty returns false so we can directly return false stating that this input string is not valid now here we will see one more example which is a proper valid string so as becomes this we create a stack we create the car array like this and in the for Loop c will point to the opening curly bracket first so this condition is true so we can push C on the stack so this opening curly bracket is on the stack the next element is the opening round bracket so C becomes opening round bracket C is equal to opening round bracket so we can push it on the stack like this now we'll move to the next character so C becomes the closing round bracket so this overall condition is false because C is not equal to any of the opening brackets stack is not empty so this condition comes out to be false now first we will see the topmost element on the stack by calling stack. Peak so top will become equal to closing round bracket like this and then we will provide a if condition we will check whether top is equal to any of the opening bracket So currently it's opening round bracket and the current element which is C whether it's the same type of closing bracket so your C is equal to closing round bracket like this so This Much string is valid so the first condition comes out to be true so we simply pop this element out because its matching bracket has been found moving to the next character now C becomes the closing curly bracket this condition is false because we have a closing bracket stack is not empty we will first see the topmost element on the stack by calling stack. Peak so top will be equal to the opening curly bracket like this so the first condition is false because top is not equal to opening round bracket and C is not equal to to closing round bracket the second condition comes out to be true because top is equal to the opening curly bracket here and C is equal to closing curly bracket so it looks something like this this is our top and this is our currently element which is C so it's a match of the same type of brackets so this much part is valid so this condition comes out to be true so the overall if condition comes out to be true so we will simply pop this element out now we have visited all the elements in this SC array so this for Loop will terminate and here you can see at the end stag is empty so stag do is empty method will return true so therefore it means that this is actually a valid string so friend this was all about the problem valid parent paresis where we can figure out that whether brackets are actually balanced or not that is the opening brackets is being mashed with the closing bracket of the same type and also in the correct order so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to represent a q in Java so friends what is a q so here Q is a data structure which is used for storing the data and it's an ordered list in which insertion are done at one end called as rear and deletion are done at other end which is called as front so friends if you see an example example below then this is a link list where the first node is referred by the front variable and the last node is referred by the rear variable so here Q follows a basic structure where insertion are done at one end which is called as rear so whatever we insert in the queue we insert at the end which is referred by rear and whatever the deletions are done we use the front variable to make the delete so basically is a type of Link list where we keep two pointers one is front and one is rear and usually the front points to the first node and rear points to the last node and this link list follows a certain pattern in which whenever you want to insert a element we basically insert at the end and whenever we want to delete any element we usually use the front end so friends Q is also called as fifo list which is first in first out list so here what we do is the first element inserted is the first one to be deleted so friends Q is a list which follows certain restrictions that whenever we want to insert an element we will use the rear end and whenever we want to remove an element we will use the front end so therefore we can see it's a first node so it means this node was inserted first and if you see whatever the notes coming after that follow a sequence of removal therefore it's termed as fif which is first in first out so the node inserted first will be the first one to be removed so let's quickly see the demonstration how Q works so friends Q is a list which follows certain restrictions that we will enter the notes from one end and we will exit the notes from other end so therefore so therefore it forms a fif list where the element inserted first would be the first to be removed so let's see a quick demonstration so initially if you see Q is empty and there are no notes so when a q is empty front points to null and the rear points to null now if you want to insert any element into a que we basically use an inq operation now let's say we use an inq operation and we want to insert a node having data is 20 so here if you want to insert this node having data s 20 then we know that there is only one end where we can insert so it looks something like this and once this node is inserted the front and the rear both points to this particular node and as in previous slide we discuss front points to the first node and the rear points to the last node so friends currently the Q has only one node therefore front and rear are both pointing to this particular node because this is the first and the last element both now let's suppose we want to insert one more element having data as 10 so it would look something like this that elements are inserted at one end and we basically use the rear end to insert the element so when we insert an element now rear will point to the node which was last inserted moving ahead now let's say we want to insert a node having data as Shi so it would look something like this so when the node is inserted now re points to that particular node so friends here currently Q is three nodes 20 10 and 15 where 20 is the first node therefore it's being referred by front node and 15 is the last node therefore it is being referred by the rear node now let's say we want to remove an element so in order to remove an element we use the DQ operation so friends as we know that Q follows a basic restrictions that the nodes are inserted at one end and they are removed from the other end so in order to achieve that what we do whenever we insert any element we we usually insert it using the rear end and whenever we remove an element we use the front end so let's see when we call this DQ operation so the node which is referred by front will be removed first so it would look something like this and once the node is removed now front will point to the node just after it and suppose we again call DQ operation so it would look something like this and now front will point to the node 15 and if we again call a DQ operation so it would look something like this and now as there are no element into the Q therefore front and real both will point to null so friends here we saw that when we inserted three nodes 20 was the first node so therefore 20 became the first node to be removed so therefore it follows a fif structure that the node which was inserted first was the first one to be removed so basically Q follows this restrictions that that whenever a node is inserted first it becomes the first one to be removed so friend this is how we represent a q so in my next tutorial we will see how we can Implement a queue in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to implement a queue in Java so friends in my previous tutorial we discuss what is a queue and we know that it's a linear data structure used for for storing the data and here we also saw that it's an ordered list in which insertion are done at one end which is called as rear and deletion are done at other end which is called as front so in my previous tutorial we discussed how we can use this front and rear end to insert and remove the elements from a queue and we also discussed that Q is a fifo list which is first in first out that a node inserted first will will be the first one to be deleted so friends in this tutorial we will discuss how we can Implement a queue so basically when we Implement a queue we usually keep two list node by the name front and rear we insert using the rear list node and we remove using the front list node so friends let's go to eclipse and see the implementation of a queue so friends here I have created one class by name Q having an empty main method so in this class we will Implement how a queue works so friends in order to implement a queue we need to create few instance variables so as we discussed in slide so Q contains a front node and a rear node so those two nodes are basically of typ list node so here we'll create create one list node and we'll give name it as front we'll also create one more list node and we'll give it a name as rear and we'll also create one integer variable now this integer variable will store the size of the Que so friend as we discussed in slide that Q is basically a list therefore internally it uses list notes so here we will create one inner class of type list node so private class list node and friends as we discussed in our previous tutorials how we can represent a list node so in a list node we basically keep two things one is the data part and other is the reference to the next list node so private int data and other is the reference to next list node we will also create one Constructor public list node now this Constructor will take in a data part so int data and we'll simply assign this data to this do data and this. next will have null value so friends here we saw a q has two list noes one is represented by front and other is represented by rear below we'll create one method as public int length now this method will return us back the length of the que we'll also create one Boolean method public bullan and we will give it a name as is mty so friend this method will return us a Boolean value that whether a q is empty or not so we'll simply return return length is equal equal Z so if length is zero then this method will return as true and if length is greater than Zer then this method will return as false so friend this is how we Implement a q using the front front and rear list node in my next tutorial I will demonstrate how we can insert an element into a queue and how we can remove an element from a queue so friends I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will continue with the implementation of a queue in Java and in this tutorial we will discuss how to insert an element in a queue in Java so friends in this tutorial we will discuss how to insert an element into a queue and if you see below is the algorithm to insert an element into a q in our previous tutorials we discussed that Q is a type of a link list which has some restrictions that it is considered as fifo list which is first in first out list so by first and first out we mean the element inserted first would be the first one to be removed and in this tutorial we will discuss how to insert an element into a q so let's see the demonstration of this algorithm step by step so friends when we initialize a q we know that the Q is empty and there are no elements so when a q is empty and there are no elements so in this situation the front node and the rear node both points to null so here you can see currently Q is empty so therefore front is pointing to null and rear is pointing to null and we also know that as Q is empty and there are no notes so the length is also zero so friends let's suppose we want to insert an element having the data as 10 so we will call inq function so let's see the demonstration how this method works now as we call the inq method and we pass the value of 10 10 into it we know that the data is equal to 10 So currently data is pointing to 10 moving ahead now in order to insert an element into a queue what we do we first create a temporary list node having the data which we have passed into the method so it would look something like this now here you can see that it is a basically list node having data as 10 where temp is point pointing to this node and it next is pointing to null so this is the node that we want to insert into a queue moving ahead now in the first step we check whether the Q is empty or Not So currently if you see front is pointing to null and rear is also pointing to null and length is zero so therefore the Q is empty so the condition in if block comes out to be true now in the F blog what we do in order to insert this temporary node into the que we simply assign the value of temp to front so it would look something like this so now front is pointing to this node having data as 10 so friends in our previous tutorial we discussed that when a q is empty and if we want to insert an element then after an insertion we know that the Q is only one element therefore from front and rear both point to that particular node so here we simply check that whether Q is empty and if it is empty then we'll simply assign the value of time to front so you can see now front is pointing to this particular node moving ahead now after the F else block we simply assign the value of temp to rear so friends here we know that after the insertion of this node Q is one Element so if the Q is one Element then we know that front and rear both point to that particular node because the Q contains the only node which is first and the last node both so therefore in this step it would look something like this that rear is pointing to the node having data s 10 and front is also pointing to the node having data s 10 moving ahead now in the last step as we have inserted this node into the Que we know that length of this Q is 1 so therefore we will increment the length by one because this Q contains now one element moving ahead so when this method gets executed the Q looks something like this the front and rear both point to this particular node and whose next is pointing to null and we also know that length is one now suppose if you want to insert one more node having data is 15 so let's see the algorithm once again so in the first step we know that data is 15 moving ahead so friends in order to insert the node having data as 15 first we'll create the temporary list node which has data as 15 and whose next will point to null so it would look something like this so here you can see temp is pointing to this list node whose data is 15 and whose next is null moving ahead now in the if blog we will check whether Q is empty or Not So currently Q has one node therefore it's not empty so the lse part will be executed so in the lse part what we do we simply assign the value of temp to rear. next now friends in our previous tutorial we know that whatever the notes we want to insert into a que we always use the rear end of it this is because Q follows some restrictions that the notes are inserted at one end and they are removed from the other end so in this case if we are inserting a note then we are always using the rear end so therefore we are assigning the value of temp to rear. next So currently if you see rear next is pointing to null and if you want to insert this node having data is 15 we need to remove this link and we need to point this link to this temp node therefore we are assigning temp value to rear. next so it would look something like this now first this link will be removed and then we'll create one link from first node to Second node so it is nothing but we are assigning value of 10 to rear next moving ahead so friends we know that we are inserting element at the rear end and this rear node will point to the last element of the que So currently we have inserted this node into the que but we are not pointing rear to this node because this is the last node so in order to do that we are simply assigning value of temp to rear so it would look something like this so now as you can see front is pointing to the first node and rear is pointing to the last node and this is the property which Q follows moving ahead now as we have inserted this node into the Q we know that the Q is now two elements therefore we'll increment the length by one so now length becomes two and finally when this method get executed the Q looks something like this that front is pointing to the first node and rear is pointing to the last node and we have inserted this node using the rear end moving ahead now let's suppose we want to insert one more element having data as 20 so in the first step we know that data is 20 moving ahead now in order to insert data is 20 we will first create a temporary list node so now this temp node is pointing to a list node having data as 20 and whose next is pointing to null moving ahead so the F blog we will check whether Q is empty or Not So currently Q is not empty because length is two and we have two notes already in the que so the else part will be executed so in the L part what we do we simply assign the value of temp to rear. next so we are doing this step is because we want to insert this node into the que and we know that the elements are inserted into Q at one end which is called as rear end so therefore we are assigning value of temp to rear next So currently rear next is pointing to null and in order to insert this node into the queue we we have to remove this link and we have to assign this link to Temp node so therefore we are simply assigning value of temp to rear. next so it would look something like this so first this link will be gone and then we'll assign the value of temp to rear next so it would look something like this moving ahead and now as we have inserted the node into the que we know that the node with the data 20 is the last node so therefore we'll simply assign the value of temp to rear because we know that rear points to the last node in the que so it would look something like this moving ahead and in the final L will increment the length by one because now we have three nodes so the length becomes three and once this method gets executed Q looks something like this that front points to the first note and rear points to the last note and we also know that length is three because we have three nodes into the Q so friends this was the demonstration of how to insert an element into a queue now let's go to eclipse and see the working code so friends in my previous tutorial I had created one class by name q and into that queue we created two list node one by name front and one by name rear and we also created one integer instance variable by name length so basically list note front will point to the first element into the queue and list note rear will point to the last element into the que and as we are discussing the inq operation we know that we are inserting the element from the rear end and we have also discussed that Q has few methods by name length which was actually returning the length of the que and when Boolean method is empty which was rning true if the list is empty and false if the list is not empty so in this tutorial we will simply see how we can insert an element into a que so we'll create one method as public void inq and this method takes in a integer data now friends in the first step we'll create the temporary list node and we'll pass the data into the Constructor so in the first step we are creating the temporary node which we discussed in the slide moving ahead we'll provide an F Els block so in the if we'll check that is Q empty or not so if the Q is empty we are simply assigning the value of temp to front and if the and if the Q is not empty then we are simply assigning the value of temp to rear. next moving ahead after refel block we are simply assigning the value of temp to rear as we discussed in the slide and in the last step we are incrementing the length by one so friend this is the inq operation which we discussed in the slide and in this class I will also create one Constructor for the Q so public Q so when we initialize any Q we know that front is pointing to null and rear is also pointing to null and length is zero so friends in order to demonstrate how in Q operation works I will create one more method which will actually print the elements of the queue so here I create one method as public void print and in the print method we'll check if if Q is empty it means it has no node to print so there therefore we'll simply return from the method and if the Q is not empty then we'll Traverse each element into the Q and we'll print it on the console so in order to print the elements on the console we'll first create a list node current and we'll assign the value of front to it so here as we know that we are implementing a cube with a link list therefore we are printing the element from the first node to the last node so therefore in order to Traverse each and every node we are first initializing the current with the value of front and then we are providing a while loop and inside this V Loop we are traversing the current till it becomes null so in the first step we are simply printing the elements on the console so current do data and then we are simply incrementing current to its next position by assigning current. next to current and after the current encounters a null value then we are simply printing null so friends let's test the working of inq method in the main method so here first I will create an of Q and when we create an instance of Q we know that Q is empty therefore front and rear both points to null so friends let's insert few elements into the Q so we'll call inq method and we'll pass the value as 10 and let's say I print the Q on the console so if I run the code now so you can see it printed 10 and null so as the Q was empty when we inserted node having data is 10 so this was the only node so therefore it printed 10 and null now let's insert one more node and if I give the data as 15 and if I run the code now so you see it printed 10 then 15 and then null so here you see Q has two nodes where the first node is pointing 10 and second node is pointing 15 and here you can see we are inserting the node at the one end which is the rear end so therefore first 10 was inserted and then 15 got inserted so if I insert one more node say 20 and if I run the code now so you you can see that using the rear end we are inserting the element at the end so friends currently Q has three elements with the data is 10 15 and 20 and in this tutorial we discuss how to insert an element into a queue so friends in my next tutorial I will discuss how we can remove an element from the queue and we'll discuss the DQ operation I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will continue with the implementation of the queue in our previous tutorial we discussed how to add an element in a queue in Java so in this tutorial we'll discuss how we can remove an element from a queue in Java so friends in my previous tutorial I added three elements into the Q by data is 10 15 and 20 so in this tutorial we will discuss how we can remove an element from a q which is nothing but a DQ operation so here I will take the same example and you can see that Q has three elements where front is pointing to the first node and rear is pointing to the last node and length is three so here you can see this is the algorithm for a DQ operation now let's see the demonstration of this algorithm step by step now in the first step we will check that whether Q is empty or Not So currently if you see length is three and we know that the Q contains three notes therefore Q is not empty so the condition in if blog comes out to be false now friend as we want to remove an element from a q so here you can see the return return type of DQ method is integer type we are actually removing an element from the queue and we are sending back the data part of it so in order to store the data somewhere we are creating an integer variable by name result and we are storing front do data into it so friends in my previous tutorial we discussed that Q is a list with few restrictions where the elements are inserted at one end which is the rear end and elements are removed at one end which is the front end so friends the Restriction which we impose on a list makes it a Q and therefore the Q is called as fifo list which is first in first out so here you can see by first in first out we mean the element inserted first would be the first one to be removed so in my previous tutorial we discussed when we inserted the elements into the que we inserted first 10 then we inserted 15 and then we inserted 20 using the rear end now in order to remove an element we know that 10 was inserted first so now 10 would be removed first so this is nothing but a fifo property first in first out so let's see how we can use the front end to remove the nodes which are inserted first so here after this line gets executed results hold the value of 10 because the node 10 was the node first inserted into the Q therefore this node will be removed first moving ahead now friends in order to remove this Noe from the queue we know that it is being referred by this front node and if you break the link from front to this node then this node can be removed easily so in order to do that what we are doing we are simply assigning the value of front. next to front so here you are simply assigning front next value to front so that once this node is removed 15 becomes our new front so therefore we have simply assigning the value of front dot next to front so it would look something like this moving ahead then we are checking that the front is equal to null or Not So currently you can see front is pointing to the second node therefore it's not null so the condition in if blog comes out to be false moving ahead so friends as we have removed the reference of front from from this node therefore this node will be garbage collected and you can see once this node is removed we will decrement the length by one so currently the length is three and after the removal of this node length becomes two so we simply decrement the length by one moving ahead and in the final step we'll simply return the value stored in the result so Friends when the DQ method is executed the Q has two elements and length is two now friend let's suppose we call DQ method once again so here first we check whether the Q is empty or Not So currently Q has two notes therefore it's not empty and then we'll simply store Front do data into the result so it would look something like this that we are storing the data into the list node which is being pointed by the front so now result contains the value is 15 moving ahead now in order to remove this node from a queue we have to break this link because if front is referring to this node then this node would not be removed so in order to break this link we are simply assigning front. next value to front so it would look something like this moving ahead then we are checking whether front is equal to null or not so front is pointing to this third node therefore it's not equal so the condition in if block comes out to be false and here as we have removed the link of front to this node so now this node has no reference to it therefore it will be removed easily we know that now Q has only one element therefore we will decrement the length by one moving ahead and in the final step we'll simply return return the value stored in the result which is 15 so Friends when the DQ method is executed Q is only one element where front and rear both point to that particular element because this is the only element left now if we suppose call DQ again so first will check whether Q is empty or Not So currently Q has length one that means it has one node therefore it's not empty so the condition in if blog comes out to be false then we'll simply store the value of front. data into result because we want to return this value so now result will hold the value as 20 moving ahead now friends we need to take an special care when we removed the last last element from a que because if the Q contains only one element and if we want to remove that particular element then we need to break two links one is of front and other is of rear because if any of the link is referring to this node then this node will not be removed so therefore here we are simply assigning the value of front do next to front so it would look something like this so now front is assigned with its next value which is null moving ahead now we'll check whether front is pointing to null or Not So currently if you see front is pointing to null therefore the condition in ifog comes out to be true and as we discussed that we need to break both the links in order to free this node so therefore we'll simply assign the value of null to rear so now this link will be removed so it would look something like this so now front and rear both are pointing to null so friends as this node is having no reference therefore this node will be freed easily so once this node is removed we'll decrement the length by one because we know there are no elements left so we'll simply decrement the value of length by one so now length becomes zero because we have removed all the notes so in the final step we'll simply return the value 20 so friends once this method gets executed this node gets freed up and as we know that now front and rear both pointing to null therefore the list is empty and length is zero so friends if we again call DQ method then the first step we check whether Q is empty or not so here you can see front is pointing to null rear is pointing to null and we also know that length is zero therefore Q is empty so there are no elements left to be removed so the condition in if blog comes out to be true and we'll simply throw in no such element exception because there are no elements left to be removed so friends in this slide we discussed the demonstration of the DQ method now let's go to eclipse and see the working code so friends in my previous tutorial I created one class by name Q we created few instance variable of type list node one of which was front and other was rear we also created an integer variable which actually store the length of the queue and then we have created few methods one was length is empty and inq so basically we created inq method which could insert the elements into the que and here if you see and we also saw that we have added three elements and when we printed the queue it printed something like 10 15 20 so so I will take the same list and we'll perform DQ operation on it so first let's write the DQ method so public we know that the return return type of it would be integer so int TQ now the first step we do is we check whether the Q is empty or not so is empty now if the Q is empty we know that there are no more elements left to be removed therefore we throw an exception as no such element exception and we pass a string as Q is already empty moving ahead now we know that when we remove an element from a queue we are returning the data part of it so therefore we'll create a integer variable by name result and we'll store Front data to it moving ahead now as we have got the data of the front node we'll simply Traverse front to its next value by assigning front next to front and then we simply check whether front is equal to null or not so if front is equal to null we know that we have to make rear also null which we saw in the slide moving ahead now as we removed the node from a queue we have to decrement the length by one and finally we are returning the result so friend this is the code for DQ method whose demonstration we saw in the slide now let's test the working of this method so initially we have inserted three notes now now let's say I dq1 node and then I print the Q again so if I run the code so you can see when we inserted three notes first 10 was inserted then 15 got inserted then 20 got inserted so the insertion was at the rear end now when we are doing a DQ 10 was removed because we are removing a note from the other end which is the front end so thus Q is a fifo list where we insert the node at one end which is the rear end and where we removed the node from the other end which is the front end so now as you can see 10 was the first element to be inserted therefore it got removed first now if I call DQ again so here you can see 15 also got removed and if I call DQ once again so here you can see nothing got printed because we have removed all the elements from the queue and when we printed the list we can see when the list is empty we are simply returning from the print method so therefore nothing got printed and now his list is empty if I call DQ one more time and if I run the code we get an exception saying No Such element exception as Q is already empty so friend this was the working of DQ method so friends apart from this inq and DQ method Q also has two more methods by name first and last so when we call the first method we get the value stored at the node which is being referred by by front and when we call the last method we get the value stored in the list node which is being referred by the rear so here we simply create public int first so here first we simply check that whether Q is empty because of Q is empty then we know that front and rear both points to null therefore we check whether Q is empty or not and after this check we simply return return value stored in the front so we simply return return front. data and we also write one more method say last which is very similar we'll first check whether the Q is empty or not and if the Q is not empty then we'll simply return rear. data so friends let's test the working of first and last method so here I will just remove this thing so we inserted three nodes by Valu is 10 15 and 20 so if I run the code so you can see front is pointing to a node having data as 10 and rear is pointing to a node having data is 20 asem so for simply print Q DOT first and q. last and if I run the code so you see it printed 10 and 20 because 10 is being referred by front and 20 is being referred by rear so friends in this tutorial we discussed about the DQ operation we discussed about the few of the methods like first and last so this was basically all about the implementation of Q I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day hello everyone so in this video we are going to see a problem that how we can generate binary numbers from 1 to n so here you can see that the question is generate binary numbers from 1 to n using a q so binary numbers can be generated by various ways but here we will take a q data structure and we will generate the binary numbers from 1 to n where n will be the value provided to us so let's say value of n is three so the output would be a resultant array of string type and the binary numbers from 1 2 N will be 1 1 0 1 1 so binary number 1 corresponds to 1 1 0 corresponds to 2 1 1 corresponds to 3 and similarly if n is 5 then we need to return like 1 2 3 4 and 5 so from 1 to n so these are the values in decimal number system and its corresponding B numbers are 1 1 0 1 1 1 0 0 1 0 1 so here first we will see the conceptual overview that how we can generate the binary numbers from 1 to n so let's say we have provided with the value of n is 5 so the binary numbers we need to return return is 1 1 0 1 1 1 0 0 1 0 1 so this value corresponds to one this to two this is three this is 4 and this is five so you can watch the videos and understand how this conversion happens from a binary number to a decimal number so here let's take one example let's say we are given with this binary number 1 0 1 so this is at zero spot this is at one and this is at two so what we do is this is binary number which is having 0 and 1 which is two numbers so we simply take this digits value multiply it by two and do their sum and we will get the decimal number so to convert this number into a decimal number what we do is we take this digit value which is 1 which multiplied with 2 to the power this value we do sum we take zero multiplied with 2 to the^ 1 we take one multiplied with 2 to the power 2 so this give us 4 this give us 0 and 2 to ^ 0 is 1 so 1 into 1 gives 1 so this gives value as five so you can Google the stuff or watch the videos where there are programs where we can convert from one number system to another number system So currently our problem is that we are given with a value of N and we need to generate the numbers from 1 to 5 so we need to generate something like this 1 1 0 1 1 1 0 0 1 0 1 so how we can do is so here you can see that at the start we directly have one number one and its binary representation is also one so the first number is we already know it's it would be one now here as we need to return the generated binary number in the form of string what we do is if I append 0 to it and if I append one to it I will get 1 Z here and 1 one here so if you see closely if we are appending zero we will get our next number if we are appending one we will get our third number so the first number we know that it will be one if we append zero we'll get the second number if we append one we'll get the third number now what about this fourth and fifth so here we do the same steps if we upend zero and if you append one so to 1 0 it becomes 1 0 0 and if you app one we'll get 1 01 now let's say if we would have have n = to 7 so the next numbers would have been 1 1 0 for 6 1 1 1 for 7 so how this numbers would have come we would have taken 1 one appended zero appended one so this would have given 1 1 0 1 1 1 so this is how the binary numbers are generated but the main problem is for the first digit we know that this is one we can append zero and one and we get 1 0 1 1 but how about other numbers how we will get this 1 Z and 1 one in sequence so that we can append 0 and 1 to 1 Z and get the next elements and then upend one one with zero and one to get the rest of the elements that also in sequence and this chain can go on like this so we need to maintain a certain order like this should come first then 1 Z should come then 1 one should come and then when we are doing one zero we to upend like this then we pick one one we upend like this and here also we'll go in this Direction only we take 1 0 0 we'll append zero and one we take 1 0 1 we append 0 and 1 to get the next binary numbers so this similar kind of structure or the sequence can be maintained y q so here in a q which is first in first out so the L element which is inserted first will be first one to be removed so here we are directly putting one and then we remove one so when we remove one we have that element we can append zero and one we will get 1 0 and 1 one so first we will put 1 0 then we will put 1 one so in the next iteration we will take 1 Z out we will append Zer and one and into the cube we'll put 1 0 0 first like this and then 1 1 and then in the next iteration we'll pull out 1 one so while pulling out 1 one we are actually getting the generated numbers but for the rest of the numbers we will append 0o we'll get 11 1 0 we'll put it into the Q we'll append 1 to 1 one and we will put 1 1 1 into the Q so this chain goes on and the numbers are generated so let's see the demonstration of this algorithm step by step so here is the algorithm let's say we call generate binary numbers which is this method we pass in the value of NS 4 so we need to generate four numbers from 1 to 4 so the first number will be one then it will be 1 Zer then 1 1 and then 1 0 0 so let's see the demonstration of this algorithm that how we can generate these four numbers so n is four first we will create a result array because this is the result array which we need to return from this method and this is of string type so the length of this array would be n so result array will have four elements because we need to return this four generated binary numbers we know that we need to use Q so we will initialize Q so Q is an interface and its concrete type is a link list so it looks something like this so for the first number we can directly offer one into the Q because we need to generate the binary numbers from 1 to n so we directly put a string one into the Q because this Q is of string type so one comes into the CU like this and now in order to fill the result array we are providing a for Loop which will go from zero index to a index n minus one which is value of n is 4 4 - 1 which is 3 which is the last index which is third index so I will start from the zero index and as we discussed we already know the first element so we simply pull the element from the Q and provide it into the result array like this at index I so when we will pull the Q it only has one element so one was entered first so this will be the only element to get exit first because Q is fif for data structure first in first out the element which enters first first will be first to be removed so one will be pulled out and simply provided to the result array at zero index because I is pointing to zero so this gets pulled out and one comes here so this is nothing but a string like this because we have created an array result of string type so for timing I'm just demonstrating it like this without double quotes and we know that once we get our first element like this we can append zero and we can append one to get the next two elements which is our N1 and N2 so string N1 can be generated by appending zero so N1 becomes 1 Z 1 appending 0 will give 1 Z and one appending one will give 1 one so N1 becomes 1 0 and N2 becomes 1 1 1 appending with 1 will give 1 one so N2 becomes 1 one and we know that after generating N1 and N2 we will put them into the Q in the respective sequence N1 will go first and then N2 will go so first we will offer N1 so 1 Z will go into the Q and then we offer N2 which is 1 one so now our Q has two elements 1 Z and 1 one so after placing the first element at its correct position in the result array we will increment I I becomes one which points to index one now in order to fill the result array at particular index which is one we know that we need to pull the element out because we know that the next element is 1 Z which we need to put it into the result array so whatever elements we are putting into the Q they are in proper sequence so the next element will be 1 Z so this number will be generated 1 Z we will pull that out and put it into the result array at index one 1 Z comes out we get string 1 Zer here and so here you can see that after we are getting this string out we know what that string is so now for the next elements we can append zero and 1 so we get 1 0 0 and 1 0 1 and we can put this Two element directly into the Q so first we will generate N1 and N2 so result of I will give 1 Z we will append zero so N1 will become 1 0 0 and N2 will become 1 + 1 will give 1 1 like this and then we will simply offer N1 and N2 into the que because we need to put them in proper sequence so that this binary number generation is done in proper order so so 1 0 0 which is N1 it will go into the Q and then we will offer N2 which is 101 so this will go into the Q now this element is generated properly so we will increment I now I will point to two which is the second index to fill this value we'll first pull the element from the Q which is 1 one and assign it to the result array at index 2 so 1 one will come out and one one will come here so here in order to create space we will simply shift this IID so these are still in q but we have just shifted it I so that space is created here for the other elements to go in so we have identified one element 11 one here so we got 1 one we know that to generate the further elements we will append 0o and append one so will give 1 1 0 and this will give 1 1 1 we will generate both of these numbers N1 and N2 so N1 becomes 1 1 + 0 which will give 1 1 0 and N2 will become 1 1 + 1 1 1 1 and then we will offer both the elements into the Q so first 11 1 0 will go and then 1 one one will go we have filed this position so we will increment I so I will now point to the third index and how we can fill this we will simply pull the element from the Q which is the first element which got entered first so one got entered first before this rest of the three elements so 1 0 will be pulled out and it will be assigned to the result array here at the third index like this so friends here the algorithm is ended because we have generated the integers from 1 to n so this is 1 this is 2 this is 3 and this is four 1 2 4 because value of n is four but in order to demonstrate how these further numbers are generated we'll simply see the rest of the algorithm so whatever the number we just pulled out which is 1 0 it will help us in generating the further elements so 1 0 0 0 which is this part I'm showing it here we will append zero we will append 1 so N1 becomes 1 0 0 + 0 so 1 0 0 0 like this and N2 becomes 1 0 0 + 1 which will give us 1 0 0 1 and here we have got 1 0 0 0 like this and similarly we will off for both the elements into the Q so 1 0 0 0 will be our N1 and then we will offer N2 which is 1 0 1 like this so This binary number addition will go on like this but here now when we will increment I I will become four and four is not less than four so this for Loop will terminate and though we have elements in the Q but we have figured out all the elements from 1 to n so we will simply return the result so this result will be a string array having 1 1 0 1 1 1 0 0 the four elements from 1 to n which is four so friend this was all about the algorithm that how we can generate binary numbers from 1 to n using a q so your Q place a very significant role because this data structure is first in first out the element which got inserted first will be the first to be removed so this property makes us easy to generate these binary numbers by just appending 0o and one so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to represent a binary tree in Java so friends first we will discuss what is a tree data structure so here you can see that we are given a tree a tree is a nonlinear data structure which is used for storing the data and it is made up of nodes and edges without having any cycle so here you can see that we represent a tree through nodes and edges so here you can see the nodes are connected to other nodes through edges so friends tree is basically a nonlinear data structure without having any cycle so you can see that nodes are connected to each other but they never form a cycle so here if suppose six is pointing to 9 so therefore you can see that it will form a cycle so therefore this representation is not a tree because in a tree you will find notes having edges to other notes but you will never find a cycle and you can always think of a tree in the form of a hierarchical structure and also you can see that each node in a tree can point to n number of nodes in a tree so here you can see the node having data as one is pointing to the three nodes by data as 2 9 and 3 so there can be n number of nodes in a tree which can be referred by any node so usually tree is way of representing the hierar cular structure where the parent node is called as root so whenever we represent a tree usually the first node which is the parent of all other notes is generally referred as root and you can see that it has many levels of additional notes so so friends in the tree you can see that one is the parent of all the nodes below it and it's generally referred by the root because this is the root of the tree and whatever the edges are coming out from this root it's pointing to the other nodes and here you can see that this structure can go to many levels and also a node who is not pointing to any other node is generally called as Leaf so here you can see that node one is a parent of 2 9 and three node two is parent of four and five and node four has no Childs therefore this is called as Leaf node similarly five is a leaf note six is a leaf Note S is a leaf note N9 is a leaf note because they don't don't have any childrens moving ahead so friends what is a binary tree so friends a binary tree is a special kind of a tree where each node has zero one or two childrens and not more than that can have zero childrens one children or at Max two childrens so here in the below diagram you can see as root is the parent of all the nodes it's having two childrens with data two and three the node two which is parent to four and five has two childrens four and five and at the last you can see node four which is a leaf node has zero childrens so friends similarly a node can have one children and the other children can point to null so friends a binary tree is basically represented by a tree node so here you can see a tree node consist of three things one is the data part which actually holds the data as you can see the data is like 1 2 3 6 7 4 5 and it is a pointer to the left node and a pointer to the right node so these pointers are basically of type tree node itself so here you can see the node having data as one is a basically tree node and whose left is pointing to the node two and whose right is pointing to the node three so therefore a binary tree having a tree node consist of only three things one is the data part one is the pointer to the left tree node and one is the the pointer to the right tree node so basically the way it represent a binary tree in the graphical form is something like this that it contains the data which you can see here and two edges coming out of it so here you can see this is the left Edge and this is the right Edge and we represent this age through the left and right pointers moving ahead so as we discussed know previous slide that a binary tree is basically represented internally through a tree node so friends a structure of tree node is something like it contains data it contains pointer to the right tree node and a pointer to the left tree node in an actual tree and Below you can see the Java code for representing a tree node so it contains a data and here I have taken this data in the form of integer and which can be any generic type and it contains a tree note left which actually points to the node which is just left to this particular node and one tree node right which actually points to a tree node which is just right to it and basically it has one Constructor which takes in a data part so whenever you initialize a tree node we usually pass the data which we want to store into it so usually when a node tree node is created so data which we pass into the Constructor is stored in the data variable and left and right at the time of initialization usually points to null and later on we make them refer to the other tree notes moving ahead so let's quickly see a demo how we can create a binary tree so when we initialize a binary tree the root is actually pointing to null and this root is also a type of tree node now let's say we have created one tree node having data as one and whose left and right is both pointing to null and which is referred by this temporary variable so let's say we want to insert this temp into the binary tree so what we do we simply assign the value of temp to the root so it looks something like this so when we insert one tree note usually root points to that particular node because this is the only node into the tree now let's say we create one more node having data as two and whose left and right both pointing to null which is referred by this temporary node and if we want to insert this node into the tree we know that root is already pointing to the node having data as one so one thing we can do here is we can either point Point root left to this particular node or root right to this particular node so either way we can do so let's say we assign temporary node value to root left so it would look something like this so now here you can see this is a binary tree having two nodes where root is pointing to the node having data as one and whose left is pointing to a node who having data is two and here you can also see that root right is pointing to null and left and right of root2 is pointing to null now let's say we want to insert one more node having data as three now here we can insert this node into a binary tree at three places one is at the roots right and other two places are nodes two left and right so basically we can place this node three into this three places which is pointing to null so let's say we insert it at Roots right so it would look something like this so now here you can see root is having data as one and whose left and right both are pointing to a node having data as two and three and suppose we want to insert one more node then we can insert it in at the four places now so those four places would be two's left two's right and three's left and three's right because those four positions are pointing to null so friends in this tutorial we discussed how to represent a binary train ja Java and we also discussed the structure of tree node so friends in my next tutorial I will be discussing how to implement a binary tree in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss how to implement a binary tree in Java so friends in my previous tutorial we discussed how we can represent a binary tree in Java and we also discuss the structure of tree node in a binary tree so friends in my previous tutorial we discussed that binary tree consist of a root node which is of type tree node and usually this root node keeps the hold of all the nodes in the binary tree we also discussed that the tree node consist of a data part and it contains two pointers one is left pointer and one is right pointer so this left pointer is pointing to the left tree node and the right pointer is pointing to the right tree node so friend this is how we store the data into tree node and we usually use left pointer and right pointer to hold the left tree node and the right tree node and Below you can see the Java code to represent a tree node so here you can see it has three things one is the data part one is the pointer to the left tree node and one is the pointer to the right tree node and here you can see we can store any generic type of data into a tree node and below is the Constructor of tree node where we actually pass the data so this data part whenever we initialize a tree node get stored into the data variable so friends let's go to eclipse and see the implementation of a binary tree in Java so friends here I have created one class by name binary tree which is having a main method so let's Implement a binary tree into this class so friends in our previous slide we discussed that a binary tree consist of a root node which is of type tree node so first we'll create an instance variable of type tree node and we'll give name to it as root because this root node will hold all the other nodes of a binary tree and in order to represent this tree node we'll create an inner class by name tree node so private class tree node so as we discussed in the previous tutorial that as it is a binary tree therefore it will have two pointers one is pointing to the left tree node and another is pointing to the right tree node so therefore we'll create two pointers of type tree node as left and right and this tree node along with holding the left tree node and the right tree node it will also hold the data so we are creating an integer type and which will actually store the data so this can be any generic type not supposingly of integer type we can store any data into this tree node so in this tutorial I taking the integer data moving ahead now below we'll also provide one Constructor and this Constructor will take in the data part which you want to store so when we initialize a tree node usually store the data into the data variable moving ahead we'll create one method as public void and we'll create a binary tree into it create binary tree so in order to create a binary tree first we'll create few nodes so let's say we are giving the notes name as first and let's say I give the value to data as one and I will just create few notes let's say I give the name as second third fourth fifth and let's say I provide dat as two 3 4 and five now when we call this create binary tree it will first create this five tree noes now in order to store this five notes into the binary tree first thing we do is we assign the value of first to root so now root will be holding the Tre note having data as one and let's say to first left we are assigning the value of second and to First write we are assigning the value of third so friends here root will point to the node having data as one and its left will point to a node having data as two and one's right will point to the node having data as three so here we have simply assigned the value of first to root and then we are assigning the value of second to first left and value of third node to first right so after these three statements here you can see root will point to first and then after this two statement it would look something like this second so here first left will point to the second and first right is pointing to third moving ahead now let's say we assign the value of fourth to second left so we assign value fourth to second left and we assign value fifth to second right so friend this is how we create a binary tree with the few nodes and after this four or five statements the binary tree looks like this so friends the binary tree which we created after those four five lines of execution the binary tree will look something like this that we initially created Five notes with the data 1 2 3 4 5 and then we have assigned the value of first to root so therefore now root is pointing to the node having data as one and then we assign the value of second to first left so now first left is pointing to the node having data as two and we assign third node to the first right therefore first right is pointing to the node having data as three we also assigned the value of fourth and fifth node to two's left and two's right so therefore it looks something like this so this is how we actually Implement a binary tree where we insert the node using the left and the right pointers of in tree node so friends in this tutorial we discussed how to implement a binary tree in Java and in my next tutorial we will discuss how we can Traverse each and every node of a binary tree in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss recursive pre- AIT reversal of a binary tree in Java so friends what is a pre-order binary tree traversal so friends in order to Traverse each and every node of a binary tree we apply this three steps on the each node of a binary tree so what we do is we visit that particular node and then we Traverse it left sub tree and then we Traverse it right sub tree so here if you take an example of this tree then we start with the root node and we apply these three steps on the root node so what we do we first Traverse this node and then we Traverse its complete left sub tree tree and then we Traverse its complete right sub tree so once we process this node we first go to his left sub tree and there we encounter a node having data is two so on this node we again apply this three steps that we visit this node and then we visit it left sub tree and then we visit it right sub tree so after we process the node having data is two we then go to its left sub tree and then we encounter a node having data S 4 so we apply these three steps on the Node four we first visit this node and then we Traverse to left sub tree and then to its right sub tree so here you can see node 4 has no left sub Tre and no right sub tree therefore therefore we are done with the processing of this node and then we return back to the node having data as two so we have processed this node two we have we have processed the node 4 so now in the third step we visit the right sub tree so we go to the node 5 and then we apply this three steps on the Node five we first visit this node then we visit his left sub tree and then we visit his right sub tree so as node 5 is having no left sub tree and right sub tree therefore we are done with the processing of the node 5 and once we are done with the Note 5 then we are sure that we have processed the right sub tree of the node two so therefore we have processed two then four and then we have processed five so we are done with the left sub tree and then we again go back to the root node one and as we have visited the left sub tree of it we now will visit the right sub tree for the node one so then we go to the right sub tree of the node one and when we reach to the node three we apply these three steps now for the node three so first we visit this node and then we visit it left sub tree and then we visit the right sub tree so after processing the node three we go to Six and we apply this three steps we visit this node we then go to it left sub tree and then go to it right sub tree now as node 6 is having no left sub Tre and no right sub tree then we are done with the processing of this node and then we return back to the node three so once we return back to the node 3 we have processed left sub tree and now the step remains to process the right sub Tre so when we reach to the node 7 we first process this node and then we Traverse the left sub tree of it and the right sub tree of it so as node 7 has no left sub tree and no right sub tree therefore we are done with the processing of the node 7 and then we reach to the node 3 and since we already processed this node then we reach to the node one so friends in pre-order traval we first process the node and then we process it left sub tree and then we process it right sub tree and this we do recursively for each and every node so let's see the demonstration of pre-order binary tree traversal so friends suppose you want to Traverse a tree whose root is nine and whose left is a node having data s two and its left is having data S 4 and the right of node having data is two is null and the root 9 also has a right subtree having the data is three and whose left and right sub trees are both pointing to null so let's see the demonstration of this algorithm that how we can process the notes of a binary tree in pre-order traversal so here you can see that below is the algorithm for it and as we are applying this pre-ordered traversal to each and every node recursively so here we know that the method name is pre-order and inside this method we are again calling this method to process the left and the right sub tree so friends when we are doing a pre-ordered reversal we are calling this method recursively and in order to understand this method recursively here we are maintaining a call stke which is Method call line number and the root so in the method call we'll just keep the track of the method that which method is being called and we'll also keep the information of the root that which current node is being processed and and we'll come to know about line number when we are demonstrating the algorithm so let's call the pre-order method and we'll pass the root as 9 so when the execution Point comes to pre-order we knowe that the call stack will now execute this pre-order method and we are keeping the track of the root So currently the root is being pointed by the data is 9 so then we check that whether root is equal to null or not so friends why we are providing this condition is because this is considered as our base case and as we are calling this pre-order method recursively we need a point to exit this recursion that when root is equal to null then we simply return from that method So currently you can see root is pointing to 9 here so therefore it's not equal to null so the condition in if block comes out to be false and then as we discussed in our previous slide that first we visit the node and then we visit his left sub tree and then we visit his right sub tree so we'll first visit the node and we'll print the data associated with that node so the output is nine so we have processed this node moving ahead so now we are calling the pre-order method to Traverse the left sub tree for this rout so the value we are passing passing to this pre-order is root left so currently you see root left is pointing to the node having data as two and as we are maintaining this call stack so when we call this pre-order method we'll keep the track of this line numbers so that once we return it back we know that from which line we need to execute the method So currently from line six we are calling this pre-order therefore we'll keep the track of this line number so here we have stored the number is six and now we'll again call pre-order method and we'll pass the root do left to it which is nothing but the node 2 so now root will be the node two and here pre-order is again called with a root as node two so now we are again executing pre-order with a root as two so we'll check whether root is equal to null or Not So currently root is not equal to null so as we discussed in our previous slide that once we reach to the left sub tree we process this node and then we go to its left sub tree and then to its right sub tree so now we are processing the node two so the output would be two because we are just printing the data part of it moving ahead and now we'll again call pre-order method recursively and then we'll pass root left to it so currently root is pointing to the node having data S2 and its left is pointing to the node having data S4 so as we are calling this preorder again we'll keep the track of the line number so we are placing the line number six because we know that we are leaving this pre-order at line six and we are again calling this pre-order so the point of execution again reaches to pre-order and this time the root is roots left so which is four four so when new route becomes the node having data is four and as we are again executing this pre-order we know that in the call stack this method will be called again and this time the root is being four so we'll again execute this pre-order recursively we'll first check whether root is equal to null or Not So currently root is pointing to four therefore it's not null and here we'll simply process this node so the output would be four and after we process this node we know that now we have to Traverse it left sub tree and then it right sub tree so first we are processing its left sub tree so we are simply calling pre-order again and we are passing Roots left so currently here you can see root left is pointing to null so therefore we'll Now call this pre-order by passing a value null and as we are leaving this pre-order now here we'll keep the track of the line number so we are calling this pre-order again and now the root would be null because we are traversing root left so currently root is pointing to four and its left is pointing to null so therefore our new roote becomes null and there will be one more method on the stack with the name pre-order and the root would be null so we'll again execute the pre-order method so we'll check whether root is equal to null So currently if you see root is equal to null so we have reached our base case so this base case will help us in exiting the recursion and as we know that we are left with no more notes in the left sub tree to Traverse therefore we'll simply return from this method so when we return this method gets executed so it gets it's removed from the call St and now as this method is removed from the call stack call goes to the pre-order method which was executed just before it so we'll now start executing this pre-order and as we know that we have left this pre-order at the line number six so we'll now start from the line number six and we also know that when we left this pre-order method at that moment the root was four so once the call reaches to this pre-order root will be pointing to four so friends here we have First Traverse the node 4 then we process the left sub tree and now we'll go to it right sub tree so that thing we'll do recursively so in the line S now we'll simply go to its right sub tree so as root is four and as right is pointing to null therefore we'll call pre-order with a null value and as we are calling this pre-order method with the value as null we are leaving this pre-order method so we'll update the line number that from line number 7even we have again called this pre-order method so now this pre-order will be called with a value of null so it's nothing but Roots right so when new root becomes Roots right so now root will be pointing to null and we also know there will be one more method on the stack with a root value of null moving ahead so we'll check whether root is equal to null or Not So currently root is equal to null therefore we'll simply return from this method so this method gets removed from the call stack and the execution Point goes to the method which called it so now we'll again start executing this pre-order method from the line number seven and we also know that we have left this pre-order when the root was pointing to no node 4 so we simply Traverse to the node 4 and this would become our root and then we'll start again executing from the line seven so once we reach the line8 we know that we are done with the processing of this pre-order method and whose root is four so therefore this method will be removed from the stack and the execution point will go to a method which called this method so here the execution reaches the pre-order for the root node 2 and we also know that we left this pre-order from the line number six so we'll start executing from the line number six and we also know that when we left this pre-order at that moment root node was two so here the root will now point to the node two moving ahead and from the line seven we'll Now call the pre-order and we'll pass the roots right because we are applying this pre-order traversal to each and every node that we are first traversing the node then we are processing it left sub tree and then we are processing Its Right sub tree so as here you can see we have processed this node two and we also process it left sub tree which is node four so now we are left with the processing of the right sub tree so therefore we are again calling this pre-order and we are passing the value of roots right so here Roots right is is null so therefore we again call this pre-order method and we'll pass the null value to it and as we are leaving this pre-order method and we are calling the new pre-order method so we'll just keep the track of the line number so it signifies that we are leaving this pre-order from the line number seven so here now we are calling pre-order with the value as null so therefore we know that there would be one more method on the call stack whose current roote would be null so therefore now root will point to null and we'll start executing this pre-order method so then we'll check whether root is equal to null or Not So currently root is equal to null therefore we have reached our base case condition and we'll simply return from this method so when we return from this method this method will be removed from the call stke and the execution point will now reach to a method which called this method and as we have reached to this pre-order method we know that we had left this method from the line number seven so therefore the execution will start from the line number seven and we also know that when we left this pre-order method at that time Root was pointing to the node two so therefore this root will now point to two and then we'll simply start executing this pre-order method so once we reach the line number eight so therefore this method will be removed from the stack and the execution point will reach to a method previous to it and we also know that we had left this method from the line number six therefore we'll start executing from the line number six and we also know that we had left this pre-order method at that moment root was nine so therefore now root will reach to 9 so friends for the root 9 we have processed the left sub Tre completely so now it's the time to process the right sub tree so therefore we start the execution from line number six and here we know that we will again call pre-order method and this time we'll pass Roots right which is the nodee three and as we are leaving this pre-order method we'll keep the track of the line number so now pre-order will be called with the root pointing to the node three and we also know that there will be now one more method on the stack so now pre-order will start executing with a root having data is three so therefore now root will point to the node having data is three moving ahead we'll check whether root is equal to null or Not So currently root is not equal to null so therefore we'll simply process this node and then we'll start processing it left sub tree and the right sub tree so we'll simply print the data for this root node which is three and then we'll process the left sub tree of it so we are again calling this pre-order method and this time we are passing Roots left so it's nothing but we are passing Roots left which is null and as we are leaving this pre-order method we'll keep the track of the line number which is six so now the execution Point reaches to pre-order and this time the root is null so therefore root will point to null and we also know that there will be one more method on the call stack and the root will be null so we'll execute pre-order with the root as null so we'll check whether root is equal to null or Not So currently root is equal to null so we have reached our base case so we'll simply return from this method now as we return from this method the pre-order method on the call stack with the root as null will be removed from the call stke and the execution point will reach to a method which had called this method so we'll again start executing pre-order method and we know that we had left this pre-order from the line number six therefore the execution point will start from the line number six and we also know that when we had left this pre-order method at that time Root was pointing to three so now root will point to three moving ahead from the line seven we'll now again call Roots right because we had traversed the left sub tree for the root three now we'll process Its Right sub tree so we'll again call pre-order method and we'll pass Roots right which is null so when we are leaving this pre-order we'll keep the track of the line number so when we call this pre-order method we had passed Roots right which is null so therefore for this pre-order now root will point to null and we also know that there will be one more method on the call stack with the root as null so then we'll check whether root is equal to null or Not So currently root is equal to null therefore we have reached our base case so we'll simply return return out from this method so when we return from this method this method will be removed from the call stack and and the execution point will reach to a method which called this method so now we'll again start executing this pre-order method and we know that we had left this method from the line number seven so we'll start from the line number seven and we also know that when we had left this preorder method root was pointing to three so therefore root will reach to three moving ahead now once you executed all the statements from this pre-order this pre-order will be removed from the stack and the execution point will go to a method which called this method and the point which we have left this pre-order was at line number seven so therefore the execution point will start from the line number seven and we also know that at that moment the root was nine so therefore now the root will point to the 9ine and finally we are done with this pre-order therefore this method will be removed from the stack so friends in this slide we saw the demonstration of how pre-order traversal works that it first visit the note and then it recursively calls pre-order to process the left sub tree and then to process the right sub tree and this goes on for each and every node so here you can see the output is 9 2 4 3 so we have visited 9 then we visited 2 then we visited 4 and then we finally visited three so friends here we saw the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial we discussed how to implement a binary tree in Java so I had created one class binary tree and we have implemented the binary tree in Java so here we had created an instance variable of type tree node which was actually root because this root will hold all the notes of a binary tree and we had also discussed how we can create a binary tree by creating the few nodes now here let's write a code for pre-ordered traval of a binary tree so public void we'll give the method name as pre-order now this method as we know will take in a root which we saw in the slide and as we are going to call this pre-order method recursively we'll first provide a base case so the base case would be if root is equal to null then simply return from this method and if root is not equal to null then simply visit the node so we'll print root. data and once the processing of node is done we will again call pre-order method and we'll pass root left and in the last line we'll again call pre-order method and we'll pass root do right to it so here after processing of a node we are recursively processing the left sub tree and the right sub tree in a pre-order fashion so friend this is the code for pre-ordered binary tree traversal now let's test is working in main method so first we'll create a binary tree which we actually saw in the slide so here in my previous tutorial I had created few nodes so I'll just remove one of the node and I give the data which we saw in the slide as 9 2 3 and 4 so we also saw that Ro was pointing to 9 9 left was second and 9 right was holding a node having the data as three and we also know that node 2 left pointed to node 4 and we'll just simply remove this line so here we have created a minority which we discussed in the slide where root is pointing to 9 and whose left is pointing to two and whose right is pointing to three and then again two's left is pointing to four now after creating this binary tree Let's test the working of this pre-order method so in the main method we'll first create the instance of binary tree and then we'll simply call create binary tree now once we call this create binary tree the binary tree will be created and the root will hold the actual binary tree for us and then we'll simply call pre-order and we'll pass the root of the binary tree so when I run this code so here you can see it printed 9243 which we actually discussed in the slide so friends in this today tutorial we discussed the pre-order binary treat reversal I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss iterative pre-order traveler of a binary tree in Java so friends in my previous tutorial we discussed what is a pre-order B binary tree traversal so in pre-ordered tree traversal we perform the three steps for each and every node of a binary tree that we first visit that particular node and then we visit his left sub tree and then we visit his right sub tree and this we do for each and every node so in my previous tutorial we discussed the recursive pre-order binary tree traversal and in this tutorial we will discuss iterative pre-order binary tree traversal we also discussed that we apply these three steps to each and every node of a binary tree that we visit that particular node and then we visit his left sub tree and then we visit this right sub tree so friends in my previous tutorial we use the recursion in order to Traverse the binary tree now in this tutorial as we are not using the recursion and we are using the iterative way therefore we need to use an additional data structure which could hold the information of the notes so friends when we use recursion and we called the method recursively so it internally used a stack so in the alterative way we will use the stack data structure so friends below is the algorithm for iterative pre-order traversal of a binary tree and as we are using the iterative version of this algorithm we are creating a stack which could hold the additional information for us so that when we backtrack to a particular node we can fetch it from the stack easily and we also know that stack is a Leo data structure which means the last in first out so the node inserted last would be the first node to be removed and if you want to know more about stack data structures you can watch my previous tutorial so in this tutorial let's take this example that we want to Traverse the notes of this binary tree so let's see the demonstration of this algorithm step by step so basically when we execute this algorithm we start with the root and the first step we check is whether root is equal to null or Not So currently you see root is pointing to the node having data is one therefore it's not null and then we'll create a stack which could hold the tree notes for us so here you can see we have created one stack now this stack will hold the tree notes for us so on the first step we'll simply push the root node moving ahead so friend as this is the iterative version of the algorithm we are using using a while loop and we are placing a condition that iterate till the stack is empty so currently you can see stack is not empty because we have ped one node therefore the condition in while block comes out to be true and while loop executes so in this line as we know that stack has only one element so therefore this element will be popped out and will assign this pop node to a temporary node so it would look something like this so first the node will be popped out so as the three node with the data as one was popped out now this temp will point to that particular node moving ahead so friends in pre-order tree traversal we first process a node and then we process it left sub tree and then we process Its Right sub tree so in the first step we'll simply print this node so the output would be one moving ahead so friends we have processed this node and now we will process its left sub tree and then Its Right sub tree so in order to do that we are first putting the right node on the stack and then we are putting the left node on the stack because when we pop it out we'll first pop out the left node and then we'll pop out the right node and in order to do that we are first checking that whether temp right is equal to null or Not So currently temp right is not equal to null therefore we'll push the node having data S3 on the stack so you can see three is now on the stack and then we'll check whether temp left is equal to null or Not So currently temp left is not equal to null therefore we'll push the node having data is two on the stack so friends as stag is a Leo data structure it means the node inserted last would be the first one to be removed and we also know that in pre-order tree traversal we first visit the node and then we visit the left sub tree so basically in order to Traverse the left sub tree first we push the right node on the stack and then we push the left node therefore when we pop it out we'll pop out the node having data as two now we'll again check in the while loop whether stack is empty or Not So currently stack is not empty therefore condition in while loop comes out to be true and then we'll simply pop an element from the stack and we'll assign it to the temporary node so the node is popped out so it means now temp will point to the node having data is two and in The Next Step we'll simply print the data for the temporary node so two is printed and hence we have processed this node and now we we want to process the left sub tree first and then Its Right sub tree so on the Stag we'll first put the node which is pointed by temp right and then we'll put the node which is pointed by temp left we'll check whether temp right is equal to null or Not So currently temp right is pointing to the node having data is five therefore it's not null therefore we simply push the node having data is five on the stack and then will check whether temp left is equal to null or not so here you can see temp left is pointing to the node having data S4 therefore we'll push the node four on the stack and then we'll again execute the while loop and we'll check whether stack is empty or Not So currently stack is not empty therefore the while loop executes and now in the first step we'll simply pop an element which is on the top of the stack so here we know that four is on the top of the stack so it will be popped out and now temp will point to the node four moving ahead and then we'll simply print the data associated with this node which is four and then we'll simply check whether temp right is equal to null or Not So currently temp right is equal to null therefore the condition in if block comes out to be false and then we'll check whether temp left is equal to null or not so here you can see temp left is also equal to null therefore the condition in if blog comes out to be false and then again in while loop will check whether stack is empty or Not So currently you see stack has two notes therefore it's not empty so the while loop executes and the first step will simply pop the top element and we assign its value to the temporary node So currently you see node having data is 5 is the top element therefore we'll pop it out and now the temple point to the node having data is five moving ahead now we'll simply print the data associated with this temporary node which is five moving ahead we check whether temp right is equal to null or not So currently temp right is equal to null therefore the condition in if blog comes out to be false we then check whether temp left is equal to null or not so here you can see temp left is also null therefore the condition in if blog comes out to be false and then we'll again execute the while loop with a condition that stack is empty or Not So currently stack has one node therefore it's not empty so in the first step we'll simply pop an element from the stack stack and we'll assign its value to the temporary node so here you can see when we do stack. popop the node 3 will pop out and then the temp will point to that particular node so it would look something like this so now temp is pointing to the node having data as three moving ahead now we'll simply print the data associated with this temporary node so the output we see 3 and then we check whether temp right is equal to null or Not So currently temp right is not equal to null therefore the condition in if log comes out to be true so in the fog we simply push temp right which is the node 7 on the stack and then we'll check whether temp left is equal to null or not so temp left is pointing to six which is not null therefore the condition if blog comes out to be true and we'll simply push temp left on the stack which is six and then in while will again check the condition whether stack is empty or Not So currently stack has two elements therefore it's not empty so in the first step we'll simply pop an element from the stack so the top element is a node having data six so so this node will be popped out and it's value will be assigned to the temp So currently temp is pointing to the node aing data as three and after this step temp will point to the node 6 because because when we do stack. pop 6 will be popped out so it would look something like this so now temp is pointing to six we'll simply print its data on the console which is six and then we'll check whether temp right is equal to null or Not So currently temp right is pointing to null therefore the condition in if blog comes out to be false and then we'll check whether temp left is equal to null or not so temp left is equal to null therefore the condition in if block comes out to be false and then in y Loop we'll again check whether stag is empty or Not So currently stack is not empty because there is one node and in the first step we'll simply pop the element from the stack and assign its value to Temp so when we pop an element from stack we know that 7 will be popped out so therefore temp will now point to 7 so it would look something like this and then we'll simply print the data associated with this node on the console which is seven and then we'll check whether temp right is equal to null or Not So currently temp right is equal to null therefore condition in if block comes out to be false and then we'll again check whether temp left is equal to null or not so temp left is also equal to null so therefore the condition in if block comes out to be false and finally we'll check whether stag is empty or Not So currently you see as we have processed all the notes of a binary tree so the tag is empty therefore the condition in while block comes out to be false so friends using an stag we saw how we can perform pre-ordered traversal of a binary tree so here we discussed about the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial we created one class by name binary tree and we implemented binary tree into it now this class has has instance variable of type tree node which is the actual root of our binary tree we also discuss about the recursive pre-order treat reversal and in this tutorial we will see the iterative version of it so therefore I'll just command this code and below I will create a method as public void preorder and in this method we'll write a code which would perform the iterative pre-order treat reversal so in the first step we'll check whether root is equal to null or not so if the root is equal to null so it means there are no nodes into the binary tree so therefore we'll simply return from the method and in the first step we'll simply create a stack so here we will import the stack from java.util package and as we discuss in slide we'll just push the root on the stack and after that we'll provide a while loop and inside this value will check whether stack is empty or not so if the Stag is not empty then the while loop will be executed and in the first step we'll create a temporary node and we'll pop the element from the stack and we'll assign it to the temporary node and as we have popped an element from the stack we'll simply print its data on the console and in the next I will check that whether temp right is equal to null or not so if temp right is not equal to null then we'll simply then we'll simply push temp right on the stack and we will do this step for the temp left as well so here if temp left is not equal to null then we'll simply push temp left on the stack so friend this is the iterative version of pre-order treat reversal now let's test is working on the main method so in the main method we have created this binary tree and then we called create binary tree so it will create a binary tree with few notes which we discussed in our previous tutorial and the last I will simply call the pre-order method and when I run this code so you can see it printed 9243 and it printed the same what we discussed in our previous tutorials when we had called the recursive version of the pre-order Tre traval so friends in this tutorial we discussed about the iterative version of pre-order tree traversal I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss recursive in order traversal of a binary tree in Java so friends what is in ordered binary treat reversal so here you can see that in order binary tree traversal has basically three steps and we apply these three steps to each and every node of the binary tree so the basic steps involved in in order binary tree traversal is we first visit the left sub tree for a particular node and then we visit the node and after visiting that node we go to its right sub tree and these three steps we apply on each and every node of the binary tree so let's take an example of the below binary tree now let's suppose we want to visit each and every node of this binary tree so we start with the root so here you can see root is pointing to node one now we apply these three steps on the Node one so here you can see basically the step two is involved in the processing of the node which we are currently pointing to so here before processing the node one what we do we first Traverse its left sub tree so here you can see this is the complete left sub tree which we want to Traverse before we process this node and after we process this complete left sub tree we then visit this node and after visiting this node we go to its right sub tree so here when we are at node one then before processing this note we go to its left sub tree now as we go to its left sub tree we encounter the nodee 2 so when we encounter the node two we apply this three steps over the node two and before processing the node two we first Traverse its left sub tree then we process the node and then we go to its right sub tree so here before processing the node two we go to its left sub tree first so once we reach the node 4 we apply this three steps on the Node 4 so before processing the node 4 we Traverse to left left sub tree then we process the node and then we go to the right sub tree so here you can see node 4 has no left sub tree therefore we are done with the processing of the left sub tree and after we are done with the processing of left sub tree we actually visit the node so the first element we visit is the node 4 and after we are done with the node four we go to its right sub tree and we know that note 4 has no right sub tree therefore we are done with the processing of the Note 4 completely so the call returns back to the node 2 and from the node two perspective we have actually visited it complete left sub tree so now is the chance to visit the node 2 so we actually visit the node two and then we go to it right sub tree so when we reach to the node 5 we actually apply this three steps now on node 5 we traverses left sub tree then we visit the note and then we go to its right sub tree so here you can see Note 5 has no left sub tree therefore we are done with the processing of the left sub tree so then we process the node 5 and after we process the node 5 we go to its right sub tree and we know that node 5 has no right sub tree therefore we are done with the processing of the node 5 so friends after the node 5's process the call returns back to the node one and from the node one's perspective we have completely Travers the left sub tree now so now is the chance to visit the node one so we visit the node one and then we go to its right sub tree so once we reach to the node three we apply these three steps over the node three so before processing of the node three we first go to his left sub tree then we visit the node and then we go to his right sub tree so when we reach to this left sub tree we encounter a note having data is six so we apply this three steps now over node 6 we visit its left sub tree then we process the node and then we visit the right sub tree so here as node 6 has no left sub tree therefore we are done with the processing of the left sube and then we actually visit the node and after visiting the node we go to its right sub tree and as node 6 has no right sub tree therefore we are done with the processing of the Note 6 completely then our call goes back to the Note 3 and we know that we have completely visited its left sub tree so now we can visit the node three so once we visit the node 3 the third step is involved is we go to its right sub tree so as we go to its right sub tree we encounter a node having data as 7 so on this node 7 we now apply this three steps we first visit the left sub tree of it then we visit the node and then we visit the right sub tree so friend as we know that node 7 has no left sub tree therefore we are done with the processing of the left sub tree for the node 7 and then we actually visit the Note 7 and then we go to its right sub tree so here we can see Note 7 has no right sub tree therefore we are done with the processing of the node 7 so here we have visited each and every node and to each and every node we applied this three steps that before processing the node we actually visited its complete left sub tree then we visited the node and then we went to its right sub tree so friend these are the step steps involved in in order binary treat reversal now let's go ahead and see the demonstration of the algorithm so friend let's suppose we want to Traverse this binary tree where root is pointing to the node 9 whose left is pointing to node two and whose left is pointing to node four and node four has no left and right sub tree therefore they're pointing to null node two has no right sub Tre therefore it's pointing to null and here node 9 right is pointing to the node three which have no left sub tree and the right sub tree so friends below you can see the algorithm for the in order binary tree traversal and here you can see the method name is in order which takes in a root and in the method we are actually again calling the inord method therefore these calls are recursive in nature so in order to understand the recursion we are using this SC stke where we are keeping the information for the current executing method and we are also keeping the track of the root note which is getting executed in the particular method call and we are also keeping the track of the line number whose significance we will see once we demonstrate the algorithm so let's see the demonstration of this algorithm step by step now when we call in order method and we pass the root So currently you see root is pointing to the node 9 so we know that this method will be part of our call stack so it would look something like this that now this method will be part of our call stack and this method will be executed with the root as 9 because currently root is pointing to 9 we move ahead and we check whether root is equal to null or not so friends why we are providing this condition as this is the base case for our recursion because in the in order method we are again calling the in order matter recursively so friends in order to break this recursion we need to provide a base case and if we don't provide this base case then this method will call each other recursively so in order to stop this we are providing this base case so currently you see root is pointing to the node 9 therefore it's not null so the condition in if block comes out to be false so in the first step what we do is so what we discussed in the slide that before processing of a node we will First Traverse his left sub tree so we again call the in order method and this time we are passing Roots left because we want to process the left sub tree now so here you can see root left is the node two therefore this in order method we'll call the in order method again with the root as two so friends here we are leaving this method and now we are entering to this method again so we'll keep the track of the line number that at the line five we left this method so that once this method is processed we again return R back to this method and we'll start executing from the line five so therefore we'll keep the information for the line number whenever we leave any particular method so here we keep the track of the line number which is five that we are leaving this in order method at the line five and we are calling this in order method again with a root two so friends this method will be called again and this time the root will be the node two so here now root instead of pointing to 9 it will point to two and we also know that we have left this method in order method so there will be one more method on the stack so now this in order method will start executing with the root as two so let's see the working we'll first check whether root is equal to null or Not So currently root is pointing to the node two therefore it's not null so friends as we discussed in the slide before processing any node we have to process it left sub tree first so in order to visit the node two we'll first have to visit this left sub tree so here we again call in order method and we pass Roots left so here you can see root is pointing to the node 2 and we will call in order method and we'll pass the root do left which is node 4 and as we are leaving this method we will keep the track of the line number so here now in order method will start executing with the root as four So currently root is pointing to the node 2 so now it will point to node 4 and here you can see there would be one more method coming on the stack now this in order method will start executing with the root as 4 moving ahead we'll check whether root is equal to n or Not So currently root is pointing to the node four therefore it's not null and here before processing the node four we have to first process his left sub tree therefore we are again calling the in order method and we are passing root left so currently root is pointing to the node four so now we are calling this in order method and we are passing the null value to it and here we will keep the track of the line number that as we are leaving this method and we are calling this method so we are keeping the track of the line number so friends now in order method will be called again and this time the root will point to null so here you can see currently root is pointing to four and as we discussed that we are going to Roots left so now root will point to null and we also know that once this method gets start executing there will be one more method on the call stack now here you can see this in order method has root as null moving ahead we'll check whether root is equal to null or Not So currently you see root is equal to null therefore we have reached our base case which makes sense because when we encounter a null value it means there are no notes to be traversed so we simply return from this method and once we return from this method we know that this method will be removed from the call stack and the execution point will go to the method which called this method so now execution Point reaches here so friends we know that at line five we left this method so we'll start executing from the line five itself so our execution point will now start from the line five because we have processed this information earlier and we also know that when this method was getting executed root was pointing to four so when step of execution reaches here root will point to four moving ahead so friends here you can see for the node 4 we have processed left sub tree now is the time to process the actual node so therefore we simply print Roots data on the console so on the output you can see four will be printed because Roots data is four moving ahead and we also saw in the slide that after we process the node we then go to his right sub tree so in order to go Its Right sub tree we again call the in order method and this time we pass Roots right so currently root is pointing to the node four and Its Right is pointing to null therefore we'll again call the in order method and we'll pass the null value to it and here as we are leaving this method on the line 7 we'll keep the track of the line number so now it will be seven and we also know that once we call this method so now in order method will be called again and this time with roots right which is null so friend currently root is pointing to node four and when we call this in order method with a null value therefore now root will point to null and we also know that there will be one more method on this call stack with the root as null so let's execute this method and the first step will check whether root is equal to null or Not So currently root is equal to null therefore the condition comes out to be true and we'll simply return from this method so once we return from this method we know that this method will be removed from the call stack and the method which called it the execution point will go there so now the execution Point reaches to this method and we also know that we left this method from the line number seven so therefore the execution point will start from the line seven and we also know that when we left this method root was pointing to node four so therefore now root will point to node four again and then we'll start executing from the line 7 so when we reach the line it we know that we have completely process this in order method so therefore this method will be removed from the call stack and the call will go to the method which had called this method so now call will go to this in order method and we know that we had left this method from the line number five therefore the execution point will start executing after the line five and we also know that when we're executing this in order method at that time Root was pointing to node two so therefore now root will point to the node two and we'll start executing after line five so here we can see that before processing the node two we have completely visited its left sub tree so now is the time to process the node itself therefore we simply print its data on the console so you can see two gets printed on the console and after we process the node we know that now we have to go to its right sub tree so we again call in order method and we pass root right value which is null and we also know that as we are calling this in order method we will update the line number here so now the execution Point reaches to the in order method and we know that there will be one more method on the call stack with the root as null so here you can see root is pointing to node 2 so now this root will point to null and we'll start executing this in order method so in the first step we check whether root is equal to null so here you can see root is equal to null therefore we'll simply return from this method and we are returning from this method that because we have already process it right sub tree so once we return from this method we know that now this in order method will be removed from the call stack completely and now the execution point will reach to this in order method and we'll now start executing this in order method from the line number seven so we'll start executing from the line number seven and as we know that when we were executing this in order method root was pointing to two so now root will point to two and then we simply execute this in order method so once we reach to the end of this method we know that now this method will be removed from the call stack and the execution point will reach here so we'll start from the line number five and we also know that when we are executing this method root was pointing to 9 so therefore now root will point to 9 and then we'll simply execute the steps so friends here you can see before we processed node 9 we complet completely Traverse it left sub tree and after we Traverse its left sub tree completely now we are visiting the node so we are simply printing its data on the console moving ahead and once we are done with the process of this note we have to process the right sub tree so therefore we are again calling in order method and we are passing the value Roots right to it so here you can see Roots right is the node three and as we are calling this new method we are updating the line number so point of execution reaches to the in order method with a root as three so now root is pointing to three and we also know that as this is a new method on the stack there will be one entry on the call stack so here now this in order method will start executing with a root as three so we first check whether root is equal to null or Not So currently root is pointing to three therefore it's not null and then for the root3 we apply the in order traversal again we first visit its left sub tree so in order to visit its left sub tree we are calling in order method and we are passing root left value to it so here you can see root left is pointing to null therefore we are calling this in order method with the value as null and as we are leaving this meth method and we are calling this new method we will update the line number so then execution point will reach to this in order method with the root as null so we know that there will be one more method on the call stack with a root as null and now root will point to null moving ahead we check whether root is equal to null or not So currently root is equal to null therefore we'll simply return from this method and this metal will be completely removed from the call stack and as this metod is removed from the call stack the execution Point reaches to this in order method which actually called the in order method with a null value and from which line we have to start we have to start the execution from the line number five and and we also know that when we were executing this in order method root was pointing to three so now root will point to three so friends now in this step as we have processed the left sub tree completely then now we'll process the node itself so we are simply printing the data on the console and then as we have to process it's right sub Tre now so we have calling in order method and we are and we are passing Roots right which is the null value and before calling this new method we are updating the line number so when the point of execution teaches the in order method root is null so there will be one more method on the stack with the root as null so now this root will point to null and we'll start executing this method so in the first step we'll check whether root is equal to null or Not So currently root is equal to null therefore we'll simply return from this method and when we return we know that this method will be removed completely from the call stack and the point of execution reaches here so we know that we'll execute this method from the line number seven and we also know that at that moment root was pointing to three so now root will point to node three and then we'll start executing from the line seven so when we reach to the line 8 we know that we have completely executed this in order method so this will be removed from the call stack so friends now the execution Point reaches to this in order method and we'll start executing from the line seven and we also know that when we are executing this method root was pointing to 9 therefore we will simply Traverse root to 9 and then we simply process all the step for this in order method so now this will be removed from the stack so friend as we know there are no method on left on the call stack therefore we have successfully executed the in order binary treat reversal and the output you can see it's 4293 so friend this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial I had created one class by name binary tree and I have implemented binary tree into that class you can watch my previous tutorial in order to understand it's working so in this tutorial we will simply write the code for in order binary tree traversal so let's say I give the method name as public void in order and as we discussed in the slide this in order method takes in a root now in the first step we check if root is equal to null then we'll simply return from this method because this is a base condition as we are as we are calling this in order method recursively we have to provide a base case so that we can get exit from this recursion and as we discussed in our slide that before visiting any node we'll first visit its left sub tree so we'll call in order method and we'll pass pass root left to it and after we process it's left sub tree we will visit the node so we simply print Roots data on the console and in the last we again call in order method and we will process Roots right subtree by calling Roots right in the in order method so friend this is the algorithm for the in order binary tree traval now let's test is working now in my previous tutorial I had created one binary tree and this is the same tree which we discussed in the slide use this create binary tree method so here in the main method we'll call create binary tree and then we'll call the in order method and here we'll pass the root now if I run the code so here you can see it printed 4293 which is the same output which we saw in the slide so friends in this tutorial we discuss the recursive way of inorder binary tree traversal I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss iterative in a traversal of a binary tree in Java so friends in my previous tutorial we discussed about the recursive in order tree traversal so steps involved in inorder tree traversal are as follows that before visiting any particular node we first visit his left sub tree then we actually visit the node and then we visit it light sub tree and this steps is applied over each and every node so friends if we apply an order tree traversal over this tree then what we need to do is before visiting the node one we have to actually Traverse it left sub tree then we have to visit the node and after visiting the node we have to Traverse Its Right sub tree so when we start with the node one we have to go to its left sub tree first because as we go to its left sub tree there is no way we can reach to the node one again therefore we need an additional data structure which can hold this node so that once we complete the visiting of left sub tree we we can pull the element out of that additional data structure and we can visit it and after visiting it we can go to its right sub tree so the additional data structure that we use here is stack so here you can see we are using stack which is a Leo data structure which means an El inserted last into the stack would be the first one to be removed in order to know more about the stack you can watch my previous tutorials before visiting this node we actually put it on the stack and then we go to its left sub tree and this we do for each every node and once we actually visit the left sub tree of any node then we pop the element out of the stack we visit that node and then we go to its right sub tree so let's see the demonstration of this algorithm step by step so let's suppose we are given with a binary tree having six nodes and where root is pointing to the node one so let's apply this algorithm over this binary tree and let's see how we can Traverse each and every node of a binary tree using the in ordered tree traversal so basically in the first step we check whether root is equal to null or not so if root is equal to null we simply return return because there are no nodes in the tree to be traversed so currently you see root is pointing to node one therefore it's not null so the condition in if blog comes out to be false so after the if blog what we actually do is we actually create a stack now this stack will hold the tree noes for for us so it would look something like this moving ahead so in the next step what we do is we create a temporary tree node and we assign the value of root to it so now the temp will point to root so it would look something like this that is temporary node is pointing to root moving ahead so friends in order to Traverse this binary tree using in order tree traversal we actually use a while loop and inside this while loop we are actually placing two conditions so we are iterating this V Loop till stack is empty and temp becomes null So currently you can see stack is empty so the condition comes out to be false but you can also see the temp is actually pointing to a note therefore it's not null so the second condition comes out to be true and as there is a r operator between these two conditions therefore the overall condition comes out to be true so the while loop executes so in the while loop we actually encounter an F El block so in the F blog we check whether temp is equal to null or Not So currently you can see temp is pointing to the node one therefore it's not null so the condition in if block comes out to be true so in the F Blog the first step we do is we actually push the temporary node on the stack which makes sense because before visiting this node we have to first visit his left sub tree so therefore we are actually pushing this temporary node on the stack so that once we are done with the left sub tree then we can pop this element out and then we can visit this node and after visiting this node we can go to its right sub tree so when we push the temporary node on the stack it looks something like this that now node one is on the stack moving ahead and in the next step we simply Traverse the temp to its left because we have to first visit the left sub tree therefore we need to Traverse temp to its left so we are assigning the value of temp. left to Temp so here temp left is the node two therefore now temp will point to the node two so it would look something like this the temp is now pointing to the node two moving ahead in the while loop we'll again check whether stack is empty or not and then we'll check whether temp is pointing to null or Not So currently you can see stack is not empty and temp is pointing to the node two therefore it's not null so the condition in V block comes out to be true and then the if log we will check whether temp is equal to null or not so here you can see temp is pointing to the node two therefore it's not null so the condition in if loog comes out to be true and then we'll simply push that node two on the stack because before visiting the node two we have to first visit its left sub tree completely therefore we'll push the node two on the stack so it would look something like this that now node two is on the stack and then we'll simply Traverse temp node to its left which is the node 4 so it would look something like this now temp is pointing to the node four and then again in the v block we'll check whether stack is empty or not and temp is equal to null or Not So currently stack is not empty and temp is pointing to the node four so therefore the condition in while block comes out to be true and then in IFL will check whether temp is equal to null or Not So currently temp is pointing to node 4 therefore it's not equal to null so the condition in if blog comes out to be true so then in the first step what we do is we simply push the temp on the stack because before visiting the node 4 we have to first reverse it left sub Tre completely therefore we are pushing the node four on the stack so it would look something like this now node four is on the stack moving ahead and the next I will simply Traverse temp by assigning temp. left value to Temp which makes sense because before visiting this node we have to first visit the left sub tree therefore not temp has to move to its left sub tree so now temp will point to a node which is left to node four and here you can see it is pointing to null so therefore now Temple point to null moving ahead we'll again check whether stack is empty or not and temp is equal to null or Not So currently you can see temp is equal to null but stack is not empty therefore the condition in while block comes out to be true and then in the F block we'll check whether temp is equal to null or not so here you can see temp is equal to null therefore the condition in if block comes out to false so the else blog will be executed and here we can see that node 4 left is pointing to null therefore there is no node to be visited so therefore we have visited its left sub Tre completely so now is the turn that we can visit the node 4 so in order to do that we'll simply pop the first element from the stack and we'll assign the temp to that node so here you can see s t is a Leo data structure so the last element inserted is the first one to be removed so when we do a pop the node four will be popped out and value of node 4 will be assigned to Temp so therefore once the node 4 is popped out temp will now point to the node 4 so it would look something like this that now node 4 is popped out and whatever the value it holds it will be assigned to Temp so now temp will point to not Note 4 so it would look something like this moving ahead so here for the Note 4 we have visited it left sub tree completely so now is the time to visit the Note 4 so on the console we are simply printing the data associated with the temporary node so here node 4 becomes the first node to be traversed so on the output four will be printed moving ahead and as we have visited a node 4 now we'll simply Traverse to its right sub tree so we have simply assigning value of temp. right to Temp so here temp. right is pointing to null so therefore now temp will point to null moving ahead so in the v BL we'll check whether stack is empty or Not So currently stack is not empty and temp is equal to null or Not So currently temp is equal to null but stack is not empty therefore the condition in while block comes out to be true and we'll check whether temp is equal to null or Not So currently temp is equal to null therefore condition if blog comes out to be false and the else blog will be executed so here you can see for the node four as its left is pointing to null and Its Right is pointing to null it means there are no notes on the left and the right side for the node 4 to be traversed therefore for the Note 2 we have completely visited its left sub tree because we have printed the output four which means we have traversed this node so here what we are doing is we are again popping the element from the stack and we are assigning it to Temp so when we pop an element from the stack we know that it's node two so it would look something like this that node two is popped out and its value will be assigned to temp temp so it means now temp will point to node two and which makes sense because we have completely Traverse the left sub tree for the node 2 so now it's the time to Traverse the node two so in the next step we'll simply print the data associated with the temporary node which is two so on the console we simply print two and and then we'll simply Traverse time to its right so here as we have visited the left sub tree for the node 2 and we also visited the node 2 now is the time we go to its right sub tree therefore we are simply assigning temp. right value to Temp so it would look something like this so now temp is pointing to the node 5 because it is on the right of the node 2 moving ahead now in the while loop we'll check whether stag is empty or Not So currently stack is not empty and temp is also pointing to node 5 therefore the condition in V block comes out to be true and then in if log we check whether temp is equal to null or Not So currently temp is not equal to null because it is pointing to the node 5 therefore the condition in if log comes out to be true so what we do is we simply push the node five on the stack because we cannot visit this note till we visit left sub completely therefore we need a way to store this element on the stack so we are simply pushing the temporary node on the stack so now node five is on the stack and then we simply go to its left because we need to Traverse its left first so now temp is pointing to null in the v block we will check whether stag is empty or not so stag is not empty but temp is pointing to null so the overall condition comes out to be true so the while Block executes in the F blog we'll check whether temp is equal to null or not so temp is equal to null therefore the condition in if blog comes out to be false and the lse block will be executed so as node five has no left sub tree therefore simply means that we have visited this left part now we'll actually visit the node so we simply pop the element from the stack so when we pop the element from the stack we know so we know that five was inserted last therefore it would be first one to be removed and when we remove the node 5 we assign its value to Temp so now temp will point to the node 5 so it would look something like this so now temp is pointing to the node five and then we'll simply visit the node 5 so on the console we print the data associated with the temporary node which is five moving ahead and once you have visited this node now it's the time to go to it right sub tree so now temp fill point to null moving ahead in the while block we'll check whether stag is empty or Not So currently stag is not empty but temp is pointing to null so the overall condition comes out to be true because stack is not empty so the while Block executes in the F blog will check whether temp is equal to null or not so temp is equal to null therefore the condition in if blog comes out to be false and the lse blog will be executed so here you can see we have completely visited the node 5 and this node 5 is actually right to the node two therefore we have completely visited a left sub tree for the node one so when we pop an element from the stack one gets popped out and now temp will actually point to the node one so node one is popped out and its value will be assigned to Temp so now temp will point to node one moving ahead so friends here you can see for the node one we have completely visited its left sub Tree by printing 4 2 and five so now we can actually visit this node so therefore we simply print the data associated with this temporary node which is one so one gets printed on the console therefore we have visited this node and the next step as we have visited this node now we'll simply go to its right sub tree therefore we simply assign temp right to Temp so here you can see temp right is pointing to the node three therefore now Temple point to the node 3 again in the v blog we'll check whether stag is empty or not so here you can see stag is empty so the first condition comes out to be false but here you can see temp is pointing to the node 3 therefore it's not equal to null so the second condition comes out to be true so here the overall condition comes out to be true and the while blog executes so here we will check whether temp is equal to null or Not So currently temp is pointing to the node 3 therefore it's not equal to null so the condition in if log comes out to be true and here before visiting the node 3 we have to first visit its left sub Tre completely therefore we need a way to store this element on the stack so we simply push the temporary node on the stack so it would look something like this now three is on the stack and then we'll simply go to it left sub tree because this left sub tree we need to visit first before actually visiting the node 3 so we are simply assigning temp. left value to Temp so here you can see temp left is pointing to the node 6 so therefore not temp will point to the node 6 in the while block we'll again check whether stag is empty or Not So currently stag is not empty so the first condition comes out to be true and temp is actually pointing to the node 6 therefore the second condition also comes out to be true so the overall condition comes out to be true and while block executes so in the first step we'll check whether temp is equal to null or Not So currently temp is pointing to node 6 therefore it's not equal to null so the condition in if block comes out to be true and then we'll simply push the node six on the stack because we can't visit this node till we process its left sub tree completely therefore we are storing the node 6 on the stack so after pushing the Note 6 on the stack we simply go to its left sub tree so now tempil point to the left of the node 6 which is null moving ahead now currently stack tag is not empty but temp is pointing to null therefore the overall condition comes out to be true we check whether temp is equal to null or not so temp is equal to null therefore condition and if log comes out to be false and the lse block will be executed so here as node 6 has no left sub tree therefore we are done with the processing of the left sub tree for the node 6 so now is the time that we can visit the node 6 so what we do is we simply pop the element from the stack because we know that we have actually stored this element on the stack so we pop this element from the stack and we'll assign it to Temp so it would look something like this so now temp is pointing to the node 6 moving ahead and then we are simply printing the data associated with node 6 so six gets printed on the console and as we have visited this note now is the time to go to this right sub tree so therefore now temp will point to null so in the while blog will check whether stag is empty or Not So currently stag is not empty so this condition comes out to be true but temp is pointing to null so the overall condition comes out to be true so the while block executes we check whether temp is equal to null or not so here temp is equal to null therefore the condition in if blog comes out to be false so the lse block will be executed so friends here you can see for the node 6 we have actually visited its left sub tree we have visited the node and we have visited his right sub tree so therefore we have completely visited his node 6 and here you can see node 6 is to the left of Note 3 so now you actually traversed the left sub tree for the Note 3 so therefore now we can visit the node 3 so in order to reach to node 3 we know that we already stored this node on the stack so we simply pop this element from the stack and we'll assign it to Temporary node so it would look something like this that Note 3 gets popped out and its value is assigned to Temp so therefore now temp will point to Note 3 and then we'll simply print the value associated with this temporary node which is actually three so three gets printed on the console and as you have visited the node 3 completely now we need to visit his right right sub tree therefore we are simply assigning temp right to Temp so now temp will actually point to null so now again we'll check the condition in while loop so first we check whether stag is empty or Not So currently stag is empty so the first condition comes out to be false and then we'll check whether temp is equal to null or not so here you can see temp is equal to null therefore the second condition comes out to be false so overall both the conditions are coming out to be false so the while loop terminates and here you can see we have actually visited all the notes of this binary tree and we have printed the data associated with those notes which is 4 25 1 63 so friend this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous tutorial we actually created one class by name binary tree and we actually implemented the binary tree into this class so friends in order to understand binary tree more you can watch my previous tutorials so in my last tutorial we actually discussed the recursive version of the inorder treat reversal but in this tutorial we will discuss the iterative way for the inorder treat reversal so here I will just comment this code and below I will create the method is in order now this in order method we'll take in a root so let's code the algorithm which we saw in the slide so in the first step we'll check that whether root is equal to null or not so if root is equal to null we'll simply return from this method because there are no notes in the binary tree to be traversed and the first step we'll create a stack which will hold the tree noes for us and as we discussed in the slide we'll create a temporary node and we'll start it from the root so tree node temp and we'll simply assign the value of root to it and now we'll simply provide a while loop and we also saw that we have placed two condition on that that whether stack is empty or not so the the first condition is we are checking whether stack is empty or not and then we are providing an r and the second condition we provide is time should not be equal to null so in the while loop we'll simply provide an F Els block so in the F blog will first provide a condition the temp should not be equal to null and if temp is not equal to null then we simply push the temp on the stack and then we Traverse temp to its left and if temp is equal to null then we simply pop an element from the stack and we will assign its value to the temporary node once we pop the element from the stack we'll simply print it on the console so temp do data and as we have printed the data on the console then we'll simply Traverse time to its right so friend this is the code for iterative in order treat reversal now let's test is working in the main method so here first we have initialized the binary tree and then we have created a binary tree with few notes so here in create binary tree we have actually created few notes which we also discussed in our previous tutorials you can watch my previous tutorial in order to understand how this binary tree is created and after creating the binary with few notes we'll simply call the in order method and we'll pass the root to that method so if I run this code now so here you can see it prints 4 293 because in the create binary tree the root is n and root left is second which is two and Roots right which is three so so here 9 left is is two and N9 right is three and here you can see second left is fourth now the fourth node is pointing to the seconds left so 9 is at the root its left is two and its left is four so therefore so on the console it printed four then it printed two and then 9 and then three because as N9 is on the root in order to process this node we have to first visit his left sub tree so on its left is the node two and and before processing the node two we have to go to its left sub tree so which is four so four gets printed first then we print the node 2 and then we actually print the root node and then we go to its right sub tree so we simply print three so so friends in this tutorial we discuss the iterative version of the inorder treat reversal I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss recursive post order traversal of a binary tree in Java so friends what is post order binary treat traval basically there are three steps involved in doing the post order binary tree traversal and all these three steps are applied over each and every node of a binary tree so if we take an example of a binary tree shown in the slide then basically we start with the root node and we apply these three steps over the root node so what actually we do is in order to visit this particular node first we actually visit its left sub tree completely then we visit Its Right sub tree completely and then we actually visit the node so here if we want to visit the node one then we have to first visit its left sub tree completely and then we have to visit Its Right sub tree completely and then we can visit the node and these three steps are applied over each and every node so suppose we are on node 2 so in order to visit this node what we have to do first we have to visit its left sub tree completely then we need to visit his right sub tree completely and then we can visit the node so therefore here before visiting the node 2 we have to first visit the node 4 then we have to visit the node 5 and then we can visit the node two so here basically these three steps are applied on each and every node of a binary tree in order to do Post order binary tree traversal so friends in this tutorial we are discussing the recursive post order binary tree traversal below you can see the algorithm for the Post order binary Tre traversal so we will demonstrate this algorithm using this binary tree here and we will see how we can apply this algorithm on this binary and whatever the output comes out it will be displayed here so friends as this algorithm is recursive in nature here you can see post order method is again internally calling the post order method therefore this is a recursive nature algorithm so in order to understand the recursive nature of this post order method we will maintain a call stack so that we come to know that which method is currently being executed and what is the root that is being processed we will come to know about line number when we will actually discuss the post order method so friends let's see the demonstration of this algorithm step by step so friends here you can see the root is pointing to the node 9 and when we call this post order we actually pass the root node so to this post order we are actually passing the root node as nine so Friends when the point of execution reaches this post order method we know that on the call stack there will be one method by the name post order and we also know that we have passed the root as nine so therefore on the call stack there will be one method by name post order which will start its execution moving ahead so friend the first step we actually check whether root is equal to null or not so if root is equal to null we simply return from that method and here you can see that this condition will act as our base case because as we are calling this post order method and internally again calls the post order method we need to provide a base case to stop the execution of this post order method because if we don't provide the base case post order method will again call Post order method and it will go on calling each other infinitely so this is the base case which is required in order to break the recursion and we will see its significance later in the demonstration So currently as you can see root is pointing to 9 therefore it's not equal to null so therefore the condition in if block comes out to be false and at the line number five we see it calls post order method again and this time we are passing Roots left which is the node two so friends as we discussed in our previous slide that in order to visit a particular node we have to first visit its left sub tree completely then we have to visit his right sub tree completely and then we can visit the node so therefore before visiting the node 9 we have to first visit this left sub tree completely so we are again calling the post order method and we are passing root. left to it which is nothing but the node two so here you can see when we had called this post order method there was one method on the call stack and inside this we are calling this post order method again so when we call this post order method we are leaving this post order method so in order to keep the track of this post order method we will update the line number here so it would look something like this that from line number five we are leaving this post order method and we are again calling the post order method with a root S two so once this line gets executed we know that post order method will be called again and this time this post order method will be called with the root S2 so therefore the line of execution reaches to the post order method again and we know that root will now point to the node two so now this method starts execution with a root S2 therefore we know that there will be one more method on the call stack so here now this post order method will start its execution with the root as two moving ahead we will check whether root is equal to null or not so here root is pointing to the node two therefore it's not null so the condition in if log comes out to be false and at the line number five we are again calling the post order method and this time we are passing root. left so your root left is nothing but the node 4 so why we are doing this step is because because in order to process this node 2 we know that we have to first visit his left sub tree completely then we have to visit his right sub tree completely and then only we can visit this node and we also discussed in our previous slide that all the three steps are applied to each and every node C of the binary tree so therefore before traversing the node two we have to first visit his left sub tree completely so therefore we are calling this post order method again with a root S 4 and we also know that we are leaving this post order method so we will update the line number here which is nothing but five so now point of execution reaches to this post order method with the root as 4 and we also know that now root will point to the node four and as this method will start his execution there will be one more method on the call stack with the root S4 so here now this post order method will start its execution with a root S4 so in the first step we will check whether root is equal to null or Not So currently root is pointing to the node for four therefore it's not null so the condition in if blog comes out to be false and then on the line number five we are again calling post order method with the value as root do left so friends in order to process the node 4 we have to first visit its left sub tree completely then we have to visit it right sub tree completely and then only we can visit the node 4 therefore we are again calling the post order method and this time we are passing the value as root do left so here root is pointing to node four and its left is pointing to null therefore now we are calling this post order method with a null value and we also know that we are leaving this method from the line number five therefore we'll update the line number here as five so the point of execution will reach to this post order method with the root as null so therefore now root will point to null and we also know so that there will be one more method on the call stack by the name post order and whose root will be null so now this post order method will start its execution with the root as null so here first we'll check whether root is equal to null or Not So currently you can see root is pointing to null therefore the condition in if block comes out to be true so therefore we have reached our base case so we'll simply return from this method so friends as we return from this method we know that this post order method is executed completely therefore this method will be removed from the call stack so friends when this method is removed from the call stack the call goes to his previous method which actually called this method with the root as null and we also know that we had left this post order method from the line number five so the point of execution reaches to this node and we'll start our execution from the line number five because at this line number we have actually left this method so therefore we'll start our execution from this line and we also know that when we had left this method at that moment root was pointing to node 4 so therefore now root will point to Note 4 moving ahead so friends at the line number six we are again calling the post order method but this time we are passing it a value as root. right which actually makes sense because in order to Traverse this node 4 we have to first visit his left sub tree completely then we have to visit his right sub tree completely and then we can visit the node so therefore on the line number five we have completely visited the left sub tree for the node 4 so now is the time to visit Its Right sub tree so therefore we are again calling the post order method and we are passing the value as root. WR so here root is pointing to note four and Its Right is pointing to null therefore we know that now we'll call this post order method with a null value and we also know that as we are leaving this post order method from the line number six we need to update the line number here so the line number becomes six so friends point of execution reaches to this post order method and this time the root will be null and we also know that once this method starts his execution there will be one more method on the call stack with the root as null so it would look something like this so we know that root is null so therefore now root will point to the null moving ahead we will check in the fog whether the root is equal to null or Not So currently you can see root is equal to null so therefore we'll simply return from this method and as we return from this method we know that this method is executed completely so this would be removed from the call stack and the point of execution reaches to the post order which actually called this method and we also know that we had left this post order method from the line number six therefore the execution will start from the line number six and we also know that when when we had left this method root was pointing to the node 4 so therefore now root will point to node 4 moving ahead so friends on line number seven we will simply print the data associated with this route so friends in order to process the node for what we have actually done is we have first visited it left sub completely then we visited the right sub completely so after doing this this stuff we are actually visiting the node 4 so we are simply printing its data on the console which is for moving ahead so friends at the line number eight this post order method on the call stack will complete its execution so this would be removed from the call stack completely and the point of execution will reach here and we also know that we had left this post order method from the line number five so the point of execution reaches to the line number five and we also know that at that time Root was pointing to node two so here now root will point to node two and we'll start our execution with this post order method so friends in the line number six we are again calling the post order method and this time we are passing root. right to it so here you can see root is pointing to node two so we'll pass root. right which is null to this post order method so friends here you can see we are calling this post order method again with the root as null because root. WR is nothing but null value and we also know that we are leaving this method so we'll update the line number here and we know that line number is six so now line number changes to six so root is pointing to the node two therefore now it will point to its right which is null now this method will start this execution so therefore there will be one more entry on the call stack with a root as null moving ahead we'll check whether the root is equal to null or Not So currently root is equal to null so therefore we'll simply return from this method so when we return from this method we know that this post order method is executed completely so therefore it will be removed from the call stack and once it's removed from the call stack the point of execution reaches to this post order method and we also know that we have left this method the line number six so we'll start its execution from the line number six and we all also know that when we had left this method root was pointing to node two so here root is pointing to null so now it will point to node 2 moving ahead and at the step seven we'll simply print the data associated with the root which is nothing but two so friends here you can see before processing of the node 2 we first completely visited its left sub tree and we printed node 4 and then we visited this complete right sub tree which was actually null and then we actually visited the node 2 so it printed something like this four and then two moving ahead so at line number eight we know that this post order method is been executed completely so therefore this would be removed from the call stack and the point of execution reaches to this post order method and we also know that when we had left this post order method from the call stack the line number was actually five so we'll start our execution from the line number five and we also know that root at that time pointed to the node 9 so therefore now root will point to node 9 and our execution starts from line number five so friends here you can see that we are on node 9 and in order to visit this node we have to first visit its left sub Tre completely which you actually done and then we have to visit the right sub Tre completely so now we'll start to move to its right and then we can process this node 9 so we are again calling the post order method and this time we are passing the value as root. right because we have to now visit Its Right sub tree completely so therefore you can see Roots right is nothing but node three so we will be again calling this post order method with a root as three and we also know that we are leaving this method post order from the line number six so therefore we'll update the line number here so now point of execution again starts post order method and this time with the root as three so now root is pointing to the node three and we also know that there would be one more method on the call stack with the root as three so friends now let's start the execution of this post order method with the root S three in the first step we'll check whether root is equal to null or Not So currently root is pointing to node three therefore it's not null and at the line number five we will again call Post order method and this time we are passing Roots left which is nothing but the null value so here before processing of node 3 we know that we have to first process the left sub tree and then we have to process the right sub tree so in order to process it's left sub tree we are calling this post order method again with roots left which is nothing but the null value so friends we are leaving this post order method at line number five so we will update the line number here and then point of execution will call this post order method again with root as null so now root will point to null and we also know that there will be one more method on the call stack with the root as null so now let's execute this post order method with the root as null so here we check whether root is equal to null or Not So currently root is equal to null therefore we'll simply return from this method so once we return from this method we know that this method is executed completely so it will be removed from the call stack and point of execution will reach to this post order method and we know that we had left this post order method from the line number five so therefore we'll again start our execution from the line number five with a root as three So currently root is pointing to null so now it will point to three so we are starting from line number number five and our root will point to node three moving ahead so the line number six we will call postorder method again and we'll pass the value as root. right because in order to Traverse this node we have to Traverse his left sub tree first which we have already done so now is the time to Traverse his right sub tree and after traversing right sub we can actually visit this node three so in order to visit is right subtree we are calling this post order method again and we are passing the null value to it and we also know that we are leaving this method at line number six so we'll update the line number here so now point of execution will start the execution of this new post order method with the root as null so root is pointing to node 3 now it will point to null and we also know that there will be one more method on the call stack with the root as null so let's start the execution of this post order method with the root as null so we'll check whether root is equal to null or Not So currently root is equal to null therefore we have actually visited the right sub tree for the node three so we'll simply return from this method and as we return from this method this post order method will be removed from the call stack and point of execution will reach to this post order method and we know that we are left this post order method from the line number six with the root as three so we'll start the execution from the line number six and we know that at that time Root was pointing to three so now root will point to node three so friends we have visited the left sub tree for the node 3 and we also visited the right sub tree for the node 3 so now we can actually visit the node 3 so on the line number seven we will simply print the data associated with this route which is nothing but three moving ahead and once we reach the line number eight we know that we have successfully executed this post order method so this method will be removed from the call stack and the point of execution will reach to this post order meth method and we also know that we had left this post order method from the line number six and at that time the root was actually nine so we are starting from the line number six and we know that we had left this method when the root was pointing to 9 so therefore now root will point to 9 moving ahead so friends here you can see for the node 9 we have come completely visited its left sub tree and we have printed four and two then we actually visited the right sub tree completely and we printed three so now is the time to visit the node 9 so we are simply printing the data on the console for the root which is pointing to node 9 so now 9 will be printed on the console and from the line number eight we know that we have completely executed this post order method so this should be removed from the call stack and once this is removed from the call stack we know that there are no more methods left to be traversed so here we have actually successfully executed this recursive post order traversal to this binary tree and we have printed it each and every node on the console as 4 2 39 so friends this was the demonstration of the algorithm now let's go to eclipse and see the working code so friends in my previous Tut tutorial I had created one class by name binary tree and we actually implemented the binary tree into this class so in order to understand the implementation of this binary tree you can watch my previous tutorials so in this tutorial we will actually code recursive post order traversal of a binary tree so here I will create one method as public void post order so this is the same method which we discussed in the slide so this method takes in a root which is of type tree node so first we'll provide the base case which is we will check whether root is equal to null or not so if root is equal to null then we'll simply return from this method so this is nothing but the base case because we are calling this post order method recursively so friend as we discussed in our slide that in post order tree traversal before visiting any node we'll first visit his left sub tree and then we'll visit his right sub tree and then we can visit the actual node so first we'll visit the left sub Tree by calling root. left and then we'll visit Its Right sub Tree by calling root. WR and after visiting the left sub tree and the right sub tree we'll actually visit the node so we'll simply print root. data on the console so friend this is the code for recursive post order binary treat reversal so now let's test it's working on the main method so here in the main method we'll first initialize this binary tree class and then we'll create the binary tree so in create binary tree method we are actually creating the binary tree with few notes and these are the same notes which you discuss in the slide and we also discussed this method in my previous tutorials so you can watch my previous tutorials in order to understand how we have created this binary tree with a few notes so after creating this binary tree we'll actually call the Post order method and we'll also pass the root into it so if I run the code now so you can see it printed 4239 which is the same output which we discussed in the slide so friend in this tutorial we discussed about the recursive postorder binary tree traversal I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day hello everyone so in this video we will discuss about the iterative post order traversal of a binary tree so in our previous videos we discussed about the recursive post order reversal of a binary tree and in this lecture we will see the iterative approach to Traverse the binary tree using the post order so here you can see let's say we are given with this binary tree and we want to Traverse this binary tree using the iterative post order traversal so in our previous video when we discussed about the recursive approach to Traverse the binary tree we disced discussed that in order to Traverse a binary tree using post order what we do is before visiting the route we visit all its element on the left sub tree then we visit all its element on the right sub tree and then we actually visit the root and usually these three steps we perform on each and every node of a binary tree when we do the traversal in a recursive way so in case you want to learn more about that you can watch my previous video video so the only thing we need to remember here is when we do Post AIT reversal on every node we need to First reverse all its elements on the left side then we need to visit all its elements on the right side and then we can actually visit the node so for example if we are on node 2 then we can't directly visit the node 2 we need to visit first the node 4 then we need to visit node 5 and then only only we can visit the node when we are performing the post order reversal so in this video we will discuss the iterative approach where we are not performing any recursion so when we perform post order traversal using the alterative way we usually take the help of a stack so stack is nothing but a Leo data structure which means last in first out where the last element inserted will be the first one to be removed so we will use the stack data structure to Traverse this binary tree using the post order traversal so let's see the demonstration of this algorithm step by step so at the first step what we do is we create a tree node current which simply points to the root and in the middle of this algorithm we are also creating one temporary tree node we will see their advantages later in the algorithm so in the first step we are simply creating the current and pointing it to root then we are actually creating the stack data structure so this is our stack data structure and we are using the stack class present in Java so as we want to perform this post order traversal we need to visit each and every node of this binary tree and as we are following a iterative approach we are providing a while loop where we are providing the two conditions first is the current is not equal to null or stack is not empty so here you can see current is pointing to a node having value as one therefore this condition comes out to be true because current is not equal to null so the overall condition of this V Loop comes out to be true because any of this condition if comes out to be true this file Loop will execute so here you can see in the first step what we are checking is that if current is not equal to null then we simply go inside this if block or else we perform this logic so why we are providing this condition here is let's say current is pointing to a node having data as one and let's suppose we want to visit this node so if the current is not equal to null then we can't directly visit this node we need to first visit all the elements of its left sub tree and then we need to visit all the nodes of its right sub tree and then only we can visit this node so current will be null at this location and when current will be null then we can simply decide that now can we visit the node or not so here as current is not equal to null so there can be a possibility that this node has a left sub tree so what we do is we simply push node one into the stack and then we simply Traverse to its left by assigning current's left to current so current is pointing to node one its left is pointing to node two so now current will point to node two we again check where current is equal to null or not so current is not equal to null so the first condition comes out to be true and we don't evaluate the second condition because of this or operator so this V Loop will execute we check whether current is equal to null or not so current is not equal to null so this condition also comes out to be true because there can be a possibility that node two has a left sub tree so what we do is we simply push the current on the stack so two will be on the stack and then we simply visit current to its left so current will now point to two's left which is four and similarly current is not equal to null so this condition comes out to be true here current is not equal to null because it is pointing to node 4 so we simply push current onto the stack because there can be a possibility that there is a left sub tree or a right sub tree so four is on the stack and we go to its left by assigning current left to current so current will point to its left which is null value so friends here you can see now current is actually pointing to null now if the current is pointing to null so this null can be on the left side of this node or on the right side of its node so if the current is on the left side of the node then we know that we need to visit the right side also before visiting this node but if the current is on the right side of the node then we know that we have already visited left we have already visited right now we can visit this node so in the post order we discussed that in order to visit any node we need to visit all its left children then we need to visit right children so if current is pointing to a null then there can be two possibilities that this null value can be on the left side and this null can be on the right side so if the null is on the left side we need to visit the right sub tree for this node and if the current is on the right side then we know that we have already visited left and we already visited right then you can simply visit the node so so here current is equal to null so this condition comes out to be false but our second condition the stack is not empty so this condition comes out to be true and overall condition comes out to be true so while loop will execute this if check will fail because current is actually pointing to null so now we'll go to the else part so in the first step what we do is we create a temporary variable and we assign a value stack. peak. right so here you can see in the stack whichever is the last element inserted is the peak of the stack so when we do stack. Peak we are simply pointing to this node four and if we do do right then we are actually pointing to nodes right so here this is four and right will be null so we will see why we are creating this temporary variable so for timing you can see that temp is pointing to null now here we are given two conditions that whether temp is equal to null or temp is not equal to null so why we have provided this condition is because let's say if current is pointing to null then we need to somehow check that whether this null value is on the left side of node 4 or on the right side of the node four so in order to verify that thing we created this temporary node so as current is pointing to null so this can be any left or right sh of a node and we also know that this node will be already present on the stack and if you want to know that whether we are on the left side or on the right side what we do is we simply go to this node and go to its right so your temporary variable is doing that for us so here why we providing this check here is if temp is equal to null so this will signify that whatever the value was on the stack Its Right is actually pointing to null and there are no nodes left to be traversed on the right side of this node so what we can simply do here is pull this element out because we are now sure that as current is pointing to null and temporary is pointing to null which means that we have traversed the left sub tree and the right sub tree for this node so now we can simply pull this node out and we can simply visit it so we'll pull this element out and now temp will point to four and in The Next Step we'll simply visit the temp so we are simply printing the data of the temp which is four here so friends why we actually do all this stuff is when current actually reaches to any null value then we need to be sure that whether it's on the left side or on the right side so we simply create a temporary variable to Simply Peak the right side of a node present in the stack and if the temp is equal to null then it simply signifies that there are no notes on the right side and we have already visited the left side so now it's turn to visit the actual node so we have visited four here moving ahead so friend now here we provide a while loop and why we have provided while loop because the first thing we are checking stack is not empty so as we have recently pulled an element out of it so there can be a chance that stack becomes empty so stack should not be empty and the second condition is very important which is the core of this algorithm is we are simply checking with the temp is stack. Peaks right so here you can see so as we have recently visited this node here so there can be a possibility and we need to be sure that whether this node is on the left of two or on the right of the two because if it is on the left of two then we can't directly visit two we need to go to its right and visit node 5 but if it is on the right side then we can simply visit the node two so here stack Peak is node two this and Its Right which is this value is node five so we are simply checking whether this node which we visited just now its values equal to its parents right or not so if this value comes out to be true then we know that that parent right is actually the node which we just now visited so we can simply visit the parent now but here you can see temp is pointing to four and stack Peak which is the node two is pointing to right therefore they are not equal which means that whatever the node we have visited just now it's on the left side not on the right side of node two so this value will terminate and our call will reach to this V loop again so friends here why we have provided this V Loop it will be clear when we reach here so for timing you can just think that we have provided a while loop here so moving ahead here you can see current is pointing to null but stack is not empty so the overall condition comes out to be true current is equal to null so we go in the else now in the first step what we do is we simply assign the stack peak's right value so stack Peak is node two this node and Its Right is node five so temp will point to five so friends why we are assigning this value now here is as current is pointing to null and we have recently visited node 4 and we also verified here that node is at the left of two so there can be a possibility that node two might have a right sub tree and in post order traversal after visiting the left part we need to visit the right part and then only we can visit the parent so here we are simply assigning the value of stack. peak do right so two's right is five so temp will point to five and here we'll check whether temp is equal to null or not so your temp is not equal to null which signifies that the right part there is a node which also can have left and right children so and we can't directly visit this node because there might be possibility that it contains left and right children so here if the this condition comes out to be false and and we go in the else part where we'll assign the current to the temp so why we are assigning current to Temp because this five can be treated like any other note which can have the left and right children so as we started by pointing current to root it is similar to that step that this node can have a left or a right children so we need to perform all those steps again on this node so here current is not equal to null so this condition comes out to be true and if the current is not equal to null so this is the same case which we discussed here that current is not equal to null there can be a chance that this node have a left children so what we do is we first push the five on the stack and then we go to its left by assigning currents left to current so current will point to null so as current is pointing to null so this condition is false but our second condition is true because stack is not empty and here you can see current is equal to null so this condition also comes out to be false and we go into the else part in the First Step we are assigning stack Peaks right value to temp so stack Peak is node five this node and Its Right is this value so we are assigning null to Temp and then we are simply providing this check because if temp is null then we know that current is already pointing to null which is the left part and temp is also pointing to null which is the right part so it signifies that its parent has no CH left and right children so we can simp simply visit the parent now so in the first step what we do is we pull the topmost element which is the which is the node 5 and we'll assign it to Temp so first this will pull out and temp will point to five so we can safely visit this node because we have already visited its left and right children so five will be visited here and then we are providing this V Loop which we will discuss when we reach here so just for timing think that we are providing this Val to check whether the node which we have visited is on the left or on the right side of its parent So currently stack. Peak is two which is parent to five and if you see here do right is this value only and temp is also pointing to this node so this condition temp equal equal stack. peak. right is actually true because we are on the right side of the parent and we have already visited this note so now we can simply pull this element out and we can simply visit because we have already visited its left part and the right part so this Val Loop condition will come out to be true we are pulling two out and temp will point to node two and then we are simply printing the data of this note by visiting it so two will be printed so as it is a while loop we are again checking that whatever note we visited just now is it on the left side or on the right side of its parent so the first condition is stack should not be empty because we have recently pulled an element out so there can be a possibility the stack is empty so your stack is not empty and the second check verifies that whatever the value we have here which is the parent to this node so here we are simply verifying that this temp is on its left or on its right side so temp is actually on the left side so this condition comes out to be false so our execution Point reaches to this V Loop where here you can see current is equal to null but stack is not empty so here current is equal to null so this condition comes out to be false in the else part we will assign stack. peak. right value to Temp so stack. Peak is 1 and Its Right is node three so temp will now point to node three moving ahead we check whether temp is equal to null or not so temp is not not equal to null so this condition comes out to be false so if this condition would have come out to be true and temp would have point to null then we could have visited this node directly but as temp is not equal to null so there can be a possibility that this node can have left or right children so we simply go to the else part and we assign the value of time to current so now current will point to this node because you have figured out that there can be a possibility that three can have left or right childrens so current will point to three so now this is the same situation which we saw in the start that current is not equal to null and if current is not equal to null there can be a possibility that there could be a left children of it so we are simply pushing the current on to the stack so three will be on the stack and then we go to its left by assigning current's left to current so current will now point to null so as current is equal to null but stack is not empty this overall condition comes out to be true so we check whether current is equal to null or not so current is equal to null so in the else part we will assign Stacks Peak right value to Temp so stack Peak is note three and Its Right is six so now temp will point to six and here we check whether temp is equal to null or not but here you can see temp is not equal to null so there can be possibility six can also have left or right children so in the lse part we simply assign current to six current is not equal to null and in the if check also current is not equal to null and there can be a possibility that six can have left children so we push six on the stack and we go to its left by assigning current left to current so current will point to null now which is the left of six current is equal to null but stack is not empty so this condition comes out to be true and overall condition comes out to be true because of this R operator here the if condition comes out to be false because current is pointing to null and then we simply assign stack. peak. right to Temp so stack Peak is node six this node and Its Right is this node node so temp will now point to null and here we are providing this check that if temp is equal to null which means that current is pointing to null and whatever its parent is its right is also pointing to null so we can safely visit this node which is the parent so how we can safely visit that node is first we'll pull that element out of the stack so six will be pulled out and 10 will point to six we will visit this node so six will be visited now friends here we encountered a while loop and we discussed that why we are providing this V Loop is because the first check is stack should not be empty so stack has two nodes therefore it's not empty now as we have recently visited this node so after visiting this node we need to be very much sure that whether this node was at left or was at right to its parent which is three we can access three by Stacks Peak which is by getting this value and if you call do right if you call do right then we'll reach here only so if temp is equal to this value only then we know that we are actually on the right side of temp's parent which signifies that we have already visited the left part we have completely visited the right part and now we can simply visit the parent so here we pull the parent out and time will point to three we visit three and we again encounter the while loop so friends here you can see that this while loop is provided because if this is the condition here then here you can see the stack is not empty and as you have visited three so this three can also be the right child of its parent so therefore we are providing this V Loop let's say if this chain goes on like this and there are no left notes so this value will simply make us Traverse back because all these notes are on the right side of its parent which we already visited so that's why we are providing this file Loop so here again we are simply checking whether temp is pointing to its parents right or not so here stack. Peak will give us one Its Right will give us node three and temp is also pointing to node 3 so this file Loop condition will come out to be true and we can simply pull one out because we have visited all the left sub tree of the node one and we have recently visited all the nodes on the right sub tree of one so we can simply pull the one out Tam will point to one and we can simply visit node one now so node one will be visited here and finally we again check whether stack is empty or not so here you can see we have recently pulled one element out so stack is empty so this condition comes out to be false and the while loop will terminate and once the while loop will terminate our call will go reach here so here you can see current is equal to null this condition is false and our stack is also empty which signifies that we have completely visited this binary tree using the postorder traversal so this whole condition will come out to be false so friends here you can see that using a stack we visited all the notes of this binary tree using the postorder traversal so this was the sequence first four was visited then five got visited because before visiting two we need to visit its left part then we need to visit the right part and then we can actually visit the node so two was visited after that now we can't directly visit one because we need to Traverse all the notes of its right sub tree so we reached here we saw that three didn't have any left part so we can't visit Three directly we went to its right we saw that six left and right both are null so we simply visited six then after we visited six which was on the right side we safely visited three and three was was also on the right side so we safely visited one so this is the postorder reversal of a binary tree so friend this was all about this video and in case you have liked this video then please like comment share and subscribe my channel thanks have a nice day hello everyone so in our previous lecture we discussed that how we can do Post order traval of a binary tree using the iterative approach so in this video we will code the algorithm and we'll test its working so here you can see in intell J I have created one class as binary tree so this class we created in our previous videos which has a root of type tree node so this is the private class inside this binary tree which simply has left and right children we discussed other traversal algorithms such as pre-order in order and we also saw recursive and iterative approaches so in this video we'll see the post order traversal of a binary tree using the iterative approach so here I will be creating one method as public void I'll give a name as post order so here when we discussed post order traval using the recursive approach we saw that before visiting the nodes data we need to visit first its left sub tree then we need to visit its right subtree and then only we can visit the nodes data so this was a recursive approach which got implied on each and every node of the binary tree so when we perform the iterative approach we usually use the while loop and we Traverse each and every node of the binary tree keeping the post order traversal in mind and the data structure will help us doing this is the stack data structure which is the Leo data structure which is also known as the last in first out so the last element inserted inside the data structure will be the first one to be removed so we discussed this algorithm step by step in our previous video using us an animation so now let's code the algorithm and test its working so in post order method the first thing we do is we create a tree node current which starts from the root of the binary tree whose traversal we need to do in the second step we create a stack which will hold our tree notes we give it a name as stack and we are using java. utils stack class we can also use our stack which we discussed in our previous videos but here I will be using the java.util stack now in order to perform the post AO traval we need to provide a while loop and inside that V Loop we provide a condition as current should not be equal to null or stack should not be empty so here you can see that current is pointing to root and we need to go inside this V Loop to Traverse each and every node of the binary tree using post order so the first condition we provide is current should not be equal to null and when current is equal to null then the logic we apply we'll see later in the algorithm and the other thing is the stack should not be empty so here you can see in this Val Loop we provide a condition as current not equals to null so if current is not equal to null then it signifies that we can't visit the current directly we need to first go to its left sub tree and visit that then we have to go to its right sub tree and visit that and then only we can visit that particular node so if current is not equal to null so there is a possibility that current might have a left sub tree so the first step we do is we simply offer or you can say push the current on the stack and after pushing current on the stack we simply go to its left by assigning current's left value to current and if current is equal to null then we provide else part where what we do is we create a temporary node and we assign the stacks Peak values right to it so friends here if the current is pointing to null then we need to follow the steps to identify that whether that current is actually the left child of the parent or at the right child of the parent because if it is the left child of the parent then we can't visit parent directly we need to go to its right first but if it's the right child of the parent then we can simply visit the parent so if the current is equal to null in order to identify that the first thing we do is we take its parent which is on the stack and we'll simply assign the right value to Temp so here after getting this temp there are basically two conditions one is what if the temp is also null so this check basically signifies that if temp is pointing to null and as we have moved to parents right and temp is pointing to null it means that there are no write Children of the parent so we can simply visit the parent because when we do Post order traversal in order to visit the parent we first visit its left sub tree and then we visit Its Right sub tree and then only we can visit the parent and as we are on the right part and that is coming as null it means that we have visited the right part and now we can safely visit the parent so here what we do is we simply pop the element from the stack and assign it to the temp so once the temp is pointing to parent what we do is we simply visit the parent by printing its data on the console and after visiting the note we again provide a while loop and inside that value we provide the condition and stack should not be empty because we have recently popped an element from the stack so stack can be empty so here we are providing this one condition that stack should not be empty till this point and so here as we have visited this node now this note can be a children of its parent and it can be on the left side or on the right right side so there are also now two conditions coming up here if the temp is on the left side then we know that we need to go to the parents right now because we have visited the temp here but if the temp is on the right side then we know that we have once we have visited the right side we can simply visit the parent so here we need to provide one more condition as if temp is equal to stack do Peak do right so this condition signifies that whatever the peak values on the stack it would be parent to Temp and if its right value is equal to Temp it means the temp is on the right side so if it is on the right side then we can simply again pull the element from the stack assign it to Temp and and we can simply visit that and also friends as here we are popping out an element and visiting it we need to provide this in while loop because there can be a chance that whatever we are visiting it's actually coming out to be the right of the parent so once this condition comes out to be true and we pop the parent from the stack there can also be a chance that whatever we visited here will also be on its right of its parent so we need to provide this V Loop because whenever we are visiting any element by printing it on the console here or here we need to Simply perform a this check that what we visited was at the right of its parent or was it at the left of its parent so if it is on the right of its parent which is this condition then we'll simply keep on popping the element out and simply printing its data because in the post order reversal this is the main step that once the right children of any node is visited then only we can visit the parent so here this condition is signifying that only so this was the part in the if condition and let's say if the temp is not equal to null it means that when we Peak the parent element and we went to its right that was not null so before visiting right directly there can be a possibility that right also has left or right children so therefore these two checks are important if temp is null then we are sure that right is already visited we pop the element out we print its data and then we again check it for its parent but if the temp is not equal to null then we know that we need to visit the right part also and once we go to its right part the right part can can also have its own left and right childrens's so here now our condition become something like this what we did here so here what we do is we simply assign the value of temp because it is not equal to null to current so friend this was all about this algorithm now let's test it's working in the main method so friends here you can see that in our previous videos we created one binary tree with this hardcoded values so where root was pointing to one one had two childrens left and right as second and third this two second had two children's left and right as fourth and fifth this two and third note at left and right as sixth and seventh so these two notes so so here one is at the root second and third are its left and right children four and five are left and right children of two and six and seven are left and right children of three so this was the hardcoded binary tree so here after creating this binary tree what we can do is we can simply call the Post order and we can run the program so friends here you can see it printed 4 5 2 6 7 3 1 here in this binary tree before visiting one which was the root we need to visit two and three so two was at left so when we reach to two we can't visit two directly because two also has left and right children which is four and five so when we reached to four we found that four didn't have any left and right children so the first thing we visited was four because this was the left of two and then we visited five because five was right of two and after visiting the left and right children we visited two here and once we visited two we know that we have visited all the left Children of the actual route so now it was time to go to its right binary tree so when we went to one's right we found three so we can't visit Three directly because three has a left and right children which is six and seven so when we went to six we found that six didn't have any left and right children so we safely visited six and then we safely visited 7 because seven was right to three so after visiting six and seven which was the left and right children of three now we can safely visit three and once we visited three we were pretty much sure that we have visited all the notes of the right sub Tre of the actual route which was one so finally we visited one so friend this was all about the post order reversal and in this video we demonstrated about the iterative approach using the stack data structure so here in case you find any difficulty you can watch my previous video to this which had all the things in animation so that it becomes more clear to you and in case you have liked this video then please like comment share and subscribe my channel thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friend friends in this tutorial we will discuss level order traversal of a binary tree in Java so friends what is a level order traversal so here we use this traversal technique to visit the notes of a binary tree level by level so here you can see the root is at level zero 2 and three are at level 1 4 56 are at level two so in this traversal Technique we first visit the level 0 then we visit the level one and then we visit the level two so when we actually visit the node and printed data on the console so it will be like first one will be printed then two then three then four 5 and six so here when we do a level order traversal of a particular level then we actually store the elements of its next level on additional data structure which is nothing but the Q so here suppose we are visiting the node one then on the que we put the node 2 and node 3 so that after visiting the node one we can pull the node 2 and node 3 and we can visit them and while we are visiting the node 2 we put four and five on the Queue and when we are visiting the node 3 we put node 6 on the Queue so therefore it goes level by level and the additional data structure which we use to store this element is a q so basically in this traversal we are using Q because it is a fif for data structure which is nothing but first in first out so the element inserted first will be the first to be removed we will see its significance when we demonstrate the algorithm so let's start execution of this algorithm step by step so let's suppose we are given this binary tree where root is pointing to the node one so when this algorithm starts we first check whether root is equal to null or not so if root is equal to null then we simply return from the method because there are no notes in the binary tree to be traversed and here you can see as root is pointing to the node one therefore the condition in if block comes out to be false and then next step what we do we first initialize the Q data structure so here you can see the Q data structure where nodes are entered from one end and they are removed from the other end so this property makes q a fifo data structure that is the element inserted first is the first one to be removed and in order to know more about the cues you can watch my previous tutorials on the Q data structure and in this tutorial we will use the Java implementation of the queue which is nothing but a link list so we will initialize the queue by creating the instance of the link list so after creating the queue what we first do is we offer the root node to the que here offer is nothing but the inq operation where we add the element to the que so in the first step what we do is we offer the root node to the que so it would look something like this as root is pointing to node one therefore in the first step what we do is we basically add node one into the Q so it would look something like this that is the node one is in the queue moving ahead so friends in order to Traverse this binary tree using the level order traversal we basically use a while loop and inside this while loop we place a condition as that we will iterate this while loop till Q is empty so currently you can see Q is having one node which is node one therefore it's not empty so the condition in while block comes out to be true so in the first step what we do is we actually pull the element from the queue and we assign it to the temporary node so here you can see Q is having one tree node having data as one so when we perform a pole operation on the Q node one will be removed and its value will be assigned to Temp so it would look something like this so node one is removed from the que and temp is now pointing to the node one so whatever the value we pulled from the que we simply assigned it to the temporary node moving ahead so after pulling the note from the queue we simply print it data on the console so one got printed on the console it means we have visited the node one and as we discuss earlier that when we visit any particular level we store the elements of its next level on the queue so here we first check that whether temp. left is equal to null or not so temp is pointing to node one and it's left is pointing to node two therefore the condition in if blog comes out to be true because time do left is not equal to null so in the F blog we simply offer temp do left element to the Q which is nothing but the node two so it would look something like this that now node two is on the que moving ahead we then check whether temp. right is equal to null or not so here you can see temp. right is pointing to node 3 therefore it's not equal to null so the condition in if blog comes out to be true and here we simply offer temp. right which is the node three on the Q so now node 3 is also on the Queue moving ahead now in the while we check whether Q is empty or Not So currently Q has two notes therefore it's not empty so the condition in while block comes out to be true and then we simply pull an element from the que and we'll assign it to Temp node so here you can see when we do a poll on the que the element which was inserted first would be the first to be removed so therefore now two will be removed first and time will point to the node two so it would look something like this that node two is removed from the que and its value will be assigned to the temp so it means that temp is pointing to the node two moving ahead and then we'll simply print the data associated with the temporary node which is nothing but the two so two will be printed on the console moving ahead and when we are visiting the node two of any particular level then we have to add its left and right element on the Queue so here first we will check whether temp. left is equal to null or Not So currently temp. left is pointing to node 4 therefore it's not null so the condition in if blog comes out to be true and then we will offer temp do left to the Q which is nothing but the node four so now node four will be part of the Q moving ahead and then we will check whether temp. right is equal to null or not so temp. right is nothing but the node 5 and it's not equal to null so the condition in if blog comes out to be true and we'll simply add the node five on the Que moving ahead we again check whether Q is empty or Not So currently Q has three nodes therefore it's not empty so the condition in while block comes out to be true and then we'll simply pull the element from the Q so when we perform a pole operation the element which was inserted first is first to be removed so here you can see node 3 is the first element so now now it will be removed from the queue and its value will be assigned to the temporary node so it would look something like this so node 3 is removed and its value is assigned to the temporary node so now temp is pointing to the node 3 moving ahead and then we'll simply print the data associated with the temporary node which is nothing but three so three gets printed on the console and then we'll simply check whether temp. left is equal to null or not so here you can see temp. left is nothing but node 6 therefore it's not equal to null so the condition in if blog comes out to be true and then we'll simply store the node 6 on the Queue moving ahead and then we will check whether temp. right is equal to null or not so here you can see temp. right is equal to null so therefore the condition in if log comes out to be false because we are not storing the null value on the Q we again check whether Q is empty or Not So currently Q is three not therefore it's not empty and the first step we simply pull the element from the que and we'll assign it to the temporary node so here node 4 will be removed from the queue and temp will now point to the node 4 so it would look something like this so now temp is pointing to the node 4 and now we'll simply print the data associated with the temporary note which is nothing but four so four will be printed on the console and then we'll simply check whether temp left is equal to null or not so temp left is equal to null therefore the condition in if blog comes out to be false and we'll check whether temp right is equal to null or not so temp right is also equal to null therefore condition in if blog comes out to be false and then again in while loop we'll check whether Q is empty or Not So currently Q has two nodes therefore it's not empty so the condition of V block comes out to be true and in the first step we'll simply pull the first element from the que which is nothing but node 5 and we will assign it to the temporary node so it would look something like this so now temp will point to the node 5 moving ahead then we'll simply print the data associated with the temporary node which is nothing but five so now five will be printed on the console moving ahead and then we will check whether temp left is equal to null or Not So currently you can see temp left is equal to null therefore the condition in IFL comes out to be false and then we'll check whether temp right is equal to null or not so here temp right is equal to null therefore the condition and the if blog comes out to be false and then we go to while and we'll check whether Q is empty or Not So currently Q has one node left therefore it's not empty so the condition in while block comes out to be true so we'll simply pull the element from the Q which is nothing but the node 6 and we'll assign it to Temporary node so it would look something like this so the node 6 is removed and now temp will point to the node 6 moving ahead so finally we will print the data associated with the temporary node which is nothing but six so we have printed the data associated with the node 6 moving ahead we will check whether temp left is equal to null or Not So currently temp left is equal to null therefore the condition in if blog comes out to be false and then we'll check whether temp right is equal to null or not so temp right is equal to null therefore the condition in if blog comes out to be false and finally we will again check whether Q is empty or Not So currently here you can see Q is empty so therefore the condition in while block comes out to be false because Q is empty so there are no more nodes left to be traversed so therefore this while loop terminates and we know that we have visited all the notes of this binary tree level by level so here you can see we first traversed node one then we visited node two then three then four then five then six so friend this is the algorithm for the level order traversal of a binary tree now let's go to eclipse and see its working code so friends in my previous tutorial I had created one class by name binary tree and we implemented the binary tree into this class so you can watch my previous tutorial to know more about how we have implemented the binary tree so in this tutorial I will be coding the algorithm for label order traversal of a binary tree so here I will be creating one method as public void and I will give the name to his level order so in this method we will be coding the level order traval of a binary tree so in the first step we'll check whether root is equal to null or not so if root is equal to null then we'll simply return from this method because there are no nodes in the binary tree to be traversed and then we'll initialize a q which will hold the tree notes for us and here we are using the Java implementation of the queue so we'll import it from the java.util package so after we create the instance of this queue we'll simply offer the root node now we'll create a while loop and inside this while loop we'll place a condition as that we iterate this while loop till Q is empty so inside this value we'll first create a tree node by name temp and to this temporary note we'll pull the element from q and we'll assign its value to the temporary node and after pulling the element from Q we'll simply print its data on the console so we'll do temp. data so after printing the data associated with the temp node we will store its left and right node on the Queue so we'll first check that whether temp left is equal to null or not so if it is not equal to null then we'll simply offer it to the que and similarly we'll do do this for the temp right so I will just copy it and I will make it to Temp right so friend this is the algorithm for the level order traversal of a binary tree now let's test is working in the main method so in the main method we'll first create the instance of this binary tree class and then we'll actually create the binary tree so here you can see I have created this binary tree with the few notes so this is the binary tree which we discussed in the slide and in order to know more about this create binary tree method you can watch my previous tutorials so after creating this binary tree we will then call the method level order and if I run the code now so here you can see it printed 1 2 3 4 5 6 7 which we actually discussed in the slide that it prints level by level so friends in this tutorial we discussed about the level order traversal of a binary tree I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day hello everyone so in this video we will discuss that how we can find the maximum value in a binary tree and we'll discuss an algorithm which is recursive in nature so here you can see let's say we are given with this binary tree having notes as 4 3 7 5 and 8 and four is at the root so let's say we want to find the maximum value inside this binary tree so looking at this binary tree we know that 8 is the maximum value but how to find whether 8 is the maximum value in this binary tree is using this algorithm which is recursive in nature because here you can see the method name is find Max which takes in a root and inside that it again calls find Max so your find Max method is calling itself at two places at line number six and line number 7 so therefore this algorithm is recursive in nature so here the idea behind finding the maximum value in a binary trees let's say we know the value of fruit and we know what's the maximum value in the left sub tree and what's the maximum value in the right sub tree so we can simply compare the maximum value of the left sub tree with the roots value and then we can compare with the maximum value of the right sub tree and we can come to know what's the maximum value among these three values so this idea can be applied on each and every node recursively so for example if you want to find the maximum value of this binary tree having three notes as 3 5 and 8 we can simply take the roots value then we need to calculate the maximum value of the left sub tree and the maximum value of right subtree and we need to Simply compare these three values and we will get the maximum value till this node so this algorithm is recursive we need to apply this three steps on each and every node and using this algorithm we will also Traverse each and every node because in order to find which is the maximum value among this binary tree we need to Traverse each and every node so let's see the demonstration of this algorithm step by step so that the idea of finding the maximum value inside this binary tree will be more clear to you also here you can see as this algorithm is recursive in nature when F Max will get executed it will internally call again the find Max so in order to keep the track of these methods we will create a table which will be nothing but our call stack so let's see how this algorithm and this call stack works together so at the first step we are calling the find Max method and we are passing in the root of the binary tree whose maximum value we need to calculate so on the call stke you will find one find Max method whose root is pointing to a node having value as four so here you can see that this table has five values line number root result left and right so as the algorithm is recursive in nature when we will leave this find Max method and we'll again call find Max we'll simply keep the track of the line number here we'll keep the track of the root result left and right which we will see later how they are important moving ahead so here as the algorithm is recursive in nature we need to provide a base case so that we can exit from the algorithm if you don't provide this base case then this find Max will again call find Max and it will go on because there will be no end so we need to provide this base case that if the root is null here then we can simply return the minimum value from here so for example if the root is pointing to null so we will simply return the minimum integer value because null can signify that this is the minimal value as the return type is integer we need to return a value so we simply return return the mean minimum value of the integer because the minimum value of integer won't affect the maximum value of this binary tree so here currently we are providing a check that if root is equal to null then simply return the integers minimum value So currently root is pointing to four therefore this condition comes out to be false also friends we discussed the idea that how we can find the maximum value of any node and its left and right children is finding the maximum value of this left sub tree finding the maximum value of its right sub tree and comparing it with the roots value so here this three line will do that in the result we are simply storing The Roots value so here in the result it will be coming as four moving ahead so now we'll Traverse to the left of this binary tree in order to find the maximum value of the left sub tree so we are simply again calling the find Max method but this time we are passing in roots. left so root is pointing to four and its left is pointing to three so three will be our new node and here you can see we are leaving this find Max method at line number six so we'll simply keep the track of line number here so that when this find Max will end we know that where to start this find Max so we'll simply store the line number which is six and we will again call the find Max method passing in Roots left node so on the call stack it would look that find Max method is called we have left this find Max method here at line number six and we are again called find Max and this time the root is roots left which is three so now root will point to 3 moving ahead root is not equal to null again we will apply the algorithm recursively on this node so first we will Store The Roots data so which is three now in order to find the maximum value till this node is we need to find the maximum value of its left sub tree we need to find the maximum value of it right sub tree and we need to compare those value with the roots value so first we'll go to the left of this root so we will call find Max again and this time we'll pass Roots left which is five but we are leaving this find Max method so we'll keep simply keep the track of this line number so which is six so now find Max will be called again again with roots left which is five so our new root will become five root is not equal to null so this condition comes out to be false and now we'll apply our algorithm recursively to this node we will first store The Roots data in the result which is five and then we will again call find Max method to Simply calculate what's the maximum value of its left sub tree and we are leaving this find Max method at line number six so we'll simply store line number six here so there will be one more method on the call stack but this time the roots value will be null because five's left is null here we are calling Roots left so Roots left is null so now root will point to null here we will check with the root is equal to null or not so here you can see that we have encountered a base case that root is equal to null so here we will simply return the minimum value of the integer because as roots left is null so there are no more notes to Traverse and we will simply return the least value of the integers which is integers Min value whose value is this because this value is negative in number therefore it won't affect the maximum value of this binary tree and as the left child is null so we can simply return the minimum value of the integer so we are returning the integer minan value so here you can see that we are leaving this find Max method here and once we leave this find Max method here this call will go to this method because this find Max method had called this find Max method and we also know that we had left at line number six so we'll start our execution from line number six and as we are returning the integers Min value so this find Max method will get that value so it would look something like this this method will be removed from the call stack execution point will reach you here we will start our execution from line number six because we had left this method at line number six and here you can see whatever the value this find Max method return returned we will simply store in this integer variable left so which was the integers Min value so in the left we'll simply store the minimum value of the integer so I'm simply denoting it by imv here and when we were execu this findex method here you can see root was pointing to five so again root will point to five and we will proceed ahead with this method so here you can see we have this Roots value which is five we have calculated the maximum value of the left now we will calculate the maximum value of the right so we'll again call the find Max method but this time we'll pass the Roots right value so here you can see that we will again have to leave this method at line number seven this time and we will call find Max method again passing in Roots right which is null so it would look something like this line number is updated here find Max method will be called and there will be one more method on the call stack with root as null so now root will point to null and why this root is pointing to null because we have called find Max method by passing Roots right which is roots right is null so here now root is equal to null so we'll simply return the minimum value and this meod will be removed from the call stack and the execution point will reach again on this method and we'll start our execution from line number seven so this method returned the integer minimum value which will be stored in the right here and when we have left this F Max method root was pointing to five so now root will again point to five and the execution will continue from here so here you can see now we have got all the three values to compare the roots value the maximum value of its left sub tree and the maximum value of its right sub tree so now we can simply perform this comparison for this node so here we'll check whether left is greater than result or not so left value is the minimum value of the integer so therefore this condition comes out to be false because value of left is integer minimum value and result value is five so five is greater than left so this condition will come out to be false we'll check whether rights is greater than result or not so right's value is also integer minimum value so this condition also comes out to be false and here you can see that among this node the maximum value is of the root which is five so we'll simply return five from this find XX method so now here you can see this find Max method will be removed from the call stack and the return value will be five so this method will be removed from the call stack the execution point will reach here and we know that we have left this find Max method at line number six so we'll start execution from line number six this findex return the value as five so this five will be stored in the left variable here and when we left this find Max method root was pointing to three so now root will point to three moving ahead so friends for root3 we have already calculated the maximum value of its left sub tree which is five here now we need to Simply calculate it for right sub tree so we'll again call find Max method and this time we'll pass Roots right which is 8 so we will be leaving this method at line number s here and there will be one more method on the call stack with Now new root as eight so root will point to eight now we check whether root is equal to null or not so root is not equal to null we will store Roots data which is eight and now similarly we'll perform this recursive algorithm for the root 8 now so here you can see friends this three steps we need to perform on each and every node so what we did for five now we'll again do it for eight so we'll simply go fast here because we already seen what happens when the nulls are encountered so first we'll update the line number which is six and there will be a find Max method in the call St because now we are going to Roots left so Roots left is null so this find Max will be called with null value root will point to null and root is equal to null so we'll simply return the integers minimum value and this method will be removed from the call stack and integers Min value will be to this find Max method so it would look something like this we'll start execution from line number six where root will now point to8 and the integers minimum value which was written from this findex method will be stored in the left here and similarly now we'll go to Roots right so we'll update the line number here here so find Max method will be called again with the root as null root will be pointing to null and here root is equal to null so we'll simply return the minimum value of the integer so this method will be removed from the call stack and this method will start execution from line number seven now where root will now point to 8 because when we left this find Max method root was pointing to 8 so root will point to 8 now and the integers minimum value which was written from this find ma method will be stored in the right now and now as we have got these three values to compare we will check whether left is greater than 8 or not because we need to find the maximum value so left is not greater than eight so this condition comes out to be false right is also not greater than result because right is storing the integers minimum value and8 is greater than this value so this condition also comes out to be false and we'll simply return 8 from this method because we have found the maximum value of this right sub tree which is8 so we'll simply return return 8 from this find Max method so this method will be removed from the call stack and the execution point will reach to this method where we had left at line number seven so we'll start from here and here root value was three so now root will point to three and we know that from the right we return the value which is maximum as 8 so eight will be stored in the right here so friends here you can see for this small binary tree we got the three values five was the maximum in the left sub tree eight was the maximum in the right sub tree and we'll simply compare it with the root which is the result value so here we'll perform the comparison so we'll check whether left is greater than result or not so this condition comes out to be true because left value is five which is greater than three so we'll simply update the value of result with the maximum value which is five so this will become five we'll check whether right's value is greater than result or not so value of right is 8 which is greater than result which is five so this condition also comes out to be true so we'll simply update the maximum value which is8 into the result so this will become 8 and then we'll simply return 8 so from this find ma method we are returning 8 which is the maximum value among these three notes so this method will be removed from the call stack and this method will start execution from line number six where root was pointing to four so root will now point to four and the value which this find Max method return return which was eight will be stored in the left so here you can see that for the actual root of the binary tree we figured out what's the maximum value in the left sub tree which is8 so now we need to Simply find the same for the right sub tree we'll start our execution from line number six again and now we'll simply go to its right sub Tree by calling the find Max method and passing in The Roots right value which is seven so this method will be removed from the call stack and we'll simply store the line number seven because we need to keep the track of this recursive nature algorithm so line number will updated at 7 there will be one more method find Max having the root 27 because we have left from line number seven passing in Roots right value so root was four and Its Right value is 7even so 7 will be our new root for this find Max method and Friends similarly we will apply this algorithm recursively on this node now what we seen with five and 8 so we will simply quickly go over this algorithm root is not equal to null we'll Store The Roots value in the result field which is seven we'll recursively go to the left sub tree now here by passing in Roots left as we are leaving at line number six we'll store line number six there will be new method on call stack with roote pointing to null now because we are going to its left now so this roote will be null and we'll simply return the integer minimum value from this find Max method we start our execution from where we left at line number six where root was pointing to 7 and the value which this find Max return return was integers minimum value so we'll simply store in the left and similarly for the right it will perform the same we update the line number here we leave this method we again call find Max with roots right which is null so there will be one more method on the call stack having value of root as null so root will point to null we'll simply return the integers minimum value because root is equal to null so this method will again come on the call stack and we'll start execution from line number seven now so here root will now again point to7 and this method had return integers minimum value which will simply store in the right here and now we'll simply compare these three values 7 left and right and we know that 7 is the maximum value so these two conditions will come out to be false because left is not greater than result and right is also not greater than result so this both the condition will come out as false and we'll simply return 7 from this find Max method because 7 is the maximum value of the right sub tree for the actual root so this method will return 7 execution point will reach here we had left at line number seven so we'll start executing from line number seven where root was actually pointing to four so root will point to four and the find Max method which got executed before this find Max method return value is seven so seven will be stored in the right so here you can see for this complete binary tree now we have we actually got all the three values The Roots value the maximum value of the left sub tree and the maximum value of the right sub tree so we'll simply compare these three values and get the maximum value of this binary tree complete so we'll check whether left is greater than result or not so value of left is 8 it is greater than result which is four so we'll simply update the value of left into result so result becomes eight now we compare whether value of right is greater than result or not so right value is 7 which is not greater than 8 so this condition comes out to be false and finally we will return the value8 which is the maximum value among this binary tree so this method will terminate here and on the call stack this will get removed returning the maximum value of this binary tree which is 8 so friends here you saw a very long demonstration of this algorithm where we applied this algorithm recursively on each and every node to find what's the maximum value of the binary tree so friends the complexity is involved in this recursive nature which we demonstrated using the call stack and one once you understand how this call stack works you can simply code the algorithm related to binary tree recursively now let's go to intelligence C the working of this code so friends I hope you have liked this video and in case you have liked this video then please like comment share and subscribe my channel thanks have a nice day hello everyone so in this video we'll see the demonstration of the algorithm that how we can find the maximum value in a binary tree so in our previous video we saw the demonstration of the algorithm step by step so in this video we'll simply code the algorithm and see it's working so here you can see in our previous videos we created one class as binary tree which had a root as an instance variable of type tree node so this is the class of tree node which we created in our previous videos and we solve different algorithms so here let's say we are given this binary tree and let's say we provide a maximum value in this binary tree as8 and rest of the value we keep as it is now we want to write an algorithm where we can find the maximum value of this binary tree so friends here in case if you find any difficulty you can watch my previous videos where we have demonstrated each and every line of this code step by step and we have demonstrated all these algorithm step by step so let's code the algorithm to find the maximum value of a binary tree so here we have created one method at find Max who return type is integer because we want to return the maximum value of a binary tree so here we'll simply return find Max we'll pass in the root because we need to pass a root to find the maximum value of a particular binary tree which we also saw in our previous video so here we'll create a method as public whose return return type will be integer find Max and this is the method which will take the root of the binary tree and will simply return the maximum value of this binary tree so here this is our binary tree whose maximum value is eight so let's see the code to find the maximum value of this binary tree so as we discussed in a previous video that this algorithm is recursive in nature the first thing we provide is the base case we simply check whether root is equal to null or not so if root is equal to null will'll simply return the minimum value because as root is null it simply signifies that we can simply return the minimum value of the integer so here we need to find the maximum value of this binary tree and if root is coming out as null then we need to return an integer value so we can safely return the minimum value of the integer because beyond that there won't be any minimum value and our task is to find the maximum value so this minimum value won't affect the maximum value of this binary tree so after providing this if check for the base case the first step is to store The Roots value so we are creating an integer value result and we are storing The Roots value into this result and also we discussed the basic idea behind this algorithm is in order to find the maximum value of a binary tree we simply compare the roots value to the maximum value of its left sub tree and also we'll compare this value with the maximum value of its right sub tree so so when we compare these three values we come to know what's the maximum value of a binary tree so this algorithm is very recursive in nature and this is applied on each and every node of the binary tree so where we simply Store The Roots value then we go to its left sub tree to find the maximum value of the left sub tree once we get that value then we go to its right sub tree and we find the maximum value of the right sub tree and after we get these three values We compare them with each other and we get the maximum value of the complete binary tree so here after getting the roots value we simply try to get the maximum value of the left sub Tree by calling the find Max method recursively providing Roots left value so here we are simply providing the roots left which is the left sub tree of this root and whatever the value this find Max method will return return we'll simply store in the left variable and similarly we do it for the right sub tree we call find Max recursively providing Roots right value so in order to see how this recursive nature works you can watch my previous tutorial where we demonstrated this recursive nature with an animation so you can watch that and here after finding all these three values we'll simply compare it with each other so the first step we compare whether left value is greater than result or not so if left is greater than result we simply update the result with the left because at the last we need to send the result and which should be the maximum value so first we are comparing left with result and then we are comparing right with result so if the value of right is greater than result we are simply updating the value of right to result and at the last we are simply returning result so here you can see that we are comparing all these three values here if left is greater than result we are storing the greater value in the result and then we are again comparing whether right is greater than result or not and if right is greater than result then we are storing the value of right into result and finally we are returning result because this will be the maximum value among these three values so here you can see this is the algorithm to find the maximum value of a binary tree so let's test its working working in the main method so first we are creating this binary tree with these values where we know that 8 is the maximum value and here we are simply printing the maximum value by calling the find Max method which internally will call this find Max method providing in the root which is this root and this root is being created here with this create binary tree method so after we create this binary tree with this hardcoded values and when we will call the find Max method we will get the maximum value of this binary tree so here you can see it printed eight because eight was the maximum value of this binary tree now let's say if I update any value to 10 and if I run the code again you can see answer came as 10 because 10 is the maximum value of this binary tree so friends here we saw the algorithm to find the maximum value of any binary tree which was basically recursive in nature where we compared the three values one was the root Val value we compared it with the maximum value of its left sub tree and we compared it with the maximum value of its right sub tree here and finally we returned the result which was the maximum value of the complete binary tree and this algorithm we applied on each and every node of the binary tree because this is recursive in nature and in order to see the complete animation of this recursive nature you can watch my previous video so friend this was all about this video I hope you have liked this video and in case you like this video then please like comment share and subscribe my channel thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to represent a binary search tree in Java in our previous tutorial we actually discussed about the binary tree we saw that each and every node in the binary tree had two children one was the left child and one was the right child so a binary search tree is a special type of binary tree in which the data is organized in an ordered manner which helps us in Faster search and insertion of the data so how binary search tree helps us in Faster search and insertion of data we'll see later first we will discuss the three properties which makes it a binary search tree so here in the diagram you can see a binary search tree which satisfies the three properties so the property one says the left sub tree of a node contains only nodes with values lesser than the nodes value so what does it mean let's suppose if we take a node having data six so all the nodes to it left like 4 2 5 they have values lesser than six so if you see there are three notes to the left of six and if you compare the values of these three notes with six you will find that 4 is less than 6 2 is less than 6 and five is less than six so all the nodes to left of a particular node should have values lesser than the nodes value and similarly if you go to WR of any particular node then all the values should be greater than the not's value so if you take the example of note having value as six and if you go to its right we see there are three notes having datas 8 7 and 9 all the values are greater than the nodes value so here in the binary sory we are keeping the data in ordered form that from a particular node if we go to its left we will only find the values lesser than the noes value and if we go to its right we'll only find the nodes having values greater than the then the particular node so friend the third prop property says the left and the right sub tree each must also be a binary search tree so friends here we saw the note six is following these two properties that all the values to his left are lesser than the nodes value and all the values to his right are greater than the noes value and in a binary search tree these two properties should be true for each and every node of the binary search tree so for example if we take a node having value as four then we can see that to its left there is only one node and its value is 2 Which is less than four and if we go to its right then there is only one node whose value is five which is greater than four so four also satisfies this two properties and similarly if you are on node two then it doesn't have any left and right CH therefore it also satisfies this two property and if these two properties are Satisfied by all the nodes of a tree then that tree is called as binary search tree so here in this diagram you can see that it is a binary search tree so suppose if I change a value here and I make it a value as8 so here you can see that node with the value as four if you go to its left we are getting a value lesser than the nod's value and if we are going to its right then we are getting a value greater than nodes value so four satisfies this two property but if you go to the parent of four here you can see the value is six and we know that all the notes of a left sub tree should be lesser than the notes value so here you can see 4 2 8 should all be less than the notes value but 8 is greater than six therefore this is not a binary search tree because these two properties should be true for each and every node and if you are on a particular node then we take all the nodes of which left sub tree and right sub tree and we compare it with the nodes value so here you can see four and 2 are lesser than 6 but 8 is not lesser than six therefore it is not a binary search tree and similarly if I take a value of five here then you can see that if we had at node 8 then if we go to its left we see that value of five is lesser than 8 and if we go to its right then we have node 9 and value of 9 is greater than 8 so eight satisfies these two properties but if you go to the parent of eight which is nothing but six so here you can see that it is not a binary search tree because from property two the right sub tree of a node contains only the nodes with values greater than the nodes value so if you see the right sub tree from the note six we see it has three notes and all these three notes should have values greater than six but here you can see 8 and 9 have values greater than six but five is lesser than six therefore this tree is not a binary search tree so friend all these three properties if Satisfied by each and every node of a binary tree then it becomes a binary search tree below these three properties makes the search and insertion of data faster because let's suppose if you want to search for a value five in this binary search tree then we simply check the value five with the root of the tree so here you can see that five is not equal to 6 and as it is a binary search tree we know that five must be lying somewhere to the left of this tree because it satisfies the three properties and we know that the left sub tree of a note contains only values lesser than the notes value so we know that fire must be lying somewhere to the left of node 6 so from node 6 we Traverse left and we we reach to four and also here you can see when we are traversing to Note 4 we are simply discarding all the notes of the right sub tree because we also know that five can never lie to the right of six so let's suppose if we had a binary search Tre having many notes then we could have simply discard half of the notes and we would have continued our search to either right or to left of the search tree so friends if we compare fire to four then we know that five is greater than four so five must be lying somewhere to the right to four and then we simply Traverse to its right and we discard the left sub tree of the node 4 and finally we found the node having data is five so friends when we want to insert a data into binary search Tre we usually follow these three properties only so let's say if you want to insert a node having data is 10 then we simply start from the root node we check the value of root to the data which we want to insert so here if we compare the value 6 with 10 then we know that 10 is greater than 6 therefore it should be inserted to its right so we Traverse to its right and we see there is one more node so we compare this value with the value which we want to insert so here 10 is greater than 8 therefore we know that 10 must be inserted to its right so we simply Traverse to its right and we find there is one more node having data is 9 so we check that whether 10 is greater than 9 or not so here 10 is greater than 9 so we go to its right and we find that there is no node because 9's right is pointing to null so we simply insert node at that place so friend this is how search and insertion of data gets faster in binary search tree because in each iteration we discard half of the tree as we know that we either want to Traverse to right or to left so friend this is the usefulness of binary sear tree moving ahead so friend if you see the structure of tree node in a binary sear tree then it is very similar to binary tree that this tree node is nothing but the inner class of binary search Tre which is basically the three properties one is the data property to hold the data and another two properties are nothing but the references to the left sub tree and the right sub tree we also provide a Constructor to this three node class which takes in a data part so whenever we want to create a new tree node we simply pass in the data property and left and right property actually points to null so friends let's go to eclipse and see the implementation of binary search tree Hello friends in this section we will discuss how we can Implement a binary search tree so friends here I have created one class by name binary search tree which is having a main method and we also discussed in our previous tutorial that binary search tree is nothing but a binary tree so friends initial implementation of binary search tree is very similar to binary tree in binary search tree class we'll create an instance trans variable of type tree node which would be nothing but the root of the binary sear tree so here we can see the type is of tree node so we'll create an inner class I'll give it a name as tree node so friends here binary sear tree is a type of binary tree therefore the implement which we saw in the binary tree is very much similar to binary search tree that we have created one another class by name tree node also friends in our previous tutorial we discussed that a tree node consists of three parts one is the data part so private hint data so this property will hold the data of the tree node here I have taken the type of this data as integer so it can be any generic type as well also friends we know that binary search tree is a type of a binary tree where each tree node has two childrens one is the left children and one is the right children so we'll create a tree node and we'll give it a name as left and we'll create one more tree node and we give it a name as right so basically a tree node has two childrens one is the left and one is the right inside this tree node class we'll also provide a Constructor so public tree node and this Constructor will take the data part so we'll initialize the data of this tree node with a value which which you have passed into the Constructor and also friend whenever the new tree node is created the left and right points to null so friend this is how we actually represent a binary search tree in Java in our upcoming tutorial we'll actually see how we can insert and how we can search a node into a binary search tree so friends I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to insert a value in a binary search tree in Java and also friend in this tutorial we'll discuss the recursive approach to insert a value in a binary sech Tre so friends below you can see the code to insert a node into a binary search tree so here the insert method takes in a root node and the value which we want to insert also friends here you can see insert method internally calls insert again therefore it's nothing but a recursive call so in order to keep the track of this recursion we will use the call stack and based on this call stack we will see the demonstration of this algorithm step by step so friend let's suppose currently binary sear tree has no notes and when the binary search Tre is empty we know that root will point to null now let's suppose you want to insert a value five into this binary sear tree so here you can see on the call St there will be one insert method and currently as root is pointing to null therefore here we can keep the track of the root which is pointing to null and we can also keep the track of its left and right tree node which are also null and the last column will have the value which we want to insert moving ahead so friend in First Step we'll see that whether root is equal to null or not because as we are going into this recursion here we have to provide a base case so that we can come out of this recursion so our base case condition would be to check whether root is equal to null or not So currently here you can see binary search Tre is empty therefore root is equal to null so the condition in if block comes out to be true and inside this if block as we want to insert this value five therefore first we'll create a tree node and provideed a value as five so it would look something like this friends in our previous tutorial we also discussed that when we create a new tree node we actually pass the value into the Constructor of tree node so in this tree node the data is the actual value which is five and as it is a new tree node therefore left and right are pointing to null and also friends as we are creating this tree node we are assigning it to the root so it would look something like this that root will point to a tree node having data is five and also friends here we'll provide the value as five that root is now pointing to five moving ahead and then we'll simply return the root so your insert metod will come to an end and it will be removed from the call stack so friends when binary search tree was empty we have inserted one node having data is five now let's suppose we want to insert one more value the value which we inser inerting is three and here we also know that root is now pointing to a node having data is five so on the call stack it would look something like this that root is five it's left and right are null and the value which you want to insert is three so in the first step we check whether root is equal to null or not so here you can see root is not equal to null therefore for the condition in if blog comes out to be false so friends in our previous tutorial we actually discussed what is the binary search Tre we discussed the three properties which binary search Tre follows property one was let suppose if you are on a particular node which has some value and if you Traverse to it left then all the nodes value to its left would have values lesser than the noes value and if you if you go to its right then all the nodes value would be greater than the node value and these two properties should be true for each and every node of the binary cry so friends when we insert a new node we actually check for these two properties so here you can see we have provided an if loog and inside this ifog we have provided condition as that whether value is less than root. data value so here you can see root. data is nothing but five and the value which we want to insert is three so here you can see the value is actually less than root. data value so here if you want to insert a new Tre node having value is three then we can only insert into the left sub tree of the root because value is less than root. data so therefore the condition in if blog comes out to be true so friends here you can see we are again calling the insert method and we are passing the value as root. left and the value which we want to insert so on the call St there will be a new insert method and as there would be a new insert method we will be leaving this insert method and we will again calling the insert method so we need to keep the track of the previous insert method so we know that we have given the line numbers here and we know that we we are leaving this insert method at line number seven so we'll simply put a value of seven in the line number column and we'll call the insert method and this time we'll pass root. left as a new root so it would look something like this that there would be a new insert method on the call stack and here we know that root left is null therefore for this insert method root will be null and left and right would be null and the value which you want to insert is three so here root will be pointing to null now and we'll again check whether root is equal to null or not so here you can see root is equal to null and then we'll create a new tree node and we'll pass the value into its Constructor and we'll assign it to the root so it would look something like this a new tree node is created having the value as three and left and wrer pointing to null so now root will point to this tree node moving ahead so here now root is pointing to three and finally we'll simply return from this insert method so friend as soon as we return from this method this insert method will be removed from the call stack and the execution point will reach to the insert method which was executed just before that and we also know that we have left at line number seven so we'll start the execution from line number seven so it would look something like this so now we are starting again this insert method from line number seven and when we had left this insert method root was pointing to five so here root is now pointing to five and as we had written root which was nothing but three it will be assigned to Roots left so here you can see root is pointing to five and Roots left is pointing to null therefore whatever we return from previous insert method it will be assigned to Roots left so it would look something like this moving ahead now root left is three and then finally we'll simply return the root so the execution of this insert method will be complete and it will be removed from the call strike so friends here we have inserted two notes now let's suppose we want to insert a value 7 so it would look something like this first insert method will be created on the call stack having root as five whose left is three and whose right is null and the value which you want to insert is seven we check whether root is equal to null or not so here you can see root is pointing to a node having data is five therefore it's not null and using the binary search tree properties we'll check that whether value which we want to insert is less than root do data or not so here you can see root do data is nothing but a value five and here we are inserting a value 7 therefore the condition in if block comes out to be false we are inserting a value 7 which is greater than the roots value therefore it must be inserted to the right sub tree of the root so now else block will be executed now here we want to insert the value to Roots right therefore we are again calling the insert method and this time we are passing in a value as root. WR so here you can see root is pointing to a node having data as five and Its Right is pointing to null and as you want to insert a new note to this right therefore we simply calling the insert method and we are passing root. right with a value which we want to insert and also here we are again calling the insert method we are leaving this previous insert at line number n so we'll simply put a value of nine into the line number column that we are leaving this insert method at line number nine so now on the call St there would be a new insert method and as we have passed in root. right so here you can see root. right is null so we are executing this insert method with root as null and left and right are null and the value which you want to insert is 7even and friends as this insert method is getting executed root is pointing to null so root is pointing to null we are checking whether root is equal to null or not so so here root is equal to null and as you want to insert this new tree node having value as 7 we'll simply create a new Tre node and pass a value 7 to its Constructor and then we'll assign it to the root so it would look something like this that root will now point to a tree node having data as 7 and whose left and right are pointing to null so here root becomes seven and finally we simply return the root so when we return the root execution of this insert method gets completed so it would be removed from the call stack and the execution Point reaches to insert method which was getting executed just before this insert method and we know that we had left this insert method at line number n so we'll start our execution from that point so friends here once the insert method gets executed we had return return the value 7 and once the execution starts from line number n we know that at that point root was pointing to five so root will point to five and we also know that we have written node 7 from the insert method so therefore simply assign whatever you return from the insert method to roots. right so here root is pointing to node 5 and Its Right is pointing to null therefore node 7 will now point to Roots right so it would look something like this so here now right will become seven and then we'll simply return from this insert method so this insert method will be removed from the call stack so friends here we inserted three nodes now let's suppose you want to insert one more node having value as one so in the first step we'll call the insert method providing in the root and the value is one so your root is pointing to 5 and left is pointing to three and right is pointing to 7 and the value which you want to insert is 1 in the first step we are checking whether root is equal to null or not so root is not equal to null so friend as it is a binary search tree we are checking the whether value which we want to insert is less than Roots value or not so here you can see 1 is less than 5 therefore we are sure that the value one will be inserted somewhere to its left sub tree so therefore the condition in if blog comes out to be true because 1 is less than five and here we are again calling the insert method by passing in root. left and the value so your root do left is nothing but three and as we are leaving this insert method we will keep the track of the line number so we are providing value as seven so now the insert method will be called with root do left which is nothing but note three so for this insert our root will become three so here you can see there will be a new insert method where root will be three and left and right are null and the value which you want to insert is one so here now root will point to three we'll check whether root is equal to null or not so root is not equal to null and then we'll check whether value which we want to insert is less than root. data or not so here 1 is less than three so we know that one should Lie To the Left sub tree of the root having value as three therefore we are again calling insert method by passing into the value as root. left so your root. left is nothing but null and as we are leaving this insert method we'll keep the track of the line number which is nothing but seven so here a new insert method will be on the call stack having root as null because here we are passing root do left so root. left is nothing but null so now root will point to null moving ahead we'll check whether root is equal to null or not so here you can see the root is equal to null and then we'll create a new tree node by providing it the value as 1 and that re node will assign to the root so it would look something like this that now root is pointing to a node having data as one and whose left and right are pointing to null so now root is pointing to one and then we'll simply return the root so we have simply returning the tree node having data is one so when we return this tree node we know that this insert method is completed execution Point reaches here and we'll start our execution from line number 7 so at line number seven when we had left this insert method root was pointing to three so now root will point to three and we know that to Roots left we have assigned the value which we had returned from the insert method so root left is null and the value which we returned from the insert method was nothing but one so therefore now root do left will point to the tree node having data is one so here left will now become one and it would look something like this and finally we'll simply return root so when we return root this insert method will be completed and it will be removed from the call stack and the execution Point reaches to the insert method and we'll again start execution from the line number seven and at that point root was pointing to five so therefore now root will point to five and as we have returned tree node having value is three that would be assigned to Roots left so your root is pointing to a node having data is 5 we'll simply assign the value three to Roots left so it would look same and finally we'll simply return the root so the insert method will be completed and it will be removed from the call stri so friends here we inserted four nodes into to Binary s Tre by applying the properties of binary s tree that suppose if you are on a particular node then all the values of the nodes to its left would be lesser than the nodes value and all the values to its light sub tree would be greater than the noes value so here you can see 3 and 1 are lesser than five therefore they lie on the left sub tree of this node and here you can see 7 is greater than 5 therefore it is lying on the right sub tree now friends let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually discussed how we can insert a node into a binary search tree so in this tutorial we'll actually code how to insert a node into a binary search tree so first we'll create an insert method so public white insert and to this insert method we'll actually pass the value which we want to insert and inside the insert method we'll simply call the insert method which we we actually discussed in the slide so we'll pass root and the value which we want to insert and here we'll create a method as public whose return return type would be tree node name would be insert taking in parameters as root and the value which you want to insert friends in our previous tutorial we actually discussed the recursive way to insert a node into a binary search Tre so here we'll first provide a base case that if root is equal to null then we'll simply create a new tree node by passing in the value and then we'll simply return the root so this would be our base case and if root is not equal to null then we provide the condition which binary tree satisfies that if value which you want to insert is less than Roots value then we simply Traverse to its left and we'll again call insert method by passing in root left and the value which you want to insert and if value is greater than Roots value then in the else part we simply Traverse to the right sub Tree by calling insert and providing the Valu is root. WR and the value which you want to insert so whatever the insert method will written we'll simply assign it to the roots left and in the lse part what the insert method will return return we'll simply assign to Roots right and finally we'll simply return return root so friends in our previous tutorial we actually saw how this insert method Works step by step now let's test is working into the main method so first we'll create the instance of binary search Tre and then we'll insert few notes which we actually saw into the slide so with the value is five 3 7 and 1 so friends after inserting this for note we'll simply print it on the console that whether they are inserted in the right order or not so friend in order to print the notes on the console I will code the algorithm for in order tree traversal which we actually discussed in a previous tutorial when we discussed about the binary tree so in order so here simply will call in order by passing in the root so here we'll provide in order method which will have the root so we had also discussed that we first so friends we also discussed that in in order traversal we first check whether root is equal to null or not so root is equal to null we'll simply return and in this traversal we also discussed that first we visit the left sub tree of the root then we actually visit the root and finally we visit the right sub tree also friends here you can see that first we are going to the left of the root then we are actually printing The Roots data and then we are going to its right so friends binary search tree also follows one property that if we do the in ordered traverser of a binary search tree then the notes will be printed in sorted form so let's see how so we'll simply call in order which will internally call the in order and we'll pass route into it so if I run the code now so friends here you can see it printed 1 3 5 7 and also you can see the numbers are in sorted order because if you perform in ordered traversal on the binary sarch Tre we get the traversal in sorted order so friends which actually proves that whatever we inserted into the binary search Tre followed these three properties friends I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to search a given key in a binary search tree also in this tutorial we will see how we can search a given key in a binary search Tre using recursion so friend let's suppose we are given a binary search tree and we want to search a particular value inside this binary search tree so below you can see the algorithm to search a given key in a binary search tree also friends the method which we are going to call is search method and here inside this search we are again calling search method therefore in this algorithm we are basically using recursion so friends in order to keep the track of this recursion we are basically maintaining a call stack whose significance we'll see while demonstrating the algorithm step by step friends let's suppose we want to search a key five into this binary search tree so in the first step we'll simply call this search method by providing it a root which is the root of the binary search tree and the key which you want to search so Friends when the search method will start its execution on the call stack it would look something like this that there would be a search method on the call stack and as we are passing the root which is nothing but six and the key which we want to search is five so here we are simply keeping the track of these values moving ahead so friends as we are searching a particular key using this recursion we have to provide a base case so that we can come out of the recursion so here the base case would be we are simply checking in the F blog that whether root is equal to null or root do data is equal to key or not So currently you can see root is not equal to null it is pointing to a node having data as six and we also know that root do data which is value six is not equal to key which is five therefore the condition in if block comes out to be false so friends in our previous tutorial we actually discussed what is a binary search tree so friends the binary search tree is nothing but a minority tree which follows some properties so the first property says that let suppose we are on a particular node and if we Traverse to it left sub tree we'll find the nodes having values lesser than the node value so let's suppose we are on node 6 if it travel to left sub tree we are seeing the notes having values 4 2 and 5 so these all three values are lesser than six and similarly for any node if you go to its right sub tree we'll find the values greater than the node value so let's suppose if you take an example of node 6 if you go to its right sub tree we are finding there are three nodes having values 8 7 and 9 so all these three values are greater than six also friend these two properties should be true for each and every node of the binary search tree and using these three properties where actually searching a particular key in the binary search TR so here in the F blog we are simply checking that whether value of key is less than root. data or not so here you can see root. data is nothing but value six and the key which we are searching is five so by the binary search tree property we know that five must be lying somewhere to the left sub tree of node 6 so here the condition in if blog comes out to be true so friends here we know that five must be lying to the left sub tree of node 6 therefore we are calling search method Again by passing in the value as root. left and the key which we want to search also friends when we call this search method we are actually leaving this search method and we are again calling the search method so therefore in order to keep the track of the previous search we will store the line numbers so it means that we are leaving this search method at line number six and we are again calling search by providing root do left and the key which we want to search so friend this search method will be called again and this time the root will become root do left which is nothing but four so here on the call stack there would be one more search method so as we call this search method by passing root do left which was nothing but value four so root become four so here root will now point to four moving ahead we'll again check whether root is equal to null or not so here you can see root is not equal to null because root is referring to a node having value as four we'll also check whether root. data is equal to key or not so here you can see root. data which has value 4 is not equal to key which is five therefore the condition in if block comes out to be false and then we'll again check whether key is less than root do data or not so here you can see root do data is four and the key which we are searching is five so therefore 5 is greater than 4 so the condition in if block comes out to be false so the else part will be executed so friends as here key is greater than root. data we know that five must be lying somewhere to the right sub tree of the node 4 so therefore in the lse block we'll simply call the search method Again by passing in root. right and the key which we want to search and also friend as we are leaving this search method we have to keep the track of the previous search method so first we'll store the line number so it would look something like this that we are leaving this search method at line number 8 and we are calling this search method Again by passing root. WR as the new root and the key which you want to search so it would look something like this on the call stack there would be one more search method and as we are calling it by root. right we know that root. right is nothing but node having data is five so here root is five so root will now point to five then we'll check whether root is equal to null so here you can see root is pointing to node having data is 5 therefore it's not equal to null and we'll again check whether root. data is equal to key or not so here you can see key is nothing but five and root do data is also five therefore root do data is equal to key so the condition in if block comes out to be true so friend it means that we have found our key so in the line number three we are simply returning the root which is is nothing but the key which we found so this is the tree node which we actually found and we are returning this tree note from this search method so friends after this line gets executed this search method will be removed from the call stack and the execution point will go to its previous search method and we also know that we had left the previous search method at line number eight so we'll start our execution from that point also friends when we had left this search method we know that root was pointing to four therefore now root will point to4 and from the line number eight we'll simply return whatever the value we got from this search method which was nothing but a tree node having data data is five so therefore this search method will be executed completely and it will be removed from the call stack and the execution point will reach to this search method and we know that we left this search method at line number six so we'll start our execution from line number six and also friends when we had left this search method that time route was pointing to six therefore now root will point to six and finally we'll return what we actually got from the previous search which was nothing but the tree node having data is five so we'll simply return five and this search me will removed from the call stack so friend this is how we actually search for a particular value in a binary search tree now let's suppose if you want to search one more value which is not in the binary search Tre so let's say we want to search a key having value as 10 so we know that 10 is not in the binary search Tre so let's see how this algorithm works in the first step we'll call the search method by passing in the root and the key which you want to search so on the call stack it would look something like this that root is six and the key which you want to search is 10 moving ahead we check whether root is equal to null or not so root is pointing to six therefore it's not equal to null we'll also check whether root. data is equal to key or not so here you can see root do data which is 6 is not equal to 10 therefore condition in if block comes out to be false and then using the three properties of binary search Tre we will see whether 10 is lying into this binary search Tre or not so in the first step we'll check whether key is less than root. data or not so here you can see 10 is not less than 6 therefore we know that 10 might lie somewhere to its right sub tree so the condition in if block comes out to be false and the lse part will be executed so here as we know that 10 might lie somewhere to the right sub tree of six therefore we again call search method by passing in root. right so root is pointing to six and root. right is pointing to8 and as we are leaving this search method we'll keep the track of the line number which is8 and then we'll simply call the search method by passing ing in root. right and the key which you want to search so on the call stack there would be one more search method and this time Root will become 8 so root will point to 8 moving ahead we'll check whether root is equal to null or not so root is not equal to null because it is pointing to a node having value as 8 we also check whether root. data is equal to key or not so root. data is 8 and key which we want to search is 10 therefore 8 is not equal to 10 so the condition in if blog comes out to be false we again check whether key is less than root. data or not so root. data is 8 and the key which you want to search is 10 so 10 is not less than eight8 therefore we know that 10 might lie to the right sub tree of eight so the condition in IFL comes out to be false and the else part will be executed so here we'll again call the search method by passing in root. right so here root is pointing to it and it's right is nine and as we are leaving this search method we'll keep the track of the line number so on the call stack there would be a new search method and this time Root will become N9 because we are passing root dot right as root is pointing to8 Its Right is pointing to 9 so here our new root will become 9 we'll again check whether root is equal to null so here root is not equal to null because root is pointing to a node having value as 9 we will also check whether root. data is equal to key or not so root do data is 9 and the key which we want to search is 10 therefore root. data is not equal to key so the condition in if block comes out to be false we'll again check whether key is less than root. data or not so here 10 is not less than 9 therefore the condition in if block comes out to be false and the lse part will be executed because we know that 10 must be lying somewhere to the right sub tree of 9 so here you can see we are again calling search method and we are leaving this search method at line number eight so we'll keep the track of the line number and we will call the search method by passing in root. right so here you can see root is pointing to 9 and Its Right is pointing to null because there is no right child to node 9 so on the call stack there would be one more search method so value of root will be null so root will point to null moving ahead we'll again check whether root is equal to null or not so here you can see root is equal to null therefore condition in if log comes out to be true so friends condition in this if log is nothing but our base case because after 9 there are no notes into this binary SAR Tre therefore by some way we need to exit this recursion so friends here we know that 10 is not lying into this binary search Tre and also root is pointing to null therefore in the if blog we simply return root which would be nothing but null and as we are returning null it signifies that key was not found into this binary search tree so here this search method is executed completely so it will be removed from the call stack and the execution point will reach to this search method and we know that we had left this search method line number eight so we'll start our execution from line number eight and when we had left the search method root was pointing to 9 so therefore root will point to 9 also friend what we had return returned from his previous search which was nothing but null we'll simply return null from this search method so it will be removed from the call stack and the execution point will reach to this search method and we'll start our execution from line number eight and when we had left this search method root was pointing to it so now root will point to it and also friends from this search modal will simply return the null value so this search modal will be removed from the call stct and then the execution point will reach to this search method and we'll start our execution from line number eight and when we had left this search method root was pointing to six so now root will point to six and also friends on this line we'll simply return the value which we got from its previous search which was nothing but null so this method will be removed from the call stack and at last we'll simply return null which would signify that value was not found into the binary C Tre so for in this tutori we saw the demonstration of how to search a particular key into the binary search tree now let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually saw the demonstration of how to search a particular key into a binary search tree in this tutorial will actually code the search algorithm and we'll test its working so friend in our previous lectures we actually created a class by name binary search tree we also saw how we can insert a value into a binary search tree so friends in this tutorial we'll actually code how to search a given key in a binary search tree using recursion so here first we'll create a method whose return type would be the tree node and we will give the name as sir search this search method will take in the key which we want to search and inside this search method we'll simply call search by passing in the root which holds the complete binary search tree and the key which you want to search and we'll again create one more method whose demonstration which we actually saw in our previous tutorial so the name of the method is search it will have two parameters one would be the root of the binary search tree and other would be the key which you want to search so in this search method as we are using the recursion we have to first provide a base case so our base case would be if root is equal to null or root. data is equal to key then we'll simply return the root from this method so here this would be our base case because this case will help help us in getting exit from this recursion and if root is not equal to null or root. data is not equal to key then we simply check that whether key is less than root. data or not so if key is less than root do data we know that key must be lying somewhere to the left sub tree of the root therefore we'll simply call the search method by passing in root. left and the key which you want to search and also whatever is return from this search method we'll simply return here and in else part if key is greater than root. data then we know that key must be lyed to the right sub tree of the root so therefore we'll call the search method recursively by passing root. WR and the key which you want to search and whatever will be return from this method will'll simply return here so friends here we are calling this search method recursively by using the binary search tree properties so there can be a two case where we are actually finding our key then we are simply returning the root and if you're not finding the key then we are simply returning null so the null signifies that key was not found in the binary search tree also friends we saw the demonstration of this algorithm step by step in our previous tutorial now in the main method let's test it's working so here in the main method we have created one binary search tree by inserting few values as 5 3 7 1 and then we are simply printing this binary search tree so if I run the code now you can see it's printing the value of binary search tree using this in order treat traval and it prints 1357 so friend in this binary search Tre we know that it has four values 5 3 7 1 so let's suppose we search for Value three so we'll provide a f block and we'll call the search method by passing in the value is three so if this search method doesn't return null then we know that we have found our value so we'll simply print on the console as key found so if I run the code now you see it prints key found because three is present into this binary search tree now let's say if you want to search any value which is not present into this binary search tree so here we'll simply call search method by providing as value as let's say 10 and we know that 10 is not present into this binary search tree so we'll simply print key not found if I run the code now you see printed keyn note found so friends in this tutorial we actually saw how we can code algorithm to find a key into a binary search tree and we also tested it's working I hope you like this video thanks have a nice day hello everyone so in this video we are going to discuss a problem validate binary search tree so let's see what this problem is and how to to solve this so in this problem we are given a root of a binary tree now our task is to determine whether it is a valid binary search tree or not or BST so a binary search tree if it follows these three properties then it's a valid BST so the properties are let's say if you are on any particular node the left sub tree of a node contains only nodes with keys less than the nodes key so it means here note key is four and if we look towards its left then all the notes which are on its left should have value lesser than four so for example if we take six if we look towards its left it has three elements so the left sub tree which is four 2 5 should contains only the noes with keys less than the nodes key so 4 is less than 6 2 is less than 6 5 is less than 6 and similarly the right sub tree of a node which is on this side should contain only nodes with keys greater than the nodes key so 8 should be greater than 6 7 should be greater than 6 and 9 should be greater than 6 so for six the left should be lesser and the right should be greater and this two properties should be true for all the nodes so here both the left and right sub trees must also be binary search trees so what we saw on six the same property should hold for 4 8 2 5 7 and 9 that if we go towards its left all the notes towards left of a note should be less than the notes value and if we go towards right all the nodes which are towards the right should have value greater than the noes value so this property makes a valid BST moving ahead so here let's say we are given with this binary tree and we need to find whether it's a valid bstd or not so here you can see if from six we look in this direction the left sub tree has three notes 4 2 and 8 and we know that the notes in the left sub tree should be less than the notes value 4 is less than 6 2 is less than 6 but here you can see 8 is not less than 6 so therefore it is not a valid vstd so here you can see that for node four in the left sub tree we have only one node and it is less than four in the right sub tree we have only one node which is 8 and 8 is greater than four so so for four it is a valid bstd node but if we check all these conditions at this node 8 is greater than 6 and we know that all the notes of the left hand side should be lesser than the notes value so therefore it's not a valid bstd till this much point it was a valid BST because left notes were lesser than the notes value and the right notes were greater than the notes value but if we look from here then it is not a valid BST because 8 is greater than 6 it should be less than 6 so friends how we can solve this problem is that when we are at node 8 its parent is four and 8 lies towards its right so 8 is greater than four so this part is valid but but here if you see the parent of four is six so therefore 8 should lie between 4 and six so this thing you can consider as a range that it should lie between four and six but how we can propagate this information to it is with each node we assign a minan or a max value now this Min and max value will tell that that particular node value should lie between Min and Max so now let's assign these values to these nodes so if you see for six as it is a root node the minimum range should be minus infinity and maximum range should be Infinity because for six there are no constraints so it should be like this that 6 should be greater than minus infinity and lesser than infinity so this is the range for six so if we go towards the left let's say we are on node 4 so what could be the possible range for four so for this node having value as 4 to be a valid BST node it should be less than six because four if it is lying on the left side the maximum value for four would be it should be less than 6 and the minimum value would be minus infinity only because 4 can be greater than minus infinity the only constraint is for the max value that it should be less than 6 so for 4 the range would be minus infinity to 6 so this was for this note let's say if we going in right and we encounter 8 so we know that in a valid BST if you're going towards right all the notes value should be greater than notes value so 8 should be greater than 6 so it means the minimum value 8 can go is just greater than 6 and the maximum value it can be like 100 200 anything so here when it is going in the right the Min value for8 would be six and the max can be anything so friends if if you closely observe if you're going on left the minan remains same and Max changes because of the bstd constraint and if you're going on the right Max Remains the Same but Min changes so we need to keep the range in such a way that if you go towards left sub tree Min remains same so here Min was same so we are propagating such a value that whatever Min we have here we are just transferring it as it is and makes changes to parent value so we pass Six here if you go towards right sub tree here you can see Max Remains the Same so whatever Max was here it must be same here but main changes to parent value so meain change to the parent value which was six so these two properties we need to keep in mind while assigning the ranges so now let's see the ranges of the rest of the elements so for two we are going towards left so minan remains same and Max changes to parent value so Min remains same which is minus infinity and Max changes to 4 which is true as well because 2 should be less than four so this is the range and let's say if we are going in this direction which is on the right side so if we go towards right of tree Max remains same so this Infinity will remain same because this is the max value and Min changes to parent value so for 9 Min will become 8 which makes sense because 9 should be greater than 8 because it lies on the right sub tree so Min changes to parent value so8 comes here and infinity Remains the Same which is our Max so friends when tricky part comes in this direction let's say we are going in this direction now if you see we are going in the right side so if you go towards right sub tree Max remains same so for four if you look Max is six so we know that for 8 the max will remain the same which is six and Min changes to parent value so Min would be parents value which is four so it should be like this from four we are going on the right sub Tre and if you are going on the right side Max Remains the Same so here Max was six so we pass Six as it is minan changes to parent value and minan change to four so here why this range is important here you can see we have transferred six towards 8 so that we can validate whether 8 is lying between 4 and 6 or Not So currently 8 though it is greater than four but it is greater than 6 as well it should lie between four and six therefore we can directly return return a false value saying saying that this is not a valid bstd so we will see the code for this but to understand we are simply passing down the ranges and we are checking whether that particular node is actually lying between this ranges or not so for any range it should be like this but here 8 is greater than 4 but this condition is false because 8 is not less than 6 it is greater than 6 so therefore this node makes this B tree and invalid binary search tree and now for seven we are going towards left so main remains same here if you see mean is six and Max changes to parent value so parent value is 8 so max becomes 8 so for 7 it would be like 6 comma 8 and here you can see 7 is lying between 6 and 8 so friends now let's go ahead and see the demonstration of the algorithm that how we can figure out whether a binary is a valid BST or not so here you can see that this is the algorithm so friends before we start if you want to master data structures and algorithms then you can subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that this is valid method is returning a bullan value stating that whether this tree note which is being referred by root whether it is a valid BST or not and here you can see this is valid method is getting called here and here recursively so in order to demonstrate the recursion we are maintaining a call stack here where we denote the method call and we store the state of the elements like root min max left right so when any particular method will leave the call stack we store the state of that method and when it comes back we start our EX execution by applying those values back to the variables and then we proceed ahead so friends here you can see we discussed about the mean and max value and here you can see that when we are going towards left here we are calling this valid method again we are going towards left so Min Remains the Same and Max changes to Roots value which is the parent value and when we are going towards right we are calling is valid with root. right here you can see Max Remains the Same but mean changes to the parent value which is root do Val so these two properties we need to keep in mind and in this if block we are basically checking that whether this root or the node value whether it is lying between those values or not so if it is less than equal to Min we know that it should be greater than Min so we can directly return false or if root do well becomes greater than Max then we can returnal false because root do well should be less than Max so this root do well should be like this min max and here if root do Val is less than or equal to Min we can return return false because it should be greater than Min and if root do Val is greater than equal to Max we can return return false because it should be less than Max and as we are calling this method recursively we are providing a base case that if root reaches to null let's say here so this null doesn't change the BST property for one so we can directly return return true from here so now let's call this valid method we pass in the root so for root we know that it should lie like this from minus infinity to Infinity so for an integer value we are providing here a long Min and long Max so we call is valid method with Long's Min value and Long's max value because these two values will be like minus infinity and infinity to five because five is an integer and long is a data type which is greater than integer and we are taking Long's extreme values Min value and max value because the root doesn't have any constraint so we can provide the minimum and the maximum value of long so is valid method will be called and there will be one method on the call stack root as five min as Min which is long do Min value I have written it like this Max would be long do max value like this and left and right would be the Boolean values which we will be receiving from here and here and we will see that later moving ahead root is not equal to null so this condition comes out to be false so here you can see 5 is not less than equal to Min and 5 is not greater than equal to Max so here Min is the long Min value which is in the negative Infinity so five is actually between this so the both the condition comes out to be false so for five this range is valid and now we are going towards the left of five so we are going in this direction now to node two so here you can see this is valid method will be removed from the call stack and we are leaving this is valid method at line number eight so first we update line number eight here and then we are calling his valid method here you can say we are passing root do left because we want to go in this direction and when we are going on the left side we know that Min Remains the Same and Max changes to parent value so for for two Min will be minus infinity and Max would be the parents value which is five so now we'll call this is valid method with the respect to values so there will be one more method on the call stack like this we have pass root. left so root will point to node two we know that Min Remains the Same and Max changes to parents value which is five root is not equal to null so this condition comes out to be false so here root. well which is two it is not less than equal to Min it is actually greater than Min so this condition is false root do well which is 2 is it greater than Max which is 5 so this condition is also false therefore overall condition comes out to be false which signifies that 2 is between minus infinity and 5 so therefore this if loog condition comes out to be false and for two also these conditions are true so now we go towards its left so we are again leaving this is valid method at line number eight so we'll update line number eight8 here we pass root do left which is one now Min Remains the Same which is minus infinity but Max changes to parents value which is the current Roots value which is two so there will be one more method on the call stack now root becomes one so root will come here mean remains same and Max changes to parents value which is two root is not equal to null so this condition comes out to be false root. well which is one so it lies between minus infinity to 2 because Max is two so this condition is true therefore here root. well which is 1 it is not equal to minus infinity and 1 it is not greater than equal to 2 so therefore both these condition comes out to be false and we reach here so here if I just put the ranges for two it would be like this and for one it would be like this so till this point everything is fine now we'll go towards its left so we are going to call his valid method again passing in root. left so root. left is null now Min remains same and Max changes to one so we are leaving this is valid method at line number 8 now and there will be one more method on the call stack here now root will be null so root is pointing to null so whenever we encounter this null cases we know that it is our base case so we directly return return true so root is equal to null so we return true so now here you can see this is valid method will be removed from the call stack and execution point will reach here with a value as true so this got removed from the call stack execution Point reached here and we had left is valid method at line number eight so we start from line number eight and this is valid method return true so that true will be assigned to left so left will have true like this and when we left is valid method root was pointing to one so root will come back to one like this I'll remove this thing so now here you can see if from the left side we would have got a false value there is no point in going towards the right we can directly return false because if any of the value states that this is not a valid BST then overall tree would be not a valid BST so first we check whether left is true or not so if left is true then only we go towards the right so currently left is true so for this node we are done with the left part now we go towards its right so there will be one more method on the call stack which is is valid we pass root. right and here you can see one changes when we are going towards the right Max Remains the Same but mean changes to Roots value so here first we will update the line number here because we are leaving this method so 10 comes here now when we'll call this valid method Max Remains the Same it means two Remains the Same and main changes to parents value So currently parent value is one so we will see how it looks there is a is valid method on the call step with root will be now null because we have went towards its right now by calling it with root. right here you can see when we go towards right Max Remains the Same this values are same and M changes to parents value so if we move ahead root is pointing to null so this is our base case so we directly return return true from here so this method will be removed from the call stack an execution point will reach here and it starts the execution at line number 10 with root as one so this is valid method returned a value of true so we can assign it to right now like this and when we had left his valid method root was at one so root comes back to one so friends here you can see that for this one node from left we got true and from right also we got true it means this particular node is a valid BST node so we can directly return return the value of right because left is we have checked it is already true so now this is valid method will be removed from the call stack and execution point will reach here we will start from line number eight like this and this is valid method return the value of true and this method we received the value true from here so that will be assigned to the left so left will become true and in this is valid method root is at note two so root will come back to node two we check whether the left side of two returned a true or not so which is true so this condition is true so therefore now two decides to go towards its right to do the same steps so here now we'll again call his valid method we pass root. right so root. right is 7 when we are going to right Max Remains the Same which is five but mean changes to root value So currently root value is two so therefore first we update the line number here because we are leaving this isv valid method at line number 10 so 10 comes here now isv valid method will be executed again root will become seven because we are going towards the right Max Remains the Same and minan changes to Roots value because we are going to the right root is not equal to null so this condition comes out to be false root. well is not less than Min so here you can see root do Val is 7 and Min is 2 so 7 is greater than 2 and 7 should be lesser than 5 because five is Max so this condition is is false because 7 is greater than 5 so here you can see root do well 7 Min is 2 so here 7 is not less than equal to 2 so this condition is false but here you can see 7 should be greater than equal to Max which is 5 so this condition became true so therefore this overall condition came out to be true and we know that 7 is not in this range from 2 to 5 and this condition came out to be true because root do well which is 7 we are checking whether it is greater than 5 or not so it has overpass the max value which shouldn't be the case so we directly return false now because 7 should be less than 5 but here we found that 7 is greater than Max so this condition came out to be true so we return false so this method will be removed from the call stct by returning a false value execution Point reaches is here we start from line number 10 here and this method returned a false value so to write we assign false like this and when we left this is valid method root was at two so root will come back to two like this so from here we received true and from here we received false so when we'll proceed ahead from left we receive true and from right we are receiving false so therefore if any any of the value came out to be false we directly written false stating that this binary tree is not a valid BST so we return false so this is valid method will be removed from the call stack by returning false an execution point will reach here we had left at line number eight here and the previous is valid method returned a false so we return false to otk 5 so to the left we assign false and root will come back to five from here so we first check whether from left only we received false or not so for node 5 the left sub tree returned a false value so it should not go towards its right it should directly return false because left we received false so we directly return false stating that this binary tree is not a valid BST so when we will return false this method will also be removed from the call stack like this so our algorithm will end and we simply return false value so now let's say instead of seven we had three like this and root was here so this was the previous state which we already discussed let's say when we are on this part root is at three the minan value should be two and the max value should be five so for seven we had the same conditions root is is not equal to null so we check whether root do well which is three is it less than Min so this will be false because 3 is greater than Min we check whether root do well is it greater than Max so this condition is also false because 3 is not greater than Max which is five previous to that here it was 7 so therefore we had written false but now we have three and three lies between 2 and five so therefore this both the condition came out to be false so why I'm demonstrating it with thre is just to complete the algorithm for a positive BST so this tree is actually a valid BST so now we go towards the left of this root which is three and this is our base case so we'll go quickly over this we first update the line number here because we are leaving this is valid method root will come to null and min max will be 2 and 3 root is equal to null so we return true so this method will return true and it will be removed from the call stack execution point will reach here we start from line number eight this method return true so to left we assign true and root came back to three left is true so we go towards its right which is also our base case so we first update the line number here 10 and his valid method will be on callstack with new root as null because we are going towards the right so root comes here root is equal to null so we return true directly we start from line number 10 and this is valid method return a True Value so true comes here and root goes back to three and whatever the value right has we directly return that value because if you're are going towards right it means left is already true so if right would have been false we would have written false if right would have been true we are returning true so this is valid method will be removed from the call stack and will return true so we reach here we start this is valid method from line number 10 here and here this is valid method return return true so we update true here and at that moment root was at two so root comes back to two so here from this null we got true from here we got true so both came out to be true so we returned a True Value which we stored here so now this is valid method will be removed from the call stack returning the value of right which is true so two will return true and this is valid method will be executed from line number eight because five at called is valid and passing in root do left which was this and this is valid method return return true so we assign true to left root comes back to five left value is true so for this note it sees that it's left sub tree complete left sub tree returned value is true so now it checks by going towards the right so it will call is valid again passing it root. right when we are going to the right Max Remains the Same and Min changes to parents value which is root. well so here when we go towards the right we reach six so for six Max Remains the Same which would be long do max value but Min will change to the parents value which is root value which is five which makes sense because 6 should be greater than five and it can be lesser than any of the max value so max Remains the Same and mean changes to root. well so first we update line number here which is 10 and we will go quickly over this three notes now so root comes here root is not equal to null 6 is between five and Max so both the condition comes out to be false now we go to the left of six by calling his valid method passing in root dot left when we are going to the left mean Remains the Same which is five but Max changes to root. well so it should be six now so there will be one more method on the call stack with root as null we know that we have went to the left so Min Remains the Same and Max changes to Roots value which is six root is equal to null so we return true directly we start from line number eight so left will receive true root comes back to six left is true so now we go to the right of six we update line number here which is 10 there will be one more is valid method on the call stack with root as null because we have went to root dot right now and as we are going to the right we know that Max Remains the Same and Min becomes the roots value like this so root is equal to null so it is our base case so we return true directly execution point will reach here it will start from line number 10 so this method returned a value true we stored in the right and root came back to six and now we can directly return whatever the value right will hold So currently it is true so we will pass True to this is valid method and this method will be removed from the call strike so now this is valid method will be starting from 10 because we had left at line number 10 and this method return returned a value of true so right will have true root will come back to five and then here you can see from the left we received true from the right also we received true like this so for five as it is a root of this binary tree it sees that from its left side it received true and from the right it received true and five being the root node it is also in the boundaries of long do Min value and long do max value so therefore it directly returns true which is stored in the right so this method will be removed from the call stack stating that this is a valid BST so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone welcome to my new data structures and algorithms in Java tutorial series video in this tutorial we will discuss a interview coding problem search in a row and columnwise sorted Matrix so friends in an interview we are given a problem that given a row and column wise and cross and sorted Matrix write a program to search a key in a given Matrix so what do we mean by row and column with sorted Matrix so here you can see we are given a 4 cross 4 Matrix so by four CR 4 Matrix we mean that it has four rows and four columns and here you can see that each row is sorted and each column is sorted so for an example the row at zero index you can see the values is 10 20 30 40 and the last row we have values as 32 33 39 5 1 and all these rows are sorted in ascending order and similarly if you see the columns then those are also sorted so for example zero index column has value as 10 15 27 32 and similarly if you take second index column the values are 30 35 37 39 so this is the Matrix in which each row is sorted and each column is sorted in ascending order and we are given a value and we need to write a program to search that value inside this Matrix so friend let's suppose we are given this 4 cross4 Matrix which is sorted rowwise and column wise so here as the Matrix is 4 cross 4 the value of n is 4 and let's suppose we want to search for a key as 32 now this key is present present into the Matrix and we want we want to write a program which could search this key into this sorted Matrix so friends here you can see the algorithm for it now let's see the working of this algorithm step by step friends there is an inefficient solution that is using two for loops and what we do is we compare 32 with each and every value of this Matrix and see whether the element is present in The Matrix or not so friend this is an inefficient approach because because the time complexity of this solution is O of n² and here as we are given this Matrix is sorted rowwise and column wise we can use that property to write an efficient code so let's see a demo of this algorithm so here we are simply calling this search method by passing in the 4 cross4 Matrix the value of N and and the key which we want to search so friends here we know that this Matrix is sorted rowwise and column wise therefore we start our searching from the top right corner of the Matrix let's say we start from 0a 3 having a value of 40 so what we do is we compare 32 with 40 and see that whether 32 is equal to 40 or not so if it is equal to 40 we simply print that we have found our element at 0 3 and here has 32 is less than 40 so the idea behind the algorithm is if we go to the left of 40 we will find all the numbers lesser than 40 and if we go below 40 then we will find the numbers greater than 40 so friend as this is a rowwise and columnwise sorted Matrix so for each and every element in this Matrix this property holds true that if we go a step left we get the number lesser than the current number and if we go one step below then we'll get a number greater than the current number so let's suppose if we are an index 2 comma 1 so value is 29 if we go one step left we'll get the values lesser than 29 and if we go one step down we'll get the values greater than 29 and this property is true for each and every value in The Matrix so we'll use this idea and search for the the particular key in the Matrix so in step one we'll create an integer value I which will be pointing to zero so this value I will be pointing towards a particular row of a matrix at a particular index So currently it is referring to zero index row moving ahead and then we'll create one more integer variable by name j and we'll assign the value of n minus one which is which is nothing nothing but 4 - 1 so friends J Will point to the columns index so friends we will start our search from the top right corner of the Matrix so therefore we have initialized I to 0 and J to 3 and we will start our search from the index 0a 3 having a value of 40 so friend as we want to search for Value 32 inside this Matrix we are providing a while loop and in this while loop we are providing the boundary conditions of the Matrix so that value of I and J do not cross over the Matrix boundary so as I started from value zero we will iterate it to a value lesser than n and we are also providing a boundary condition for J that it is started from three it should go till index zero So currently you see I is less than 4 and J is greater than zero so the condition in V block comes out to be true so here we have provided an if log and inside this if log we are checking that value at Matrix I comma J is equal to X or not so value at I comma J which is nothing but 40 we are checking whether it's equal to 32 or not so the condition in if block comes out to be false and then we are again providing an if log and we are simply checking that whether value at I comma J is greater than x or not so here you can see 40 is greater than 32 therefore the condition in if blog comes out to be true so friend as this Matrix is sorted rowwise and column wise so friends when we compare 40 with 32 we know that 40 is greater than 32 therefore we also know that 32 must be lying One Step left to 40 so we are simply decrementing the value of J so it would become something like this the value of J becomes two moving ahead then we are again checking that whether I is less than n and J is greater than equal to Z or not so here you can see I is less than n because the value of I is 0 so it is less than 4 and J is greater than equal to 0 because value of J is 2 and 2 is greater than zero so the condition in V block comes out to be true we will again compare the value at I comma J index with X so here you can see the value at 0 comma 2 is 30 so I will simply compare the value of 30 with 32 so the Matrix Val 0a 2 which is 30 is not equal to 32 therefore the condition in if blog comes out to be false and then we'll simply check that whether value at I comma J is greater than x or not so here you can see the value at I comma J is less than x because 30 is less than 32 therefore the condition in if blog comes out to be false and lse part will be executed so friends 32 is greater than 30 therefore it must be lying somewhere below 30 so we simply increment I by 1 to go one step down so value of I is zero so now it will become one moving ahead we again check whether I is less than n and and J is greater than Zer or not so I is holding value 1 and it is less than 4 and J is holding value two which is greater than zero therefore condition in while block comes out to be true in the first if block we check whether the value at Matrix I comma J is equal to X or not so here the value at I comma J which is nothing but 35 is not equal to X which is 32 therefore the condition in if blog comes out to be false we then check that whether value at Matrix I comma J is greater than x or not so here you can see the value at I comma J which is 35 is greater than 32 therefore the condition in ifog comes out to be true and as 35 is greater than 32 we know that 32 must be lying somewhere to the left of 35 therefore we simply go one step left to 35 which is nothing but decrementing the J by one so it would look something like this that value of J becomes one moving ahead now again we'll check in the while loop there whether value of I is less than n and J is greater than or equal to Z or not so here you can see the value of I which is 1 is less than 4 and value of J which is 1 is greater than zero therefore the condition in V block comes out to be true we again check in the F blog that whether value at I comma J is equal to X or not so here you can see value at I comma J which is 25 so 25 is not equal to 32 therefore the condition and if L comes out to be false and then we'll again check that whether the value at I comma J is greater than x or Not So currently 25 is not greater than x so condition in if block comes out to be false and else part will be executed so friends s32 is greater than 25 we know that this value might lie somewhere below 25 so we'll simply move one step down by incrementing the value of I so I becomes two moving ahead we'll again check whether I is less than n and J is greater than equal to Z or not so here you can see 2 is less than 4 and 1 is greater than zero therefore the condition in while block comes out to be true we check the value of Matrix at I comma J is equal to X or not so here you can see the value at I comma J which is nothing but 29 is not equal to 32 therefore the condition in if log comes out to be false and then we simply check that whether value at Matrix I comma J is greater than x or not so here you can see value at I comma J which is 29 is less than x which is 32 therefore the condition in if blog comes out to be false and else part will be executed so friends we'll go one step down because 32 is greater than 29 so here as this Matrix is row and column is sorted Matrix we know that 32 might lie below 29 so we simply go one step down by incrementing the value of I so I becomes three moving ahead in the while loop we again check whether I is less than n or not so here you can see value of I is three and it is less than 4 and we also check whether J is greater than equal to 0 or not so here you can see J is greater than zero so the condition in while block comes out to be true then in the we check that whether value at Matrix I comma J is equal to X or not not so the value at I comma J is nothing but 33 and we know that it's not equal to 32 therefore the condition in if blog comes out to be false then we simply check that whether value at Matrix I comma J is greater than x or not so here you can see the value at I comma J which is 33 is greater than 32 therefore condition in if blog comes out to be true now as this value 33 is greater than 32 we know that value must be lying to the left of 33 so we simply go one step left by decrementing the value of J so J becomes zero and then again in while we check whether I is less than n and J is greater than or equal to zero so here you can see value of I is 3 and it is less than 4 and value of J is 0 which is equal to 0 therefore condition in while block comes out to be true now we simply check that whether value at Matrix I comma J is equal to X or not so here you can see the value of Matrix at 3 comma 0 which is 32 is actually equal to 32 therefore condition in if blog comes out to be true so friends here we know that we have found our value so therefore we simply print on the console that X is found at 3 comma 0 so in the console we are simply printing that X is found at 3 comma 0 and then we'll simply return from this method so friends in this tutorial we saw the demonstration of the algorithm now let's go to eclipse and see the working of this code hello everyone so friends in our previous tutorial we saw the demonstration of the algorithm to search for a value in row and column wise sorted Matrix now in this tutorial we'll actually write that code and test it's working so here I have created one class by name sorted Matrix and inside this class I have created one main method and here I have initialized the Matrix which we discussed in our previous tutorial which is row and column wise sorted Matrix now let's write a program to search for a key in this row and column wise sorted Matrix so I'll will give the name of this method is public void search and this method takes in three arguments one is the Matrix one is the value of n as it is a 4 cross 4 Matrix therefore value of n will be four and one will be the value which we want to search we are denoting it by X so in order to search in a row and column with sorted Matrix we are using two pointers I comma J so we are initializing I to zero and J 2 N minus one because we are simply starting our search from the top right corner of the Matrix so here value of I will be iterating over the indexes of the rows and value of J will be iterating over the indexes of the columns moving ahead we'll provide a while loop and inside this V Loop we have to iterate over the Matrix using the values of I and J therefore we are simply providing the boundary condition so that I and J do not cross over the Matrix boundary so here I should be less than n and J should be greater than equal to Z which we actually discussed in our previous tutorial in the first step we providing an if block and inside this if block we are simply checking that value of Matrix at I comma J is equal to X or not so if the value at Matrix I comma is equal to X then we know that we have found our element so we simply print X found at I comma J and then we'll simply return from this method because we have found our element and if the value at I comma J is not equal to X then we simply check that whether that value is greater than x or less than x so Matrix I is greater than x or not not so here if the value at Matrix I comma J is greater than x and as it is a row and column with sorted Matrix we have to go one step left so in order to go one step left we simply decrement the value of J by one and if the value of Matrix I comma J is less than x which is the else part then we know that we have to Traverse one step down because value of x will be lying somewhere down to the value of Matrix I comma J so we'll simply increment the value of I by 1 also friend if you don't find any value then after this V block we'll simply print value not found so friend this is the code to search a value in a row and column wi sorted Matrix now let's test is working so in the main method we have already created a matrix which is row and column wi sorted Matrix so first we'll create the instance of the sorted Matrix class and then we'll simply call the search method by passing in The Matrix the value of n which is matrix. length and let's say we want to search for a value 32 which we discussed in our previous tutorial so if I run the code now so here you can see that it prints that X is found at 3 comma 0 so we have simply printed the indexes of the Matrix where we have found this value now let's suppose if we search for a value which is not present in The Matrix say we give Valu is 100 and if I run the code now so you can see in the second L it printed that value not found so friend in this tutorial we actually coded an algorithm to search for a key in a row and columnwise sorted Matrix so friends I hope you like this video thanks have a nice day hello everyone so in this video we'll be discussing a famous interview problem print a given Matrix in spiral form so here you can see that we are given with a matrix now let's say we are given with an integer Matrix having the values as 1 2 3 4 and so on now we need to print this Matrix in spiral form now what is the spiral form so the spiral form is something like this so here you can see that it basically Travers in clockwise Direction and it goes something like this so we need to print this Matrix in this form so first we need to print it from left to right then from top to bottom then from right to left and then from bottom to top and once we are done with the outer Matrix here you can see the spiral curve goes inside so then we'll go to the inner Matrix so here we'll first reverse it like this left to right then top to bottom then right to left and then from bottom to top and after traversing it like this we will Traverse the inner Matrix like this and we keep on doing this till there are no more elements left to be traversed and this Matrix can be have any length and can have any inner boxes so if you print this Matrix it would look something like this 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 and 10 now let's see the demonstration of this algorithm step by step now here you can see this is the algorithm to Traverse The Matrix in spiral form so if you see this algorithm looks quite complex but once you get an idea it becomes very easy so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here let's say we call the spiral print method we pass in The Matrix which we saw in our previous slide so that Matrix was 4 cross 4 it has four rows and four columns so we are passing that information as well so here it would look something like this that we have this for 4 cross 4 Matrix having row index from 0 to 3 and column index from 0 to 3 so this value R is 4 is denoting that it is four rows and Cal 4 is denoting its four columns so for timing you can think it's something like this here that it's in outer boundaries of this Matrix and it is basically denoting the number of rows and number of columns but here these numbers are denoting the indexes from 0 to three moving ahead now we'll create three pointers i k and l so here I if you see it will be our normal iterator which will help us in printing The Matrix in a spiral form so this is the generic iterator K will basically help us in traversing the rows and L will help us in traversing The Columns so we'll see its significance later so for timing we are starting from zero row and zeroth column so therefore these two variables will help us in traversing rows and columns from zero so K is z and L is z so this zero is basically the index so K is pointing to zero row so this is the row and L is pointing to zero column so this is the column so now we'll see how these two variables help us in traversing The Matrix in spiral form so friends in our previous slide we saw that how we can Traverse The Matrix in spiral form first we need to Traverse the outer Matrix then we need to Traverse the inner Matrix and we need to go on like this till there are no more elements left to be traversed we provide a while loop and these are the boundary checks that K should be less than R because K could travel from0 to 3 so therefore it should be less than R which is 4 and L should be less than C so L should be less than C because this is the boundary of the column and this is the boundary of row once this condition comes out to be true you can see that we have one for for Loop second for Loop third for Loop and fourth for Loop now why this four for Loops so it's very simple the first for Loop signifies that we need to go from left to right the second for Loop will help us in traversing top to bottom the third for Loop will help us in traversing from right to left and the last for Loop will help us in traversing from bottom to top so we need to print the Matrix in spiral form so it's like going from left to right top to bottom right to left and bottom to top so this will help us in traversing the outer Matrix so this while loop will help us go to the inner Matrix and perform these steps again and it will go on till this these conditions are satisfied and once these conditions are not satisfied we know that we have traversed the Matrix in spiral form so let's see the demonstration of this four for Loops along with the outer F Loop so initially both these conditions are true now our task is to print first row so here you can see this is the first row we need to print so if you see this first row is being referred by or pointed by K and once we print 1 2 3 4 we are going to this direction so when we go to this direction you can see the row remains same and what changes is the column so if you want to print one we need 0 comma 0 if you want to print two 0a 1 0a 2 for 3 0a 3 for 4 so here you can see the column is actually changing so when we go this side column changes so this for Loop you can see as you want to print from the first element or from the First Column to the last column with row Remains the Same so the column varies and this column will vary from Lal to 0 to the last value of the column so here L will help us in starting that from which column we need to print So currently this Matrix we are printing is from the start so this is the outer Matrix but once we Traverse this Matrix once we need to go to the inner Matrix so at that time this L will help us to start from six and we need to perform this logic again so here this L help us in keeping the Traverse of which column is actually printed and this K will help us in traversing that which row is actually printed so we'll see their advantage later so here you can see that we are starting from L which is zero and we'll go till I is less than C so I is less than C we need to go till this point so here now it's very simple the die is starting from zero from here and we need to print from left to right keeping the row constant and weing the column based on the I so after providing the valid range for I here you can see that we are keeping the K constant because row is the same what varies is the I so we'll quickly go over this for Loop and we'll print the first four elements because I is traveling from 0 to less than C So currently C is four so I will go from 0 to 3 so let's see how so one will be printed I will get incremented two will be printed I will get incremented three will be printed I becomes three and then four will be printed so now here you can see when we'll do I ++ I will become four so 4 is not less than 4 which is the value of C here you can see so it means we are done with printing the first part going from left to right so this thing is done we have printed 1 2 3 4 now here you can see that as this row is already printed we don't have to print this row again we need to go to this side from 6 to 7 so what we need to do is we need to now increment K by one position because we are done with this row so K becomes one and now it signifies that this is our range to print because we have already printed the first row and here you can see see that this K also help us in starting of the top to bottom it won't print four again because here you can see that when we go top to bottom we are starting from K so I will start from this k equals to 1 and here you can see that when we go from top to bottom you can see that we need to print 8 12 16 so here you can see the column Remains the Same now what VAR is is the row so here I will simply write R so basically you need to think that if you're going from left to right colum varies if you're going from top to bottom row varies so this I will start from K because we need to print8 and we don't have to print four so we have already printed four so we have incremented K by 1 so now I will start from K = to 1 and it will go till I is less than R so here you can see I is less than R because now row varies and here you can see the column Remains the Same so in order to print this column its value is 3 which is C minus 1 so let's see how it goes so I starts from K so here I is one so now here you can see the row is actually weing here column was wearing here row is varing and column here Remains the constant so we need to print the last column so how we can get the last column is we simply do c minus one so this will help us in getting the last column so now I starting from one so we are first printing 1A 3 because c - 1 is 3 then we will print 2A 3 then 3 comma 3 so we'll see it how it goes so now 8 will be printed value of I is 1 and C - 1 is 3 so 1A 3 will be printed which is 8 we'll increment I I becomes two so it means it has now reached here then we will print 12 which is 2 comma 3 will increment I I becomes three and at the end we'll simply print 16 we'll increment I so I will become four so here you can see once I becomes 4 4 is not less than four so this for Loop will exit and here you can see that we have printed now this part left to right is printed top to bottom is printed and after printing here you can see that we have completed with this column so in the next iteration of while loop we need to start from here so for example we need to start from this column not from this column so we need to decrement C now because C is pointing to four now we need to decrement it because once everything will be finished and this value will again come here you can see we are printing C minus one so if C remains at the Four 3 will be again printed so C becomes three now and here you can see now we are simply providing one check that if K is less than R then only go from right to left so here this condition we will look into later so for time being just think that we have only this for Loop So currently K is actually less than R but we will see the importance of this condition later so for timing just think that K is less than R because K value is 1 and R is 4 now here you can see we are done from left to right top to bottom now we need to go from right to left and we know that what varies in this direction is the column so here we need to print now 15 then 14 then 13 so here you can see the column is actually varying from 2 then 1 then zero and what is constant here is the row so when we Traverse from left to right or from right to left the row Remains the Same column varies and if you go from top to bottom or bottom to top the row varies and columns Remains the Same so here now we are going from right to left so column is actually varying from two then 1 then zero and here you can see the row is same which is three so here now our I will start from C minus 1 because we need to print this part not this so I will start from C minus 1 which is 2 2 it means this column and row is constant and here you can see this I will Traverse till I is less than equal to l so here you can see if L would have been here it means that we are printing this smaller part of the Matrix because this L will help us in providing the range that which column we need to print So currently why we are going till I is greater than equal to l because we need to print all the column values corresponding to this row and here you can see that after each iteration we are decrementing I because we are printing two then 1 then zero IND IND X so we are going from right to left so row remains constant so how we can get this Valu is we simply do R minus one so this is the row which we need to print and column varies from 2 to 0 which is provided by L so we'll simply print 15 now we'll decrement I I becomes one we'll now print three comma 1 which is 14 we'll decrement I I becomes Z we'll print 3 comma 0 now which is 13 we decrement I it will become minus one it means I has gone out of the boundaries of the Matrix so this condition comes out to be false because L is zero and I should be greater than equal to l so here you can see after this for Loop completes we are done with this part 15 14 13 and here we are done with this row so now we'll simply decrement R because in the next iteration of these four Loops we will simply go to the inner Matrix so this row is already printed so we'll simply do R minus minus so R becomes three and this is the similar condition what we provided here we'll discuss this both condition later so for time being think that L is less than C because L is zero and C is pointing to three so this condition is true now here we need to go from bottom to top so we know that row will vary and column will remain the same so we need to print this column and friends here you can see that how this K is helping to prevent traversing this one again because we need to print this column which is 9 and 5 so here like we did here provided a range here you can see so we are starting I from r - 1 which is 2 because we need to print this now 9 and it will go till K so this K will help us to only print five and it won't allow us to go beyond that to print one so this is the advantage of these conditions here so I will start from two because r - 1 is 3 - 1 which is 2 so here I is starting from from the second index row and here you can see that we know that column is constant and this column is being denoted by L and the row varies so row is actually varying by this Itor I so first we will print 2 comma 0 which is 9 then we'll decrement I by 1 I will become 1 so I has become 1 now we'll print 1 comma 0 because value of L is zero so five will be printed so here you can see now I becomes zero here so we don't need to print this so therefore this K will help us in not going to this row because I should be greater greater than or equal to K but here I is not greater than or equal to K its value is zero so this for Loop will exit and once this for Loop will exit you can see that now we have printed this part so after this four for Loops we are done with the outer Matrix so now we need to go to Inner Matrix so this file Loop will help us going to the inner Matrix but before going that as we have printed this column now we need to Simply shift L by one position because we need to start again from here now so we need to shift L by one position by doing l++ so L will become one so here you can see that how this L and K are helping us and traversing this Matrix in spiral form we are done with this column so now when this value will come again into picture we will simply start from from inner Matrix and this complete Matrix will not be touched based on these conditions so let's see how so here you can see K is still less than R so this condition is true and L is less than C so this condition is also true so now here you can see that initially we started K = to 0 and L = to 0 R was pointing to 4 and C was was pointing to four and we printed the outer Matrix like this so now here you can see after the previous complete iteration we shifted everything by one position we shifted K by one position we shifted L by one position we reduced R by one position and we reduced C by one position so so now here you can see that as we have reduced the dimensions of k r l c it means that we are telling that we are done with the outer Matrix and we are now starting from the inner Matrix so here you can see K is pointing to one it means it is starting from here now L is starting from this column because we need to print this and similarly R and C so now at the start we need to print now 6 and 7 so here we know that column varies so from which column we need to start this will help plus we need to start from the first column because we need to print six and row Remains the Same so I starting from l so here you can see the advantage that this L is actually providing us the range and it will go till less than C so this I will go and print 6 and 7 because it is going till less than C so less than C is two it means 6 and 7 will be printed because column is varying and row is constant which is K so this is the similar thing now so the only idea is we need to keep the track of the ranges rest everything is very much same so we'll simply print now six then we'll increment I I becomes two so now we'll simply print 1 comma 2 here 1 comma 2 so 7 will be printed will increment I so I becomes three so 3 is not less than 3 so this condition comes out to be false now and for Loop will terminate and our condition is we need to only print 67 not the 8 so here C is helping us to keep within the boundaries of inner Matrix so we are done with this part and here you can see rest everything is same we are done printing this row now so we'll simply increment K by 1 which means we need to print now this row now we'll go from top to bottom so row varies and K is pointing to two so I will start from two because we need to print 11 now so I starting from two here and here you can see the column Remains the Same so this is the only column or only element inside this column we need to print because rest everything is printed so we simply print C minus 1 which is the second column and I is traveling from K to less than R so after printing 11 when we will increment I it will reach to three which will make us equal to R so therefore I will be equal to R and we need and we will break from this for Loop so this only 11 will be printed here now so here we'll print 2 comma 2 so 11 will be printed we'll increment I so I will become three but here you can see this condition is not getting satisfied which makes sense because we don't have to print now 15 we are done with the printing of the inner Matrix so this part is done and as we have printed this column so we'll simply shift C by 1 position here we do c minus minus and this condition K is less than R still holds true because K is less than R we'll discuss this later and now now here you can see we need to go to from right to left so column varies so here you can see this column will vary from C minus one which is this part C minus one which is 1 and it will go till L because L will help us to stop going beyond the particular column so it will help us only print 10 now because our I is starting from C minus 1 which is 1 and we need to only print this simple value which is 10 so I is 1 and it is greater than equal to 1 so this is the part and here we know that when we go from right to left only column varies row Remains the Same so here we are simply printing Rus 1 comma I so Rus 1 will give us this row and I is actually pointing to one so we are simply printing 2 comma 1 now which is 10 we decrement I I will become zero so here you can see now this condition comes out to be false because I is not greater than equal to l so here you can see we have printed 10 and this part is completed so now we'll do Rus minus because we are done with this row so R becomes two so here K and R both are pointing to two and here you can see L is less than C we'll see this both conditions later now here you can see we have completely traversed The Matrix so this for Loop will won't start because I equals to Rus 1 so if you do rus1 I will start from one which is this but we are actually done with printing this complete row so here this condition help us in exiting from this for Loop because this is the actual range of the rows I should be greater than equal to K but here you can see value of I is 1 and value of K is 2 so this condition comes out to be false because 1 is not greater than equal to 2 so we'll simply increment L now so L becomes two and this inner four for Loops will end and this V Loop will now exit because here you can see K is equal to R and C is also equal to l it means we have completely Traverse this Matrix in spiral form so friends now we need to see why we are providing these conditions I will demonstrate one condition and rest will be pretty much same for the column so let's suppose we are given with a matrix like this that it has only one row and two columns okay so we'll simply quickly go over this K is z l is z this both condition comes out to be true now we need to print one and then two because at the start we need to go from left to right and column varies so I starts from L and goes till less than C so this is pretty much normal step one will be printed and then two will be printed so this is actually printed and we are done with the problem but here if we do k++ so K is pointing to zero so now K is pointing to 1 here we will start from I equal to 1 because we are done with printing this row now we need to start from the next row and we need to go from top to bottom so here R varies and I starts from K and goes till R minus one so this for Loop won't get executed because K and R are pretty much same pointing to one so what we do is we do c minus minus because we are done with printing the last row because it is already printed so we simply go C minus minus so C comes here so friend let's suppose if this condition condition wouldn't have been provided here you can see K is equal to R now okay and if we don't provide this condition let's say this for Loop starts executing then we need to go from right to left okay so when we go from right to left we start from C minus one so C minus 1 is I will start from zero and it will go till I is greater than equal to l so here you can see L is pointing to zero so this condition comes out to be true so this is where this problem starts if this condition comes out to be true then it will simply print R minus one which is R pointing to 1 if we do minus one we get zero and I value is zero so it will actually print one which is we don't want that because why we don't want that is because we are already done with this row so therefore when we go from right to left it is very much important that we need to think that okay is the Matrix completely traversed because here you can see Matrix is completely traversed so here this condition will help us preventing to print one again after printing 1 and two we should simply exit and these two condition will help us doing that because there could be a possibility that we are given with this Matrix only so these are the few age cases which we need to provide so this condition is also pretty much same let's say if we are given a matrix like this here it was one row two column here it will be two Row one column so this condition will help us in preventing let's say one 1 2 so like 1 2 1 again similar to that stuff so friend this was all about traversing a matrix in a spiral form it is a very complex question but if you understand this figure C varies R varies C varies R varies and they vary from range k l r and C so if you understand these two points you can Traverse The Matrix in spiral form pretty much easily using the simple for Loops I hope you must have liked this video and in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will will discuss about the introduction to Priority q and binary Heap in Java so friends what is a priority Q so here you can see priority Q is a data structure that allows us to find minimum or maximum element among a collection of elements in constant time so here priority to data structure holds the collection of elements and it helps us in finding the minimum or the maximum element in a constant time that means from the collection of elements we can find the minimum or the maximum element very fast in constant time so usually priority supports this three operation one is the insertion operation where we actually insert a particular key into the priority queue so the second operation is delete Max or delete Min so here you can see whenever we call delete Max or delete Min what it does is if we call delete Max it return and remove the largest key from the priority queue and whenever you call delete Min it removes the smallest key from the priority que and return it back also friend if you don't want to remove the largest and the smallest key from the priority que then we use the third operation which is the G Max and G Min so it simply Returns the largest and the smallest key without actually removing it from the priority queue and also friends we will discuss more about the priority queue in our upcoming tutorials moving ahead so friends in our last slide we saw about the priority queue so now we will discuss about the binary Heap so here you can see the binary Heap is a data structure that helps us in implementing the priority Q operations efficiently so whatever the three operations we discussed in our last slide about the insertion of key delete Max or Min and get Max or get min those operations are efficiently implemented with the help of binary Heap also friends a binary Heap is a complete binary tree in which each node value is greater than or less than the values of its children so why it is a complete binary tree we will discuss later below you can see that there are two binary heaps one is the main Heap and other is the max Heap and why we call it is a main he because each node value is less than equal to the values of his children so here you can see if you take an example of node having value zero then its children which is 7 and three have values greater than the parent so here in the mean if the parent value is less than or equal to the value of his children also here you can see if we take a node having value of seven then both his children with which is 9 and 8 have values greater than 7even and if we take an example of three then both its children having values five and six have values greater than its parent so here this property is true for each and every node of the binary Heap and here you can see in the max he each node value is greater than or equal to the values of it children so here if we take the node having value as nine then his children have values less than the parent and similarly if you take the node having value as three then is both children is having values lesser than the parent similarly six which is the parent to five and four its value is greater than both five and four therefore by this definition a binary Heap is a complete binary tree in which each node value is greater than equal to which is the max he or or less than equal to which is the mean Heap then the values of its children so here you can see the binary Heap has two types which is the minan Heap and the max Heap so in the mean Heap each node value is less than or equal to than the values of its children and in the max each node value is greater than or equal to than the values of it children moving ahead so friend as we discussed in our previous slide that binary Heap is a complete binary tree so what do we mean by complete binary tree so here as per the definition a complete binary tree is a binary tree where all levels are completely filled except last level and last level has nodes in such a way that left side is never empty so what do we mean by this definition is below you can see a binary tree so here at the level one we have a node having value as zero so this node will be having a left child and a right child so at the level two we have this two nodes which is 7 and three until level two you can see it is completely filled because a node can have only two children but as soon as we go to level three here we see that seven has one left child and one right child similarly three is only left child and there is no right child so here you can see a binary Tre is completely filled except the last level so this is the last level so here you can see all the levels are completely filled except the last level so here we can see there is no node therefore it's not completely filled and also it has one more property that the last level has note in such a way that left side is never empty so here you can see the whatever the nodes the last level is having they are in such a way that left side is never empty so by by the left side we mean that in example two you can see that level one is complete level two is complete but level three is not complete and also and the last level is not completely filled but here you can see by the second property it says that last level is nodes in such a way that left side is never empty so here you can see one left side is empty so therefore it's not a complete binary tree so we call it an incomplete binary tree those large level is not completely filled but there is one missing left node and similarly here you can see that all the levels are completely filled and the last level is not completely filled but it has notes in such a way that the left side is never empty so friends here you can imagine complete binary in such a way that if we go from left to right then we always get a node so here at the level one there is one node so level one is completely filled as we go to level two there can be at most two notes so here you can see if you go from left to right we are getting 7 and three so those are completely filled if you go to third level if you go from left to right then we are always getting a node though there is no right child of three but still it's a complete binarity Tre because because there are no gaps if you're traversing from left to right and similarly if we talk about incomplete binary tree and if you go from left to right then here we can see that three has no left child therefore the first node is null so it doesn't satisfy the property of complete binary tree also friends in our upcoming tutorial we'll also discuss more about the complete binary tree because this is a main property which helps us in creating a binary Heap Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to represent a binary Heap in Java so friends in our previous tutorial we actually discussed about the introduction to Binary Heap so in this tutorial we'll actually see how we can actually represent the bin inary Heap in Java so friends in our previous tutorial we actually discussed that binary heaps are nothing but complete binary tree and we also discussed that there are two types of binary Heap one is the main Heap and other is the max Heap so friends diagrammatically we represent a binary Heap in the form of a binary tree that there is one parent who has two children and similarly the other levels have their own children but when it comes to storing these elements binary usually are implemented using the array so here you can see a Max he in which each node value is greater than or equal to the value of a children so 9 is greater than 3 and 6 3 is greater than 2 and 1 6 is greater than 5 and four so in order to represent the binary Heap we basically implement through the arrays also here you can see the max if is having seven element as 1 2 3 4 5 6 7 so we usually store these elements into an array so in order to store The Seven Elements into this array we usually create an array of 7 + 1 elements because the first entry of array we always take it as empty so here you can see that we never store any element at the zeroth index and here you can see that we start storing these elements from index one so usually we keep the first entry of this array as empty also friends we store these elements into an array by traversing this binary tree level by level from left to right so here you can see at level one if we are traversing from left to right we have only encountered one node which is N9 so we store 9 into an array at the first index moving ahead then we go to level two and at level two from left to right we first encounter three so we store three at index 2 and similarly then we encounter six so we store it at index 3 and similarly if you go to level three from left to right first we encounter two so two we store at index 4 and similarly the other elements also friends in the last tutorial we discussed that binary heaps are complete binary tree that all the levels are filled and if all levels are not filled then only the last level is the level which is not filled and the elements are arranged such a way that the left side is not empty so here you can see why we are taking it as B complete binary tree so let's suppose if two is not present so when we store these elements from left to right in an array so you can see that here in an array we will get a empty hole which will store a null value so whenever we are representing a binary Heap using an array we don't want that any value inside this binary Heap to be an empty or null so therefore the binary Heap are nothing but complete binary tree where each level is filled completely and if all the levels are not complete then it is the only last level which is not complete and all the nodes are as left as possible so Friends by binary Heap has these two properties one is that it should be complete binary tree and second it should follow the Heap order property so the Heap order property is what we discussed that each node should have values greater than or less than the values of its children and if the values are greater than its children then it's a Max Heap and if the values is less than its children then it's a main Heap which we already discussed in our previous tutorial also friend if you presentent this indexes here then it would look something like this that we have filled this array from left to right level by level moving ahead also friends in our previous slide we discussed that how we can represent a binary Heap in the form of an array so here you can see this Max Heap is represented in the form of an array so whenever you perform any calculation over this array we are basically provided a particular index and we need to calculate basically its parent or its child using some formula so here you can see if you had a node having value is n so in the array it is at first index and if you look for its children then it has two children one is having value as three and other is having value six and they are at index two and three so one has one children at index two and one has other children at index 3 similarly if we take a node having value as three then here we can see that it is at index 2 and if you look for his children then they are at index four and five which means that index 4 which has value two and index 5 which has value one are children of index two whose value is three so here you can see three is parent to two and 1 in which three is at index 2 two is index 4 and one is at index 5 so here value of index 2 is parent to value of index 4 and also value of index 5 similarly if we take the node having value as six then here you can see five and four are children to six if you take this representation into an array then five is one children of six and four is the other children so friends here you can see that how this binary Heap is represented into this array and how we can represent this parent child relationship into this array but in order to calculate this parent and child of a particular index there is a Formula so we already start a children of first index is two and three we saw the children of second index which is this node is four and five and we also saw for the children of third index which is this has children at six and 7even so if you given any particular index let's say k index and we want to find its children then the children of K index would be 2 * K and 2 * k + 1 so here children of one is 2 into 1 and 2 into 1 + 1 children of second index is 2 into 2 which is 4 and 2 into 2 + 1 which is 5 children of third index is 3 into 2 which is 6 and 3 into 2 + 1 which is 7 so friend this is the formula which we use in order to find the children of any particular index we simply substitute that particular index value here and we get the values of its children so friend this was the formula to calculate the children of any particular index now let's say if you are given any particular index and we want to find its parent index then here you can see the parent of seventh index is three so here the parent to the 7eventh index is three parent of sixth index is three so parent of sixth index is also three parent of fifth index is two so this is the shift index and its parent is at two so friends in order to find the parent of K index the formula would be simply K by2 so here you can see that if we are at seven index and we want to go to its parent then what we simply do is we do 7x 2 which give us a value of 3.5 and as we are dealing with the integer values these integer values is rounded up to three so 7x2 gives 3.5 and it we take the integer value of it it round off to three similar the parent of six index is three which is evaluated as 6X 2 which is 3 and parent of fifth index is two is being evaluated as 5x 2 which give us a value of 2.5 and if you round it off we get two so friends in this slide we discussed that whenever we represent a binary Heap in the form of a array and if we are at any particular index then we can Traverse to its parent or to its child using this formulas if you want to Travers to it child we simply multiply it by two which will Traverse it to the left child and if we add a one to it we simply go to its right child and similarly if you are at any particular index and if you want to go to its parent we simply divide that index by two and we will reach to its parent index so friends in this tutorial we actually discussed about the representation of a binary Heap and we also discussed that we are actually representing a binary Heap in the form of an array where this first element of the array is left as empty and we start our insertion of these elements from the index one and we also discussed that how we can actually calculate the children of any particular index IND and also the parent of any particular index I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to implement Max SE in Java so friends in our previous tutorial we actually discussed that binary heaps are of basically two types one is the Min binary Heap and other is the max binary Heap so here you can see a Max Heap is a complete binary tree in which each node value is greater than or equal to the values of its children so here if we take any particular node let's say nine so its value will be always greater than or equal to the values of its children so so here you can see 9 is greater than 3 and 6 so this property should hold true for each and every node of this Max binary Heap so if we take an example of node having value as three then 3 is greater than 2 and 1 and similarly if we take an example of six then 6 is greater than 5 and four and also in a binary tree the last level has the leaf nodes so therefore the property holds two for them as well also friends in a Max he you can see that the maximum value is always at the top which we also call as the root of the binary tree so here in the max he the root always has the maximum value and if you represent this Max in a form of an array then it would look something like this that as this Maxi has seven elements we will first create an array of length eight because the first element we always keep it as empty and we start insertion from the index one we also discussed in our previous tutorial that how we actually insert this value inside an Heap so we go level by level from left to right so at level one we have only the root node which is nine so 9 is placed at index one similarly at level two we have three and six so three is placed at index 2 and six is placed at index 3 and at level three we have four Notes 2 1 5 and 4 so two is placed at index 4 one is is placed at index 5 five is placed at index 6 and four is placed at index 7 so friends here you can see the maximum value of this binary tree is at the root which is N9 and if you represent this Max she in an array then here you can see at index one we will always get the maximum value moving ahead so friends here you can see the code for the implementation of the max priority queue so this is the initial implementation and there are many more methods which we will discuss in our upcoming tutorials and here you can see this Max priority Q is nothing but our Max he where it is the integer array which we discussed in our previous slide so we give it as a of Heap and we actually store the size of this Max priority Q in the integer variable n so friends here you can see in the main method the first step we do is we basically create an instance of Max priority q and to its Constructor we are actually passing the capacity that how many elements this Max priority Q will hold so here you can see in the Constructor the value which we are passing is nothing but the capacity of the max priority Q so this is nothing but the initial capacity of the max priority Q so when this line get executed the call reaches to this point and we know that we have passed the value as three so the capacity is three now as we have this instance variable which is an integer array by name Heap and the integer variable n which holds the size of this Max priority q and also friends here you can see that this integer array can be any generic type array but for the Simplicity of understanding I'm using here there's integer array so here in the Constructor the first step we do is we actually create an array having length as capacity + 1 so it would look something like this now capacity is three and we have initialized this array with a length of capacity + 1 which is 4 so why we actually do capacity + 1 is because we discussed in our previous tutorial that that the first element in an array we always keep it as empty so we actually don't use the index zero we always keep it as empty and we place our elements starting from index one so here you can see as we are not using this zero index now now the array can hold a capacity of three so therefore we are initializing this integer array with a length of capacity + 1 moving ahead now as you have initialized this Max priority Q here the initial value of n would be zero because there are no elements currently into this Heap so n is zero and also friends here we have provided two methods one is the ismt method which returns a Boolean value which tells that whether priority Q is empty or not so here you can see if the value of n is equal to Zer then we know that there are no elements into this Heap and Max priority Q is empty so we simply return true if value of n is zero or else we return false and the second method we provide is size we simply return return the value of n so here if we call the size method it will print zero because currently the value of n is zero and then if you simply call is empty method to check whether priority Q is empty or not it's simply return true because n is equal to zero so friend this is a basic and initial implementation of a Max priority Q there are more other methods which we will discuss in our upcoming tutorial so the only understand understand we need to see is that a Max priority que basically implemented through an array which we give your name as Heap and we simply create an integer value and which keeps the track of the number of elements currently into this Heap array so friend this was the demonstration of this few methods now let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually discussed how we can Implement a Max priority Que in Java and in our previous tutorial we actually saw an animation to basically Implement a Max priority queue and in that tutorial we actually implemented the max priority Queue at a very basic level and which we will enhance in our upcoming tutorial so friend let's see the code to implement a ma Max priority Q in Java at a very basic level so friend in this tutorial I have created one class by name Max PQ which is nothing but Max priority Q which has a main method so friends in our previous tutorials we also discussed that we represent a Max priority Q in a form of an array so first we'll create an integer array and we'll give it as a name as Heap and the second instance variable we'll give it as integer variable by name n so this will store the size of the max he moving ahead we also discussed that we will provide a Constructor so this Constructor will take the initial capacity of the Heap so inside this Constructor we also saw that first we will create an integer array whose size will be capacity + 1 so why we are taking this capacity + one is because index zero is kept as empty and we simply initialize the value of n to be zero because when we initialize this Max priority Q There Are No elements into this Heap so the value of n is zero we'll also provide a method which will return return a Boolean value and the name of the method would be is mty which will return a Boolean value that whether this Max priority Q is empty or not so we simply return n equal equal 0 so if the value of n is zero it will return true and if value of n is not zero then we know that there are elements into this Heap array also we'll provide one more method who type would be an integer value which would be nothing but the size of this Max priority Q so we'll simply return the value of n so whenever we call this size method it will return us back the size of this Max he that how many elements currently this Max she has so friend in the main method we'll first initialize the this priority Q let's say with capacity 3 and then we'll print it size and we'll also check that whether is currently empty or not so here you can see when we initialize this Max priority Q the value of n is z so the size return is zero so it will print zero and if you check whether this Max priority is empty or not so n is equal to Zer so it would return true if I run this code now so here you can see it printed zero and true so friends in this tutorial we actually discussed the basic and a very initial implementation of this Max priority queue in our upcoming tutorial we will see the operation a priority Q supports such as insertion get Max and delete Max I hope you like this video thanks have a nice day Hello friends welome welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss bottom up reepy and Max SE so friends in our previous tutorial we saw the initial implementation of a Max SE in Java now in this tutorial we will actually discuss what happens when we insert a particular element into this Max he so here you can see that a Max he is a complete binary tree in which each node value is greater than or equal to the values of its children so here you can see the node having value is 9 has two children 3 and six so 9 has a value greater than both three and 6 and similarly if we take a node having value as three it has two children 2 and 1 so both these values 2 and 1 are less than three so here you can see in Maxi each node is having value greater than the values of it children so friend this property is called as Heap order property of a Max Heap that each node value is greater than or equal to the values of its children so friend let's suppose we are given a particular Max having this Seven Elements now let's suppose if you insert any particular element into this Heap so after inserting that particular element into this Max he it may not satisfy this above property so friend let's suppose we are given any particular Max having this few elements so in this Max we know that the maximum value is always at root so friend let's suppose if we insert an element into this Maxi having value greater than 9 so friend as we discussed that Heap is a complete binary tree and here you can see all the levels are filled so when we insert a new node it will be inserted into this level four to the left of two and let's suppose we insert a value of 15 so once we insert this value as 15 the Heap order property which we discussed that each node value should be greater than or equal to the value of its children will break because two will be parent to 15 but its value is lesser than 15 so it will break the Heap OU property of this Max Heap so friends what we do is after inserting that particular value we perform bottom of re5 technique so in this technique what we do we simply adjust the location of elements so that it satisfi this Heap property so friend let let see a demo that how we can perform bottom of reep5 in a Max he so let's say we are given this Max he having Seven Elements and let's say we insert 10 so here you can see all the levels are filled completely and as Heap is a complete binary tree the value 10 will be inserted to the left of two at level four so it would look look something like this because in a complete binary tree all the levers are filled completely except the last level and the last level is filled in such a way that leftmost side is not empty so 10 will be inserted to the left of two so friend as it is a Max binary Heap we know that the maximum element always lies at the root of this binary tree but here you can see as we have inserted a value which is greater than 9 therefore the Heap order property is not being satisfied because as we discussed that each node in a Max should have values greater than the values of its children but here you can see if we compare two and 10 then the value two is less than 10 therefore it is breaking the Heap order property of Max so friends in order to satisfy the Heap OU property of this Maxi what we do is we simply adjust the locations of these nodes such that Heap order property is satisfied so here you can see as 10 is greater than 2 so what we do is we simply shift up the value 10 and we swp it with the two so it would look something like this the 10 is swiped with two so friends once we swipe this value we know that 10 is now greater than two so at this position 10 is satisfying the Heap order property of this Max he but here you can see after this swap we simply Traverse to this node and then we again see that whether it has any parent or not so here you can see 10 has a parent whose value is three so then we compare these two values because here you can see 3 is less than 10 so still the Heap OT property is not being satisfied so what we do is we simply shift up 10 and we swipe it with the three so it would look something like this so value 10 is being swapped with three so once we perform this swep we again Traverse to 10 and we check that whether it has any parent or not so it has a parent then we compare the parent to his children so here we'll simply compare 9 and 10 so here you can see the value of 9 is less than 10 so still the Heap outer property of this Heap is not being satisfied so what we do we simply perform a shift up and we'll simply swp these two values so friends when this swipe is done we simply Traverse to 10 and we again check whether it it is any parent or not so here you can see that 10 doesn't have any parent then we also see that he order property is satisfied because the root has the maximum value among the other notes now friend let's suppose we want to insert a value as8 so as it is a complete binary tree the other value will be inserted to the right of three so we simply insert 8 to the right of three so after we insert this value8 we simply compare it with its parent and here we see that 3 is less than 8 therefore the Heap order property is not being satisfied so what we do we simply perform a shift up and we simply swp these two values and once we perform this swap we simply reach to it and then we again compare it with its parent so here 9 is greater than 8 therefore the Heap order property is satisfied because in Max Heap the value of parent should be greater than the value of its children so 9 is greater than 8 so therefore the value 8 is at its correct position moving ahead friends in our upcoming tutorial we will see that how we can insert a value in Max Heap and we'll see the demonstration of the code step by step so the example we will take in our upcoming tutorial will be like this that let's suppose the max he is empty so first we are inserting four so as four is the only element into this Max he therefore the Heap OU property is maintained then we inser insert five so as level one is filled completely five will be inserted at level two to the left of four because we know that Maxi is nothing but a complete binary tree so five will be inserted to the left of four so once we insert five we'll simply check its value to its parent and as it is a Max we know that each node is having value greater than the value of its children so here we simply compare four and five and we know that four is less than 5 therefore the Heap order property is not maintained so we'll simply shift of five and we'll swp it with the four so now five is at correct position and we know that among these two values five is the largest value which is at the root of this binary tree moving ahead let let's say we insert two so two will be inserted to the right of five because left is already occupied by four so once we insert two we'll simply compare the value two with its parent and as 5 is greater than 2 therefore it is satisfying the Heap order property now let's say we insert six so here you can see the level two is filled completely so now six will be inserted at level three to the left of four and then we'll compare these two values and as four is less than six therefore we'll perform a shift up and we'll simply swap 6 and four so once we perform this swap will'll reach to this node and then we'll again compare with its parent so here now we'll compare five and six and we know that 5 is less than six so we'll perform a shift up and we'll simply swap these two values so friends here you can see six is at its correct position because it is the largest value among the other three values now let's say we insert one so one will be inserted to the right of five and then we'll compare it with parent and here we can see that 5 is greater than 1 so no swap will be done and let's say we insert three so now three will be inserted to the left of two we will compare three with its parent whose value is two and we know that 2 is less than three therefore we'll perform a shift up and we'll simply swap these two values and also friend then we'll compare three with six and we know that three is at its correct position therefore no swap will be done so friend this is how we perform bottom up reepy in order to maintain the Heap order property of Min or Max Heap so friend usually in most of the cases whenever we insert any new value in an Heap the Heap OU property breaks so after inserting a new element we simply perform a bottom of reepy technique in which we simply change the locations of the element so that they maintain a heap owder property and we we also give different names to this technique we call it bottom of Rey we also call shift up we can also call swim because the element usually swim from bottom to top when we insert a new element so in our upcoming tutorial we'll actually see the code to insert an element into a Max and we'll look the demonstration of that code step by step I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to insert in a Max seep in Java so friends in our previous tutorial we actually discussed about what is a Max he that it is a complete binary tree in which each node value is greater than or equal to values of its children and we also discussed that the maximum value of this Max binary Heap is at root and if you look into its arror representation we also discussed that how we actually place these values inside this Heap AR so we simply put these values level by level from left to right so here you can see in this Heap array if we return the value at index one we'll always get the maximum value of this Heap also friends we discussed in a previous tutorial that priority Q helps us in getting the maximum value among the the collection of elements in constant time so if we simply return the value of index one we get the maximum value of this Max binary Heap and similarly for the main binary heap if we return the value at index one we'll get the smallest value among the collection of elements so let's see how we can insert a value in Max he so friends in our previous tutorial we actually discussed the the basic implementation of the max priority Q so in this tutorial we'll actually see how we can insert a value into this Max priority Q through this insert method so in our previous tutorial we also discussed that when we call this Max priority q and let's say we provide a capacity of three so it would create an integer array having length for because we are initializing this Heap are with length as capacity + one as we are not using the zero index of this Heap array and we start inserting from index one therefore here you can see the initial capacity of this Heap ARR is three so here Heap do length is four so here you can see currently there are no elements into this Heap array so the value of n is zero which we already discussed in our previous tutorial also so friends in our previous tutorial we actually saw a demonstration of how we can insert few elements in Max he so friends we will insert the same elements into this Heap array and we'll see the demonstration of this code step by step so let's say first we insert a value as four so the insert method will be called and the value which we want to insert is four so X will become four moving ahead so friend then we provide a if check that whether n is equal to Heap do length minus one or not so here you can see Heap do length is four and if we do a minus one we get three so here we are simply checking that value of n is equal to 3 or not because if value of n is equal to 3 then we know that we have utilized all the capacity of this Heap array and there is no no more additional space left to insert the value four so here you can see currently value of n is z and it is not equal to Heap do L minus 1 which is 3 so the condition in if blog comes out to be false in The Next Step as we are inserting four into this Heap array first we'll increment the size of this Max priority Q by one then that we are about to insert one element into this Max priority que also friend as we are not utilizing the index zero so what we'll do we'll simply insert X at index one so it would look something like this so we are simply assigning the value of x to Heap at index one because value of n is one so four is inserted also friends we discussed that whenever we insert any value in a Max he we then perform a bottom of REI which we also called as swim so here now we'll actually call a method swim by passing in the value stored in N which is 1 so yes swim method will be called and here you can see that as we are passing the value of n as 1 so K will be become one so friends then in swim method we actually provide a while loop so what we do in this V Loop we simply check the newly inserted value with its parent and as it is a Max priority Q we simply check that its value is lesser than or greater than to its parent and if it is greater than its parent then we simply swp them and if it is lesser than its parent then we do nothing so this is the condition we actually provide into this V Loop so the first condition we provide is K should be greater than 1 because here you can see K value is 1 and here you can see that as there is only one element into this Heap array there is no parent to index one because it is the root of the Heap so the condition in while block comes out to be false so four is inserted into this Heap array and it is placed at its correct position now let's say we insert five so X becomes 5 we check that whether n is equal to Heap do length minus 1 or not so n is not equal to 3 because Heap do length is 4 and 4 - 1 is 3 so the condition in if blog comes out to be false now as we are inserting five we'll first increment the value of n by 1 so n becomes 2 so as you incremented n by 1 we'll simply insert 5 at index 2 by simply assigning the value of x to Heap at index 2 moving moving ahead so friend as you inserted five now we simply perform the bottom of reify by calling this swim method and inside this swim we'll simply pass the value of n so value of K becomes 2 because n is 2 now friends here you can see as we discussed in the previous tutorial that four is at root and one of its left child is five so friend as we have inserted five in while loop we'll simply check that whether value of K is greater than 1 or not so here you can see K is greater than 1 because value of K is two and in our previous tutorial we also discussed that in order to calculate the parent of any index we simply do K by2 and why we are doing this K by2 because we need need to compare this newly inserted value with its parent so here you can see value of K is 2 if we do K by 2 we'll get 1 which signifies that 4 is parent to five and then we'll simply check that whether value at parent is less than its children or not so for as it is a Max priority q k by2 is nothing but one and the value at index 1 is four which is parent to five so we'll simply compare this two values and we'll simply check that parent is less than its children or not so here you can see 4 is less than 5 therefore it is breaking the Heap order property so the condition in while block comes out to be true and in order to maintain this Heap OT property we'll simply swap these two values so it would look something like this that first we will assign five to this temporary variable and then we'll simply assign the value at index K by2 to K which is nothing but value at index one to value at index 2 so it would look something like this moving ahead and then we'll simply assign the value of five to the index K by2 which is 1 so it would look something like this and as we have swapped these two values now we will Traverse to five again in order to check that whether it's at its correct position or not because then we again compare with its parent so in order to reach to this index again we simply assign the value of K by2 to K which is nothing but traversing K to its parent by assigning K by2 to K so here you can see the value of K by2 is 1 so K will become 1 and then again in while we'll check whether K is greater than one or not so here you can see that five is at its correct position because among these two values five is the largest value and it is placed at the top of this Heap which is nothing but at index one therefore the condition in while loop comes out to be false now let's say we insert two so X becomes two we check whether 2 is equal to Heap do length minus 1 or not so Heap do length is 4 and Heap do length - 1 becomes 3 so n is not equal to 3 so the condition in if blog comes out to be false false and as we are inserting two we'll simply increment the value of n by 1 so n becomes three and to the third index of this Heap array we'll simply assign the value as two and then we'll simply perform the bottom of Rey add this index which is nothing but three so K becomes three now K is greater than 1 which is true now we have to compare two with its parent so we simply do K by 2 so if we do K by 2 it becomes 1 because 3x2 will give us 1.5 and as we are using it as integer it will be round of to one so here parent is at index one and child is at index K which is three so we'll simply compare these two values and we'll simply check that parent value is less than the child value or not so here you can see 5 is greater than two therefore the condition in this V block comes out to be false so now let's say we insert six so X becomes 6 and now here you can see value of n is 3 and Heap do length is 4 if we do minus 1 it becomes 3 and here you can see 3 is equal to 3 so friends here it signifies that this Heap array is filled completely and there are no more space left to insert six so the condition in if block comes out to be true so what we do is so we'll simply call resize method by passing in a value which is twice of Heap dot length which is nothing but 8 so friends in our ARR section we actually discussed how we can resize an array in Java so you can watch that tutorial to understand more about this resize method so what thises method actually does is it will resize this Heap array to a size double of its current length so once this method gets executed it will look something like this that Heap array has now length of 8 which is double of its previous length so we actually perform this resize method because we want to insert more elements into this Heap array so then we'll simply increment n by 1 and now we'll simply insert the value X at index 4 so it would look something like this and then we'll simply perform bottom of REI at index 4 so K becomes 4 now here in the while block K is greater than 1 which is true and now we have to compare this newly inserted value with its parent that whether it is satisfying the Heap order property or not so in order to know the parent of six we take its index which is at 4 and we divide it by 2 so K by2 becomes 2 so here the value of index 2 which is four is actually parent to value at index 4 which is six so now we'll simply compare these two values and we'll check that whether value at par parent is less than the valued child or not so here you can see 4 is less than 6 therefore it is not satisfying the Heap order property so the condition in V block comes out to be true so friends now we know that we have to swap these two values so we'll simply perform swap we'll assign six to a temporary variable and then we'll assign the value at index K by2 to K which is nothing but assigning value 4 at index 4 so it would look something like this and finally whatever the value is stored in temp we are simply assigning it to Heap as index 2 and also friends in our previous tutorial we discussed that whenever we insert a new value in a heap we keep shifting it up till it reaches to its correct position so here you can see that we have swiped 6 and four and six is at index 2 so friends after we perform this swp 6 is at index 2 so friends after we perform this swap we simply Traverse to this index by assigning a value of K by2 to K so here you can see K by 2 is 2 and if you assign it to K it becomes two and also here you can see K is 2 which is greater than 1 which means that there is a parent to six so we need to compare it with its parent so here its parent is at K by2 if we do K by2 we get the value one so the value at index one is parent to six so will simply compare five with six and we'll check whether 5 is less than 6 or not so here you can see 5 is less than 6 so the condition in V block comes out to be true and as we are inside this while loop we'll simply swap these two values using this temporary variable so at First Step we'll simply assign the value at index 2 to temp and then we'll assign the value at index one to index 2 so it becomes 5 and finally we'll assign the value stored in this temporary variable to index one and after we perform this swep we'll simply Traverse to its parent by assigning K by 2 to K so K by2 is 1 so K will be become 1 now as K is equal to 1 it is not greater than 1 so therefore we know that 6 is now at its correct position because among these four values 6 is the largest value and we know that in Max he the value at index one is the maximum among the other values so the condition in while block comes out to be false now let's say we insert one so X becomes 1 so here value of n is 4 and it is not equal to Heap do length minus 1 which is 7 so the condition in if log comes out to be false now as we are inserting one we'll first increment the value of n by 1 and at index 5 we'll simply assign assign the value which we want to insert so it looks something like this and then we'll simply perform the bottom of REI at index 5 so K becomes 5 and here K is greater than 1 so here as we have inserted 1 now we'll compare this value with its parent so we know that this value is at index 5 so if we do K by2 we will reach to its parent so 5x2 will give us 2.5 and as we are taking it as integer it will round off to 2 so K by 2 becomes 2 so if you see the value at index K by2 which is 2 is 5 so here we simply comparing five with one because we know that one is child of five so here we are simply checking that whether value at parent is less than child or not so 5 is greater than 1 therefore condition in while block comes out to be false and by this we mean that one is at its correct position because it is child to five and five value is greater than one which satisfies the he property now let's say we want to insert three so X becomes 3 the condition in if blog comes out to be false because 5 is not equal to 7 we'll increment the value of n by 1 as we are inserting three now so n becomes six so at index 6 we'll simply insert three and then we'll simply perform the bottom of Rey at index 6 so we'll call swim method and pass the value as six so value of K will become six now here whatever the value we inserted at index 6 we'll simply compare it with its parent that whether it is less than its parent or not so here K is greater than 1 because value of K is 6 so first we'll evaluate the parent of three so we'll take its index we'll divide it by 2 so K by 2 becomes 3 so the value at third index is two so two is parent of three so we'll simply compare these two values and we'll check whether parent value is less than child or not so here you can see 2 is less than three so the condition in V block comes out to be true so once the condition comes out to be true in the while block we simply swp this two values so it would look something like this we'll assign three to this temporary variable then we simply assign the value at index 3 to value at index 6 by simply assigning the value at index K by 2 to K so it becomes two and finally we simply assign the value three to value at index 3 so it becomes three so friend as the value of K was 6 and we swed 3 and 2 so three reached to its parent so now we'll simply assign the value of K by 2 to K because we need to again compare three with its parent so once we do K by2 to k k becomes 3 and in while block we again check whether K is greater than one or not so K is greater than 1 and we'll simply compare three with its parent so first we'll evaluate its parent by taking its index which is three dividing it by two which will give us 1.5 and as we are taking it as integer it will round off to one so the value of Heap at index K by2 is nothing but value at index one because 6 is parent to three and we'll simply check that whether 6 is less than three or not so here you can see 6 is greater than three so the condition in while block comes out to be false which means that 6 is at its correct position and also the three which is at its correct position so friends here we saw the demonstration of how to insert a value in a Max Heap and we saw the demonstration step by step we also saw that how we can perform bottom of Rey in case the Heap order property is not being Satisfied by inserting a new element so friends in our next tutorial we'll code this insert method and we'll test it's working I hope you like this video thanks have a nice day Hello friends in our previous tutorial we actually discussed that how we can insert a value in Max priority Q so in this tutorial we'll actually code the insert method which will perform the insertion into this Max priority que so friends in our previous tutorial we actually created one class by name Max PQ which had an integer array which was nothing but our Heap and we provided a Constructor which took the initial capacity of this Max priority Q we also provided two methods is is empty and size so is empty tells us whether Max priority Q is empty or not and size method will tell us that how many elements are there into this Max priority Q so in this tutorial we actually code about the insertion in this Max priority que so we create a method as public void insert so this insert method will take in a value which we want to insert so here I'm taking the argument as X so inside the insert method first we will check that whether this Heap array can accommodate a new value or not so we'll simply check that whether value of n is equal to Heap do length minus one or not so if the value of n which is the size of this Max priority Q is equal to Heap do Len minus one it means the integer array is failed completely and there is no space to insert the new element so if this condition comes out to be true we simply resize this array dynamically and as initial length is heaped do length we'll simply resize this array to twice of its current length so we'll simply Pass 2 into heap. length so then we'll create a method resize so this resize method will take the new capacity of the array so here if the if condition comes out to be true it means that Heap array is filled completely so into this resize method what we do we first create a new array with whatever the capacity we pass to this resize method after creating this new array we simply copy each and every element from this Heap to this temporary array and then we finally reassign this Heap to this newly created array so here first we'll create a new temporary array whose length would be the capacity which we have passed after creating this temporary integer array we will copy each and every element from this Heap to this temporary array so we'll start from zero and we'll Traverse till heap. length and inside this for Loop we'll simply copy the value at particular index I to this temporary array and after copying the contents of this integer array we'll simply reassign temp to Heap so now he will point to an array which is of length twice of its current length so after the resar method gets executed the integer array Heap will now have more spaces to insert new elements so here after if block the first thing we do is as we are inserting a new element we'll increment the size of this Max priority Q by one and then we'll simply insert the value X into this Heap array so we'll simply assign the value of x at index n and after this insertion we we know that now we have to perform bottom of hii by creating a new method swim and by passing it the value n because now we have to perform the bottom of F at index n so here we'll create a new private method swim which will take the argument where this this new index have been inserted so inside this swim method we'll provide a v Loop because in this value we'll simply compare this newly inserted value to its parent and we'll check that whether parent is less than this newly inserted value or not so the first condition we provide is whether K is greater than one or not because if K is equal to one then we know that currently Heap has only one element and if value of K is greater than one then we know that there are more than one elements into this Heap so then we'll compare the value at parent index which is K by 2 with value at K index and if both the condition comes out to be true we simply swap these two values so here so using this temporary variable we will swp these two values and after we perform this swap we'll simply Traverse to its parent by assigning K by 2 to K because we need to continue shifting up till New value inserted is at correct position that means whatever the value we inserted is at its correct position so that the Heap OU property of Heap is satisfied so friend this is how we actually insert a new value into the max priority queue now in the main method Let's test it's working so I will just remove this so let's say the initial capacity of this Max priority Q is three so here we will insert few values which we discussed in our previous slide so first we'll insert four then we'll insert five then we'll insert six then we'll insert 1 and then we'll insert three and then we'll simply print the size of the priority Cube if I run the code now so here you can see the size it printed is six because we have inserted six elements and also friend if you print this Heap array so here I'll create one method as print Max Heap so inside this print Max method I'm just excluding the edge cases so I'm simply providing a for Loop which will iterate from I equal to 1 because into this Heap array the value at 0 index is empty so we are starting from one and we'll simply Traverse I to a value n which is nothing but the size of the max priority Q and inside this for Loop we'll simply print the value of the add index of this Heap and in the main method we'll simply call Print Max he and if I run the code now you see it printed 653 412 which is the same output which we discussed in our previous tutorial and here you can see that as it is a Max priority Q the value six which is largest among the other values is that index one so friend in this tutorial we actually discussed how we can insert a value into this Max priority Q in our upcoming tutorial we'll see how we can delete a particular element from the max priority queue I hope you like this video thanks have a nice day hello everyone so in this video we are going to discuss top down reepy in Maxi so this technique is also called as sync so in this technique we are simply doing the repy in one of our previous video we saw the bottom of Rey and in this video we will be looking into top down rep5 so when we are inserting an element in a binary Heap we usually do bottom up repi and when we are deleting the max element from the Heap we usually do top down repy so friends here you can see that we are given with a Max binary Heap now a Max binary Heap as we already discussed in our previous videos that it's a complete binary tree in which each node value is greater than equal to the values of its children so for example 9 is greater than 3 and 6 3 is greater than 2 and 1 6 is greater than 5 and four so this is the one of the property which Max binary Heap satisfies the other thing is it should be complete binary tree as we already discussed that a complete binary tree is a binary tree where all levels are completely filled so for example here you can see there are three levels 1 2 3 so here all the levels are completely filled except the last level and last level has nodes in such a way that left side is never empty so here all the levels of a complete binary tree should be filled so here you can see this level is filled in the second level it can have only two childrens so this level is also filled and in the last level this side is not filled so except the last level all the levels should be filled and the node should be filled in such a way that left side is never empty so here this is the complete binary tree because the elements are filled from the left side like this but here you can see that this is a incomplete binary tree because all the levels are filled except the last level but this is not a complete binary Tre because the left side is empty because there could be one element coming up here so the insertion of nodes or the element should be such a way that it should be from the left side and the left side is never empty so if suppose here could have been one more element let's say six so this is also a complete binary tree because all the lever are filled and now next element would be inserted from here from the left side and if any of the element is not filled from the left side then this would be incomplete binary tree so here you can see when do we actually require top down reepy so when we delete an element from Heap there may be a case that it may not satisfy the Heap properties so deleting an element we mean delete Max from the max binary Heap and delete minan from the Min binary Heap so when we delete the max element from Heap let's say if we want to remove the max element which is at the root at index one so if you want to remove this element after its removal there arise a problem that this Max he may not satisfy the Heap properties thus we perform top down reify technique in which we adjust the locations of the element to satisfy the Heap property so now let's move ahead and see how we can perform this technique so let's say we are given with this Max binary Heap where the elements are stored in a an array starting from index one which we have already discussed in our previous videos now let's say when we call delete Max so we want to remove this element 9 but if we directly remove this element 9 the Heap property of this Max Heap will not get satisfi so what do we do is before removing 9 we simply store its value in some variable let's say Max now after storing the value because we need to return this value from the delete Max so we are storing it in a Max variable now after getting its value what we do is we simply take the last element which is filled in the max SE and we simply Swip both the elements so here 9 will be swapped by four so four comes here and 9 comes here now after this swap we can easily remove nine because this is the last element so nine gets removed but as we swapped it with the four the Heap order property is not getting satisfied because in the max Heap the root element should be greater than or equal to the values of its children so 4 is greater than three but it is not greater than 6 so therefore Heap water property is breaking here so now the third step we apply is we do top down rep5 now in this technique what we do is as the root element or the parent element should be greater than or equal to the values of its children the Heap po property is not getting satisfied at this location so the children of index one which is 2 and 3 we will first compare 3 and six together and we will find which is the max element among these two values so we will compare three and six so 6 is greater than three it means now we need to compare the parent value with six as parent value should be greater than both the values of his children we are simply comparing the parent element with the max of the values of its children so here we are not comparing four with three because we have already compared three with 6 and as 6 is greater than three now we'll simply compare four with six so here can see 6 is greater than 4 it means parent value is smaller than the value of its children therefore what we do is we simply perform a shift down which is top down or we can also call sync what do we do in this technique is now we simply swp six with four so six comes here and four goes here so here you can see now now the parent value is greater than both of its children so after doing this what we do is as we performed the shift down the parent element is at its correct position and then we simply Traverse to this position and then we perform the same steps again because there could be a possibility that four may not still satisfy the Heap OU property so what do we do is when reaching four we see that it has only one children therefore it doesn't have the other children so we can directly compare four with five so here five is greater than four it means the Heap OU property currently is not getting satisfied so we simply do a shift down so five comes here and four Comes Here and Now after performing shift down we reach here and now here you can see it doesn't have any children it means five is placed at its correct position six is placed at its correct position and four is also placed at its correct position so now here you can see that Max he property is getting satisfied and all the elements are at its correct position and at the end we simply return the value N9 now let's see one more example let's say we are given with this Max he where all the levels are filled completely except the last level and it is also getting filled from the left hand side now let's say we call delete Max so the first step we do is we simply store value 10 in the max variable the second step we do is we take the last element of the max Heap and we simply swap it with the root element so three comes here 10 comes here so after we perform this swap we can now easily remove this element and as 10 is removed one problem it has created is like the Heap owder property may or may not get satisfy so after we perform this swap we are at this position and we need to place the maximum value among this three values because three is the parent 9 and six are its children and whichever value is the greater among this three should come here so here we have to compare three with N9 and three with six or what we do is we simply compare both the children value which is 9 and 6 and whichever value is greater so here 9 is greater so we simply compare 9 with three because if let's say here would have been 11 for example so if 11 is greater than 9 it will also be greater than 6 because we have compared this two values already so currently it's three so now 9 is greater than three therefore what we do is we do a shift down nine comes at this position and three comes at this position so we are doing a swap and after doing the swap we reach here and then we try to compare this index value which is three with its children so here you can see now we simply compare 1 and two and whichever value is greater among these two which is two we simply compare it with three so here you can see 3 is greater than 2 therefore there won't be any shift down because three is now at its correct position because it is greater than both of its children so we don't do anything and the process ends here and this max value will be returned so why we are comparing these two children is because we need to compare parent with the greater value among this two because if 3 is greater than 2 then 3 will also be greater than 1 so that's why first we compare both the children's value and whichever value is greater among both the children we simply compare that value with the parents value and if the parents value in Max he if it is less then we do a shift down and if it is more like the current scenario then we don't do anything because three is at its currect position now let's see one last example let's say we are given with this Max he currently all the Heap properties are getting satisfied let's say we call delete Max so first we store the value 9 then we swap this value with the last value of the max he so 0 will come here and 9 will come here like this and after doing this swap we can safely remove this element with value 9 so now here you can see after this we we are starting from the very root node and there might be a case that Heap OU property is not getting satisfied so what do we do is first we compare both its children which is 3 and six and we figure out which is is the max element so if we compare 3 and 6 so 6 is greater than three so now we compare 6 with its parent value so 6 is greater than zero it means that whatever value is at index one is not satisfying the Heap order property because in the max heat the parents value should be greater than both of its children so we do shift down so six comes here and zero comes here and then we reach here now again there could be a possibility that after this Swap this value zero is still not satisfying the Heap order property so what do we do is we simply compare both The Childrens First and whichever is the max in this case it is five so we compare zero with five as 5 is greater than zero therefore the value of children is greater than the parent so it is not satisfying the Heap order property so we do a shift down five comes here and zero comes here and then finally we reach here and here we see that it doesn't have any children so therefore now zero is at its correct position five is at its correct position and six is at its correct position so here 6 is greater than 3 and 5 5 is greater than 0 and 4 and at the end we simply return return nine so friends in this video we saw that when we perform a delete Max operation in a binary Heap there could be a possibility that Heap order property is not getting satisfi in a binary Heap therefore we do top down reepy which is also known as syn or shift down where we are simply shifting down the elements till it reaches at its correct position so friend this was all about top down re5 when we perform delete Max in our next video we'll actually see the implementation of the algorithm step by step I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss that how to delete the maximum element in Max in our previous video we saw the top down reepy technique when we actually deleted the maximum element from a binary Max he and in our previous video we also saw that a Max he is a complete binary tree in which each node is greater than or equal to the values of its children so here you can see that N9 being parent to 3 and six has values greater than both of its children three is having value greater than both of its children six is having value greater than both of his children so it's a Max binary Heap and when we want to delete the maximum element from the max Heap the maximum value is usually at the top which is also the root of our binary tree so here Max is usually demonstrated in the form of a binary tree but the data is actually stored in the form of an array where index zero is empty we usually take index Zer is empty because it help us in evaluating the children of any parent we also saw the formula for evaluating the children of any parent given at index I which is 2 I and 2 I + 1 so this is child one and this is child two so this is what we actually discussed in our previous videos as well so usually we fill this array from left to right level by level so this is level one so 9 comes here then we go to level two the first element we see is three so three comes here six comes here then we go to level three 2 1 5 and four so this is what we actually discussed in our previous videos as well so if you mark this indexes at each element it would look something like this 1 2 3 4 5 6 7 now in order to access the maximum value in this Max he we simply take the value stored at index one which is heap of one and then we perform delete operation on the top of it and after we perform delete operation we also do the top down reepy so let's see it by an example which we already discussed in our previous video Let's suppose we are given with this Max he and we want to delete the max so first thing we do is we simply store the maximum value which is at heap of index one into Max and then we actually pick the last element and we swipe it with the the element which we want to delete so 9 and four are swapped four comes here 9 comes here and then we can say safely remove 9 but here you can see when four reaches here it doesn't satisfy the heat powder property the value of four should be greater than both of its children but here you can see four is greater than three but four is not greater than 6 so therefore here what we do is we compare four with its children either we compare four with both of his children or we can first compare both the childrens and take the maximum value out of them and then compare that maximum value with the parents value so first we compare both the children's value so 6 is greater than 3 so as 6 is greater than three now we compare the parents value with six so 6 is greater than 4 it means that he order property is not satisfied and we perform a swap we Tak six here and four here by doing shift down or top down repy so six comes here four comes here and after we do swap six is at its correct position then we actually go to its fun of the children from which we did the Swap and we again perform these stps as four doesn't have the right child so we directly compare four with its left child value five so five is greater than four so therefore we do a shift down five comes here and four comes here and here you can see after we do this swap five is at its correct position then we simply Traverse to four and perform the same steps again but here you can see four doesn't have a left or a right child therefore four is also at its correct position so therefore now Heap OU properties Satisfied by all the values of this Max Heap and at the end we simply return nine so now let's see the implementation of this algorithm step by step so this binary tree now we'll see the implementation in the form of an array so let's say we have this binary Heap and we know that it is starting from index one which has the maximum value in in this binary Max he the value of n which is the total number of elements is 7 we have already discussed this in our previous videos so value of n is 7 now we call delete Max so the first step we do is we simply store the value 9 in Max because at the end we need to return this value and as we are going to delete the max we first store it in the max variable which is N9 so 9 is stored in Max and we also discussed that after we store the value in Max variable we perform a swap with the last element and the root element which we are trying to delete so we pass one and N so in the swap method we are using this temporary variable and then we simply perform a normal swap so we'll go over this quickly so a is 1 and b is 7 we are sing 9 and four using the temp variable so first we are storing 9 in temp then we are storing four into heap of a which is 1 and at the end we are storing temp value at heap of B which is 7 so 9 comes here so after this method gets end 9 is here and four is here so now we can decrement the value of n because we need to remove 9 completely so total number of elements should become six now so n comes here and then here you can see we are having four here so four is not actually satisfying the Heap ouder property if we see the children of four it is at index 2 into I and 2 into I + 1 which is at index 2 and index 3 4 is greater than 3 but 4 is not greater than 6 and in the max he parent should be greater than both of its children so this formulas we have already discussed in our previous video that how we we can evaluate the children of a parent so now we actually do this top down Rey using this sync method we pass the value of the index from where we need to do this reify so currently the index value is one so we will call sync method now so the call will reach the sync method so this is the sync method where we have pass the value as one so K will become one which is the index from where we need to start our top down Rey now here we need to perform this top down reify till the Heap OU property satisfied or there are elements left such that we compare the parent with its respective children so this is the condition for that we are doing doing 2 into K less than equal to n so K is at index one its children will be at 2K index which is two and total number of element is six so 2 is less than 6 it means that element four has some children so this V Loop will execute and this condition comes out to be true so at the first step what we do is the J represent one of the children of K which is given by Formula 2 into K where K is the index of parent which you can see here if we do 2 into K we get index two so value of J will become two because J is one of the child of K so friend when we saw the animation we we first compared both of the children of the parent and whichever was the max we took that particular children and compared it with the parents value so here so first we check whether the parent has actually a right child or not because by this condition parent does have a left child because 2K value is less than equal to the number of elements we have here J less than n denotes that there is also a right child of this parent so how we can understand this is let's say let's say if we take this example here so currently this element will be removed because n is pointing to six so 1 2 3 4 5 6 so this is the present condition so for example here K value is 1 which is the parent index let's say k points to here at three if we do 2 into K we will reach to one of its children so 2 into 3 we reach here which is the child one so this condition tells us that there is one child to this parent and here you can see value of J is 2K which is 6 if 6 is less than six which is total number of elements it means there is also one right child currently 6 is not less than 6 therefore we are sure that there is no right child here if we take K value as three so therefore this condition tells us that whether we have a right child or not because we need to compare both the left child value we we have to take one of the maximum value among those and then we have to compare it with the parents value So currently value of K is 1 the index of its first child is at two and index of its next child is at three so three is less than 6 therefore we know that for K = to 1 it has both left and the right children so this condition is very important so currently this condition comes out to be true then we check whether heap of J which is value three is less than heap of J + 1 or not it means we are now comparing 3 and six which are actually children of four present at index one this and this we are comparing so 3 is less than 6 therefore this condition comes out to be true now why we are incrementing J is because J is actually telling the position of the element which is the maximum child to which we need to compare with the parent so J points to 3 which tells that 6 is the maximum value among this two children and now whatever we want to compare we need to compare parent with this value at J you will understand more this in next iteration so now we calculate whether the parent value is greater than or equal to the child value or not so here four is compared with six he of K is compared with heap of J so 4 is not greater than or equal to 6 so this condition comes out to be false and if this condition comes out to be false it signifies that Heap OU property is not getting satisfied so then we perform a swap between four and six so we'll quickly go over this method six will come here and four will come here so 6 has come here and 4 has come here so now six is at its currect position it is parent to three and four and its value is greater than both both of its children now when we discussed that after we do shift down in our previous example we actually reach to the position which actually did the swap so our next C value we assign the value J so K becomes 3 now when we did this swep six came here and four came here and then we move to four because this four we still need to figure out whether this might or might not satisfy the Heap otter property because there are more elements left in the Heap so we first check whether K has any left child or not so if 2 into K is less than equal to n which is 3 into 2 6 it is less than equal to n which is 6 so therefore it must have a left child and what would be the index of the left child would be 2 into K which is 6 so J points to index 6 now we actually check with this condition whether K also have a right child or not so 2 into k + 1 will give us the right child 6 + 1 7 but here you can see 2 into K which is J and if we do plus one we'll get the right child 7 is not less than 6 therefore it doesn't have a right child three only has a left child which is five and it doesn't have a right child so this condition is important so this overall condition will come out to be false because J is not less than n j is actually equal to n now we compare the parent value with the child value because J is pointing to the only child of index 3 so 4 is less than 5 this condition comes out to be false and then we perform a swap between four and five so a is 3 and b is 6 we are spping four and five five comes here and four comes here now after this weap we take k to its one of the child from which we compared so we are simply assigning J value to K so K will become 6 now here you can see 2 into K is not less than n because if we do 2 into K which is 2 into 6 which will give us 12 and value of n is 6 therefore this condition comes out to be false with which also signifies that we have completely performed the top down re5 six is at its correct position five is at its correct position and four is also at its correct position because it doesn't have any left or right children so the sync method will end and call will reach here and this is our array when we perform the syn op operation and after we perform sync operation we can simply delete this element by assigning a null value to Heap n + 1 n is pointing to this index which is six so n+ one will point to here so we are making it null now and here as we are doing delete Max there will be a time when most of the elements will be deleted from this Heap array so we simply comparing whether n is greater than Z and if n is equal to Heap do length minus 1 by 4 which is like 1/4 of the Heap do length if n is equal to that then we simply resize the array by half of it so we'll see the demonstration of this resize later so currently n is greater than 0 but n is not equal to Heap do length which is 9 - 1 by 4 8 by 4 2 value of n is 6 and it is not equal to 2 therefore this condition comes out to be false and we return the maximum value which is nine and we have also removed 9 from this Heap so friend let's suppose we keep on deleting the elements like this so This array will have more and more n values and let's say we call delete Max and we want to remove three so we have performed these steps and we need to remove three and let's say we have also performed sync so this will be the array and now if you assign null to the Heap of n+ 1 as we want to remove three this will become null so in this case we are simply seeing the condition that this if blog comes out to be true let's say we keep on removing the elements so there will be null values in the array so n is greater than Z and N is actually equal to Heap do length minus 1 / 4 so Heap do length is 9 - 1 by 4 which will give us 8X 4 2 and value of n is equal to 2 this means both the conditions are true so now here what we do is we call the resize method which we already seen in one of our previous video where we are simply providing the new length of our Heap where we are simply saying create a new heap of half of its current length which is 9x2 which gives out to be four so we are removing this additional space which we have occupied we are freeing it up and we are creating a new array which has the size half of the current heap's length so when this method will get executed our Heap AR will become something like this that we have resized the Heap to Heap dot length by two which is four so we have removed the unwanted occupied space so this resize method we have already discussed in one of our previous video you can watch that video and at the end we simply return three so friend this was all about that how we can delete the maximum element in a Max E using delete Max method we saw the implementation of delete Max and also the top down reepy method which is sync I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss linear search algorithm in Java so friends here we are given an array of let's say n elements and we are given an element X which we want to search into this array So Below you can see the algorithm to search for an element X into this array so this search method takes in the array into which we want to search an element here we also pass the value of n which is nothing but the number of elements in an array and we also pass the value of x which we want to search into this array so let's suppose if you given this array which has seven elements and we want to search an element X having the value as 10 so let's see the demonstration of this algorithm step by step so here you can see the number of element into this array is 7 and the value which you want to search is denoted by X which is 10 moving ahead so how this algorithm works is is we start from the leftmost element of the array and one by one we'll compare x with each and every element of array so here if x matches to any of the element then we simply return the index of array and if x doesn't match with any of the element in the array we simply return minus one so here in order to compare x with each and every element of this array we provide a for Loop which basically start from the leftmost element and Traverse till the last index of the array so here in this forl we are iterating I from 0o to a value less than n which is nothing but 7 so I will travel from 0o to less than n which is 6 and then we'll compare each and every element of array with X so at the start of our Loop I becomes zero so this I is nothing but the index value of the array so we will start from the leftmost element in the forl will provide a condition that value at index I is equal to X or not so here you can see the value of index 0 is five and five is not equal to 10 therefore the condition in if blog comes out to be false so here we are incrementing I by 1 so I becomes 1 so now in the ifog we are again comparing that value with I index is equal to X or not so value of I is 1 and if you take the value of the index one is 1 and if you compare it with X then 1 is not equal to 10 so the condition in if block comes out to be false so after the increment now I will become two and we will use this D to point to the second index of the array in the F blog we'll again check that the value of array atti index is equal to X or not so here you can see the value of array at second index is 9 and 9 is not equal to 10 therefore condition in if block comes out to be false will then increment I by 1 so I becomes 3 moving ahead so here in the block we again check that whether value at I index is equal to X or not so value of I is three so value of error heart index is 2 and 2 is not equal to 10 therefore condition in if log comes out to be false and after increment I becomes four now in the we again check that value of a aat index is equal to X or not so here you can see the value of err at Fourth index is 10 and if we compare it with X then both values are are equal so the condition in if loog comes out to be true and here we have found our element at index 4 so the flog will execute and we'll simply return return the value of index where we have found the element which is nothing but four so friend this is how the linear s algorithm Works in Java all also friends if you had searched any value which was not given in this array then after this for Loop we would have simply returned minus one because we haven't found the value into this array so friend this was the demonstration of the algorithm now let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually saw the demonstration of the linear search algorithm so now in this tutorial we actually code the linear search algorithm and we'll test it's working so here first we'll create a search method so public whose return type would be the integer because we are returning the index where we have found our search so I'll give the name as search now this search method will take the array into which we want to search for a particular element it takes the value of n which is nothing but the number of elements of this array and integer X which is nothing but the value which you want to search so friends here this search method will return back as an integer value which is nothing but the index where we have found our search and if we haven't found our search then it will return back as minus one so here we'll provide a for Loop which will iterate over each and every element of this array and inside that for Loop we'll compare each and every element with the X and if it is equal then we'll simply return the index so we'll provide a for Loop which will start from zero and which will go to a value lesser than n so ins this forl will simply provide a f condition we'll compare value at add index with X and if the condition in if blog comes out to be true we'll simply return the index value where we have found our element and if the for Loop executes completely and we haven't found our element then we'll simply return minus one which indicate that we haven't found our element so friend this is the code whose demonstration we saw in our previous tutorial now in the main method Let's test it's working so here we have actually created an array with few elements so first we'll create the instance of linear search class and then we'll simply call the search method we'll pass in the array and the number of elements would be the length of the array and let's say we want to search for a value 10 so we'll pass 10 so whatever the integer value it returns we'll simply printed on the console if I run the code now so here can see printed 4 which means we have found our element at index 4 now let's suppose if you want to search a value which is not present in this array so if I search for Value as 50 and if I run the code now so here you can see it return return minus one which states that we haven't found our element into this array so friends here in this tutorial we actually coded the linear search algorithm and we tested its working I hope you like this video thanks have ni day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss binary search in Java so friends what is a binary search binary search is a divide and conquer algorithm so here if you see that suppose if we are given an array which is sorted so here you can see the numbers are sorted in ascending order so friends let's suppose we want to search an element in an sorted array so what we can do is either we can perform a linear search that we can compare the elements with an array with an element we want to search so this linear search will go on with the each and every element that we first check with the number at zero index then one then two then three and it goes on till the end of the array but here if the array is sorted then instead of doing a linear search we can do a binary search so what we can do is we can repeatedly divide an array into half and with the E division we know that we are dividing the the array into two halves so we usually compare the element we want to search with the middle element and if suppose the element we want to search is less than the middle element then we can ignore the other half and we can search in the first half and if the element we want to search is greater than the middle element then we can ignore the first half and we can search in the last half so below you can see the algorithm for the binary search now let's see the demonstration of this algorithm step by step so suppose we are given an array having nine elements and and here you can see the array is sorted so suppose we want to search a key having the value of 65 now we know that 65 is in the array and we want to search it using the binary search so what we can do is so the first step what we do is we create an integer variable by name low and we assign a value of zero to it so here you can see low is having value of zero so here it means that we are pointing at the first element of an array at the index zero moving ahead and then we create an integer variable by name high and we assign it a value of say numbers do length minus one so here what we are actually doing in the first step we created a integer variable low and we are pointing it to the first index and then we are creating an integer variable High which will point to the last index of an array which is eight so here if you see there are total nine elements in an array and when we do numbers. length we get nine and when we do minus one we get the 8 so it just means that high is having value as eight and it is pointing to the last element of an array so friend as the array is sorted and we are applying binary search over it so we are using this while loop and inside this while loop in each iteration we will divide the array into two halves and we will search for the key 65 so the condition we are placing in the while loop is we will iterate till low is less than equal to high So currently you can see low is pointing to the zeroth index and high is pointing to the e8th index therefore low is less than high so the condition in V block comes out to be true Pro so in the first step what we are actually doing is we are actually finding the middle element of the N array so in order to find the middle element the formula we are using here is we are doing High plus low and we are dividing it by two So currently high is having a value as eight and low is having a value of 0 so when we will do 8 + 0 by 2 we get mids is 4 so here mid will point to the index 4 which is nothing but the middle element of this array moving ahead so friends here you can see as mid is pointing to the middle element of an array we know that array is divided into two parts from low to middle and from middle to high so first we'll check whether the value at Mid position is equal to key or not so if the element is equal to key then we have found our key and we'll simply return the value of index So currently you can see the value at made is 59 and if you compare it with the key then 59 is not equal to 65 therefore the condition in if block comes out to be false and then we will check that whether key 65 is less than 59 or not so here you can see 65 is not less than 59 therefore the condition in if blog comes out to be false and the else block will be executed so friends here you can see as array sorted and we have identified that key 65 is greater than the middle value therefore we know that 65 would be somewhere in the last half so now we can ignore the first half and we can directly search into the last St so this is how this algorithm works we actually divide the using this middle element and we compare it with the middle value and if the value is greater than the middle value we search in the last half and if it is less than the middle value then we search in the first half so now the overhead of searching in first off is gone and we can directly perform our search in the last half so what here actually we do is currently low was pointing to the zero index and now we know that that our key will be lying between the index 4 and 8 so therefore to the low we are assigning the value as mid + 1 so it would look something like this that now low will be having value as five and it will point to the fifth index moving ahead now in while we will check whether low is less than equal to high or Not So currently low is having value as five and high is having value as 8 therefore five is less than 8 so the condition in while block comes out to be true so now in the first step we'll again find the middle index so we apply the formula as high plus low divided by two So currently you can see high is8 and low is five so when we do 8 + 5 we get 13 and when we divide it by two we get 6.5 and when we take it as integer variable the value is rounded off to six so now mid will hold the value as six so friends here you can see we again divided the RR into two halves using this middle index so in the first step we will check whether the value at Mid is equal to key or Not So currently here you can see the value at Mid which is 75 is not equal to our key which is 65 therefore the condition in if log comes out to be false and then we check whether our key is less than this middle value or not so if key is less than this middle value then we know that we have to search into the first half and if key is greater than the middle value then we know that we have to search in the last St So currently key which is 65 is less than 75 therefore the condition in ifog comes out to be true so friends here we know that s key 65 is less than 75 so therefore it must be lying somewhere between the low index and the middle index which is nothing but the first St so now our high will become midus one because we have to search in the first half so therefore here you can see mid is six so when we do mid minus one high will store the value as five so friends here the key 65 was less than the mid value therefore we knew that it must be lying somewhere between the low index and the middle index so therefore we assigned the value of mid minus one to high so that now we can search in the first half of an array moving ahead we will again check whether low is less than equal to high or Not So currently low is having value as five and high is also having value as five so therefore the condition in while block comes out to be true and we'll again find the middle index by the formula High plus low and then we'll divide it by two so so here you can see high is having value five and low is also having value as five so when we do high plus low we get value as 10 and when we divide it by two we get value as five so now value of five will be assigned to the mid Here and Now mid will point to the fifth index so friends in the if blog we will check that whether the middle value is equal to key or not so here you can see the middle value which is 65 is equal to the key 65 therefore the condition in if log comes out to be true so it means that we have found our key so we can simply return the index position which is nothing but the fifth index and if you don't find any value in an array till low is less than or equal to high then we can come to know that element is not in the array and then we can simply return the index as minus one so friend let's go to eclipse and see the working code so friends here I have created one class by name binary search so inside this class I will be creating the method which can actually perform the binary search so let's create a method as public in so this method will return us back an integer value and I will name it as binary search and this method will take two things one is the integer array which is actually sorted array and another would be the key which we want to search in the sorted array so in the first step what we do is we create an integer variable by name low and we'll assign a value of zero to it which is nothing but the zero index of an array and we'll also create integer variable by name high and we'll assign it a value of last index of an array so we'll simply do nums do length minus one so now high will be pointing to the last index of an array and then we'll provide a while loop and in the while loop we will provide the condition as low should be less than equal to high so we'll iterate in the while loop till low is less than equal to high so in the first step what we do is we actually divide the array and we find the middle index so we'll create an integer variable by name mid and we will assign it a mid value by applying the formula as high plus low divided by 2 so this formula will return us back the middle index of an array after finding the middle index we that we will simply check that value stored at the middle index is equal to our key or not so if the mid value is equal to key then we know that we have found our key and we can simply return the mid index and if suppose the value at middle index is not equal to our key then then we can provide an F El block so in the F blog we'll provide the condition as that if key is not equal to the middle value then it must be less than mid value or greater than mid value so if key is less than the mid value then we know that key lies in the first half of an array so we'll simply assign the value midus one to high and in the else block we'll simply assign mid + 1 value to low because we know that if key is greater than the middle value then we can ignore the first half and we can start searching in the last half so at that time low will become mid + one so in the while if we find our key then we can simply return the mid index and if we didn't find our key then we can simply return minus one which is nothing but the negative index so friend this is the code for binary search now let's test it's working in the main method so here first we have initialized the binary search class and then I have created one sorted array which we discussed in the slide so friend let's search for a key having value of 65 so here I will be providing system.out.print statement and here we will print the index so we'll use this binary search instance and we'll call binary search method and inside this method we'll pass the sorted array and let's say we want to search for the key as 65 so friends here we know that 65 is in the sorted array so if I run the code now you can see it returned five which means that we have found our key at the fifth index so here you can see 0 1 2 3 4 and fifth index so it is actually returning the fifth index where we have actually found our key and let's say if I provide the value as say 100 and we know that 100 is not in this sorted array so if I run the code now so here you can see it return return minus one which is the negative index because it didn't find 100 in this sorted array so it finally returned minus one so friends in this tutorial we discussed about the binary search in Java I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day hello everyone so in this video we are going to discuss search insert position problem so let's see what this problem is and how to solve this so here in this problem we are given a sorted array of distinct integers so the array is sorted and we don't have duplicates we are given a Target value and we need to return an index if the target is found if Target is not found in the array so as the array is sorted then we have to return the index where it would be if it were inserted in order so here this problem is a search and insert problem so we are given with a sorted array which doesn't have duplicates and we are given with a Target value we need to First search the target value in the array and if the target is found we need to return that index and if the target is not found then we need to return that particular index where the target value should lie so for example if you are given an input arrays 1 3 5 7 so this is sorted array in ascending order and the target value is given as five so if I put indexes on top of the number you can see five lies at index two so we return two now let's say if we are given with the same array and Target value is two so two is not found in the array but if you see as the array is sorted and if you would have wanted to place two somewhere in the between so that the array is still sorted you can see it can lie between 0er and one so one is at zero index after that two would have come so two would have come at this place and three would have shifted ahead so two would have come at first index so we would return output as one now let's say if we are given with this input array these are the indexes and Target is eight so here you can see 8 is not found in this array so the probable position for inserting 8 would be after after 7 so this sorted array goes from 0 to 3 third is the last index and we can only insert eight after 7 which is the fourth index so we return the value as four similarly so this was the extreme case where we need to put eight outside the boundaries of the array in this direction now let's say if we are given with this a in Target is zero so here you can see 0 is not found in this array and 0 can only lie before one but before one we have index minus one so this minus1 is not a valid index in an array so our Target would lie at zero index only and the rest of the elements will get shifted in this direction why we not added zero at min-1 index because minus1 index doesn't belong the array should start from zero index so the only place to put Target is at zero index so we return the output as zero and the rest of the elements can shift here but here when the target was 8 though index 4 was not in the array but four is a valid index an array can have a size where index 4 can belong but an array cannot have an index minus one so therefore these two are some of the cases we need to handle and we need to run the algorithm in log of end time because we can directly search in the array in O of end time and we can place the element at that particular index because the array is sorted so we need to use an algorithm which runs in log of end time so let's move ahead and see that so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here this is the algorithm where the method name is search insert it takes in an array and a Target and Returns the index that where this target should belong so here as we need to run the algorithm in log of end time we basically take the help of binary search and try to figure out the proper index for this target now why we are applying this binary searches first the given array is sorted and second we need to find the Target in the array and return that index so one is the search part which we need to do in log of end time so here why the search is in log of end time is because when we try to run the binary search on a sorted array what happens is each time if the value is not found half of the array is discarded because as the array is sorted we keep on discarding the half of the array with every iteration of while loop so we will see that later and if you see the time complexity of binary search it is log of n so we will see that how we can apply the binary search and try to figure out the index for the Target so most of the algorithm is pretty much same as our binary search but there are some things to understand that how we can figure out the index of a Target if it is not found in the array so let's say we call search insert we pass in the array and we pass the value of Target is 66 so Target becomes 66 now our task is to find 66 in this sorted array if we found that index here then we simply return the index of the array where we found the Target and if not then we need to find that particular index where this target would lie so at the start as we need to apply this binary search on complete array we take two pointers low and high low starts from zero index and high starts from the last index which is array. length minus one which is 8 so if we do AR do length we get 9 and if we do minus one we get eight so high starts from eth index so now we apply the binary search and we provide a while loop where the condition we provide is low should be less than equal to high so once low crosses High we need to stop this algorithm So currently value of low is zero and high is eight so this condition comes out to be true so friends how this binary search works you can also watch my videos on binary search but here I will explain that as the array is sort it we don't directly search each and every element of the array because that would take o of n time complexity because we are comparing Target with each and every value and as arrays sorted we can use that property what we can do is we can try to find a mid element and we simply compare that mid element with Target so let's see how so in order to find the mid index we use this formula we do low plus High minus Low by 2 so here in binary search we also do something like low plus High by two but here we are using this type of approach because this formula will actually avoid the integer overflow condition so let's say if you are given with a very huge array which actually touches the boundaries of integer range so if we do the addition of low and high there could be a possibility that the range of integer is overflowing so we will get undesired value and so this part where we are doing low plus high would fail and our binary search will not work properly so therefore what we do is we apply this part where we are doing High minus low so here high would be a very large number and low would be a number which is lesser than high so so when we are doing subtract we are going back into the integers range only and when we are dividing it by two we are going further down and then we can safely add it with low to get the value of mid index so if we do low which is zero plus High which is 8 - 0 2 so 8 by 2 will give 4 which would be our mid index so mid value would be four this now the significance of taking the mid index is we directly see what value is at Mid so here it is 59 we check whether it is equal to our Target or not so here you can see 59 is not equal to 66 which is our Target so therefore this if condition comes out to be false and then we check whether Target is less than the value at Mid index so here 69 is not less than 59 so this condition also comes out to be false so here you can see the basic idea is after calculating mid we take the value at Mid index and there could be three possibilities that this value is equal to Target this value is less than Target or this value is greater than Target so here we know that the array is sorted so if Target is less than array of mid and as array is sorted we know that the target might lie in this range and here Target is greater than area of mid here you can see 66 is greater than 59 so we are sure that 66 might lie in this range because the array sorted 66 can't lie in this direction because array sorted all the number numbers before 59 will be lesser than 59 and all the numbers in this direction will be greater than 59 so our chances that 66 might lie in this direction so therefore what we do is as 66 is greater than 59 we know that it might lie in this direction so here in binary search we can safely discard this much array because with this comparison we are sure that Target will never lie in this indexes it can only be found in this indexes because it is actually greater than the mid value so therefore we bring this low to this point because if are of mid is not equal to Target we then perform our search from fifth to e8th index so high will be at the same position we bring low to this direction so what we do is the new value of low would be mid + 1 so mid is four and if we do plus one we reach fifth index so low becomes five it will point to fifth index so now our search will continue from index 5 to 8 and we will discard this much array so at every step when we evaluate mid and perform this check after that we actually discard half of the array so therefore this algorithm runs in log of end time because at every step we are discarding half of array because the possibility of Target could be either in this direction of mid or in this direction of mid if it is not equal to Mid so therefore the algorithm runs in log of end time moving ahead now we are trying to se 66 in this range so low is less than equal to high we first evaluate the mid index so low would be five plus high would be 8 - 5 by 2 so this will give 3x 2 and this would give one so mid will be sixth index like this so it will point to the sixth index so friends if array of mid here it is 75 if it would have been 66 then we would have found our Target and problem states that if we are finding our Target then we should return the index of that spot where the target belongs but here you can see that array of mid is 75 it is not equal to our Target which is 66 so therefore this condition comes out to be false and now we check whether Target is less than the value at Mid index so if we compare 66 we get it is less than 75 which is our value at Mid index which is 75 so this condition comes out to be true so here as the array is sorted and 66 is less than 75 we know that it must lie somewhere in this direction if 66 would have been greater than 75 we would have discarded this part and we would have searched in this part but as 66 is less than 75 now we can safely discard this part so how we can discard this part is as high is pointing to8 now in the next search high should go from mid minus one so therefore we assign mid minus one to high so high becomes five which is at fifth index and here you can see by doing this we have discarded half of the array and now we are searching in this part moving ahead low is actually equal to high so therefore this condition in while loop comes out to be true so first we will evaluate the mid index so low and high both are pointing to fifth index so five + 5 - 5 by 2 and the answer would be 5 so mid will become five which will point to the fifth index like this now first we check whether value in the array at Mid index whether it is equal to Target or not so 65 is not equal to 66 so therefore this condition comes out to be false and then we check whether Target is less than the value of array at Mid index or not so our Target is 66 and the value of array at Mid index is 65 so therefore 66 is greater than 65 so this condition comes out to be false so it means the new value of low would be mid + 1 because this value is less than Target so we need to search in this direction so the new value of low will become mid + 1 which which is six because value of mid is five so low will point to the sixth index [Music] now so friend now here you can see value of low is greater than high high is at fifth index and low is at sixth index so therefore this value will terminate and here you can see that one critical step is if we have found the target we simply return return the mid index but if we haven't found a Target and the binary search ends here at whatever index low will be that will be our actual index to insert the target so here 66 was greater than 65 and as there are distant integers the probable index for inserting 66 would be this which is being pointed by low and then rest of the elements can shift ahead so we simply return return the index that it is the value which is being assigned to low when the binary search ends so why we are only returning low but not high so we'll see it by an example so for this this step is very important that we always return the index value of low and that would be our actual value where this target might lie so now we will see that why we are actually only returning low and not high so friend let's say if we are given with only one element let's say the value would have been four it would have been at zero to index and let's say the target value would have been five so we know that answer would have been one because at zero we have four so five will lie at index one so at the start low will point to zero and high will also point to zero because array do length is 1 1 - 1 will give zero and low is actually equal to high so this condition is true the mid would have been 0 + 0 - 0 by 2 which is 0 so this would have been our mid this condition would have been false because 4 is not equal to 5 so Target which is five is not less than 4 so this condition would have been false so here you can see C then the lse part would have been executed it must lie in this direction so therefore we do low equal to Mid + 1 so when we do mid + 1 low becomes 1 which is at first index so therefore after this statement in the while loop low value is one and high value is zero so this Val will terminate and we know that we have to return one because five will lie after four so this is the one case so let's say now our Target is three so we know that three will lie before 4 here somewhere but here you can see index of four is already zero and three can't lie in minus one index because this index is not an array so our answer would have been zero only because three will lie here and four will shift ahead so here low is and high is at zero index low is equal to high so this condition is true the mid would be 0 + 0 - 0 by 2 which is 0 so mid comes at zero index only the value at Mid index which is four is not not equal to Target because 4 is greater than Target so here you can see Target is actually less than array of mid 3 is less than 4 so therefore this condition would have been true now and high would have become mid minus one so it means as the array sorted three must line in this direction so therefore high will become mid minus 1 so mid is zero and if we do minus one high will reach at a value minus one so in the next iteration of while loop this condition comes out to be false because value of high is less than low because low is referring to zero index and high is referring to minus one this condition would have been false and here you can see at the end we are actually returning the value of low which is our answer that three will lie at Z zero index only so therefore we need to keep a note that low will be the answer that where this target might lie if it is not found in the sorted array and this is pretty much similar to the binary search algorithm but this step is very critical to understand so friend this was all about the search insert problem I hope you must have like this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so friend in this section of course we will be discussing about various sorting algorithms and in this lecture we'll discuss what is bubbl sord algorithm so we will be looking into the demonstration of bubble sord algorithm and later we'll look into its implementation so here what is bubble sort so if you see bubble sort is also called as syncing sort now what do we mean by syncing sort so here let's say we are given an unsorted array which has some random numbers and if you apply the algorithm on those random numbers so usually the algorithm Works in various iterations and with each iteration the largest element tends to sync at the end of the array and when they SN to the end of the array they are usually placed at the correct position and after every element is placed at its particular position at the end we get a sorted array so how does this algorithm work is as we are given few numbers which are unsorted so usually this algorithm it repeatedly compares the pair of adjacent elements and swap them if they are in wrong order so when the few numbers are given which are unsorted we start with the first two numbers and we compare them to check whether they are in correct or wrong order and if they are in wrong order we simply swp them and then we move to the next two numbers so let's look into an example where we are given an unsorted array so here inside this array there are six numbers which are unsorted and now let's say we want to sort them in ascending order so now what do we do is we compare the adjacent elements repeatedly so in the first pass We compare the first two numbers and as we want to sort this array in ascending order we simply compare that the number on the left is greater than the number on the right or not so if the number on the left is greater than the number on the right then we know that they are in wrong order so here 3 is greater than 1 so we know that they are in wrong order so what do we do is we perform a swap so after performing the swap between these two numbers one comes to the left and three goes to the right and after performing the swap we simply move to the next adjacent elements we compare three with five and three is less than five so therefore they are in correct order so we perform no Swap and then we simply move ahead with the next two numbers now here you can see 5 is greater than 2 so therefore they are in wrong order so we perform a swap and after we perform swap two goes to the left and five goes to the right and then we move to compare the next two adjacent elements here we see 5 is less than six so therefore they are in correct order so we do no Swap and at the last 6 is greater than four so therefore we perform a swap because they are in wrong order so four goes to the left and six goes to the right so after the first pass completes you can see that six which is the largest element among the array tends to syn at the end of the array and here you can see being the largest element six is actually at its correct position so now with the first pass the first number got its correct position now we again perform the steps with the second pass but this time as 6 is at its correct position we don't include six in our comparison so now our new array is from index 0 to 4 so initially it was from 0 to 5 as we got one of the number correctly sorted for the second pass our array becomes from 0 to 4 so we start comparing the first two elements Now 1 is less than three therefore we perform no swap now three is greater than two so it means they are in wrong order so we simply perform swap here so two goes to the left and three goes to the Right Moving ahead we compare three with five 3 is less than five therefore no spping is done and then we compare five with four so five is greater than four therefore we perform a swap because they are in wrong order so four goes to the left and five goes to the right and as we don't include this element after completion of the second pass you can see the second largest element among this list which is five is correctly placed at the second last position just before the six so friend here you can see that this algorithm tends to make the largest element sync at the end of the array so similarly this algorithm continues but here you can see the numbers are now in 1 2 3 4 so by looking at the array the numbers are already sorted but there is no way for the algorithm to know that the numbers are sorted because the algorithm has to make the comparisons so in order to make the algorithm know that the array sorted what we do is we simply keep the track of the swipping so let's see how we can do it in the third pass so we compare the first two elements 1 is less than two so therefore they are in correct order so no spping is done so here we perform no Swap 2 is less than three so therefore there is no swap 3 is less than four so therefore there is no swap so friends here you can see in the third pass we didn't perform any swap so at the end of the third pass we simply check that whether we had performed any swap or not so if we haven't performed any swap we can come to know that a is already sorted so friend usually with each iteration or with each pass we simply keep the track of swapping and if in any particular pass no swipping is done then we can directly come to know that the array is already sorted and we simply break from the algorithm so friends this is the demonstration of the bubble sort algorithm in our next lecture we'll see the demonstration of the code through animation and then we'll write the implementation of it in eclipse and see it's working I hope you like this video thanks have a nice day hello everyone so in our previous lecture we discussed about what is bubble sort and we saw its demonstration with an example so in this lecture we'll see the demonstration of the code using an animation so here let's say we are given an unsorted array having five elements as 5 1 9 2 10 now we want to sort this array in ascending order by applying the bubble s algorithm so here you can see that this is the bubble sord algorithm so friends in our previous lecture we saw the demonstration of the algorithm where we discussed that we start comparing the adjacent elements and if they are in wrong order we simply swp them and usually when we complete one particular iteration the largest element tend to sink at the bottom of the array or at the end of the array and we also discussed that with each iteration we keep the track of the swapping and if no swap is done in any particular iteration we simply come to know that the array is already sorted so let's see the demonstration of this algorithm step by step so here the number of elements are five with an index from 0 to 4 so at the first step what we do is we simply create a Boolean variable we give it a name as is swapped now this Boolean variable will keep the track of the swapping in each iteration that whether the Swip is done or not so here you can see at the last step what we simply check that if the swap is not done then we come to know that the error is already sorted so we simply break from this algorithm so we'll see its usage inside this algorithm so here we have created the Boolean variable is swept so here you can see there are two for Loops one is the outer for Loop and other is the inner for Loop so usually the outer for Loop basically keep the track of each and every iteration and the inner for Loop will simply help us in performing the comparison with the adjacent elements so let's see the usage of these two for Loops so with the outer for Loop we start with i equal to Z and this for Loop will Loop till I is less than n minus 1 so here you can see 5 - 1 which gives 4 so this for Lo will travel four times as it is starting from zero it will go from 0 1 2 3 so with total four iterations so usually this outer follow what it tracks is here you can see the there are five numbers and we also discussed that with each iteration the largest element tend to go to its correct position by sinking at the end of the array and once it sinks to the end of the array we simply don't include that element in the next iteration so here as the outer follow will Traverse four times with each time we get a number sorted at its correct place so here there are five numbers so with four iterations we will get the four numbers sorted correctly at their position and as the fifth number is only number left it will be already sorted to its correct position so therefore we iterate this for loop from 0 to less than n minus 1 So currently value of I is 0 and it is less than 4 which is n minus 1 so the condition in for Loop comes out to be true and as you want to track that whether any swap has been performed with each and every iteration with this iteration we start with is SED as false and moving ahead now we encounter the inner for Loop which simply compares the adjacent elements and perform the swap so here you can see the inner for Loop starts from J equal to0 and here it goes till J is less than nus 1 minus I now here you can see that the outer for Loop is controlling the inner for Loop now why we are doing it is because with each iteration the largest element will sync to the end of the array and once those elements are sinking to the end of the array we don't have to include those elements so as the outer for Loop is incrementing one by one the J Will Traverse only to those positions which are still unsorted so let's see it VI demonstration So currently J is less than 5 - 1- 0 because I is 0 so the condition in for Loop comes out to be true and for Loop executes and here inside this for Loop we are simply providing an if block where we are simply comparing the adjacent elements J and J + 1 and as we are sorting this in ascending order we are simply checking that the value at jth index is greater than value at j+ 1 index or not so it means we are simply comparing these two elements now here you can see 5 is greater than 1 so therefore they are in wrong order so we simply perform a swap so here the condition in if loock comes out to be true and here inside the if block we are performing the swap so usually how we perform a Swip is we create a temporary variable and we store one of of the values inside the temporary variable so here we are storing the value at jth index to the temporary variable because in the next step we'll override this value and we actually need this value in the later computation so as we want to swap these two elements now we are taking the value at j+ 1 index and we are assigning it to the index so it becomes one and at the last step as we have stored this value into the temporary variable five we simply assign the temp to the array at the j+ 1th index so here you can see we have solved both the numbers using the temporary variable and then we we Mark is swap variable with a value true because we have performed one swap in this iteration so it becomes true moving ahead now we'll increment J by 1 so J becomes 1 and 1 is less than 5 - 1 - 0 which is 4 so the condition in for Loop comes out to be true and here as J is 1 so it will simply point to the first index and j+ will point to the second index because now we want to compare these two elements and here is 5 is less than 9 therefore they are in correct order so we perform no swap as the condition in if log comes out to be false there is no swapping we'll increment J by 1 so J becomes 2 and 2 is less than 4 so the for Loop executes now the value of J is two therefore now we'll compare 9 with 2 so here you can see as 9 is greater than two therefore they are in wrong order so here we need a swap so the condition in IFL comes out to be true because 9 is greater than 2 so now we'll simply swap using the temporary variable which we saw in our previous steps so we store 9 in the temporary variable then we store two at the place of nine and then we store the value stored in a temporary variable at the third index on the place of two so here we have simply performed a swap between these two elements and we assign value true to it swep variable which is already true we'll increment J by 1 so J becomes three and 3 is less than 4 now we are simply comparing the jth index with j+ 1/ index which is the third index with fourth index comparing 9 with 10 so here you can see 9 is less than 10 so therefore no swapping is done and the condition in if loog comes out to be false so we simply skip this part we'll increment J by 1 so J becomes four so now here you can see value of J is four and four is not less than four therefore the condition in for Loop comes out to be false and this for Loop exits and just after the for Loop we have completed our one iteration completely so we simply check that whether in this iteration We performed any swap or not because if we haven't performed any swap in this iteration then the algorithm comes to know that the AR is already sorted but here you can see the value of is SW is true so therefore this if condition comes out to be false so friends here you can see the outer for Loop has performed its one iteration completely with the value of I equal to Z so after the first iteration of the for Loop you can see the largest element which is the 10 has basically sync to the end of the array and here now you can see 10 being the largest element is at its correct position so now we'll increment I by 1 and 1 is less than 4 therefore the condition in for Loop comes out to be true so friend now next PATH starts so we simply assign the value false to the SW variable and now the second path starts so we start comparing it from the first two elements with J equal to Z so friend here you can see the value of I is 1 and value of I is basically controlling the inner for Loop and why it is controlling because with the first iteration we have found our one element which is sorted and it is at its correct position so therefore when we are starting our next pass we don't want to include this element so our arrays now become from zero to the third index so therefore we are subtracting one from this this condition because value of I is 1 so it means the inner for Loop will simply compare these elements from 0 1 2 3 and it will not touch the fourth element using this condition So currently you can see J is Zer and J is less than 5 - 1 which is 4 Min - 1 which is 3 so 0 is less than 3 and we simply perform the comparison what we did in our previous steps we compare the value at jth and J plus 1 index so here as one is less than five therefore they are in correct order so no swap is done and the condition in if log comes out to be false now we'll increment J by 1 so J becomes 1 1 is less than 3 now we simply compare the elements at index 1 and two because value of J is 1 here 5 is greater than two so therefore they are in wrong order so we simply perform a swap because condition in if block comes out to be true so we simply store five into the temporary variable and then we migrate this value which is stored at the j+ 1th index we simply assign it to the J index so it becomes two using this step and at the last we simply assign the value stored the temporary variable to array at j+ 1 index so it becomes five so we have performed a swap here so as we have performed the swap we simply assign the value true to is SWA variable will increment J by 1 so J becomes 2 2 is less than 3 now we compare the second index with the third index using array of J and area of J + 1 so 5 is less than 9 therefore they are in correct order so no swp is done we'll increment J by 1 so J becomes 3 now here you can see three is not less than three therefore the condition in for Loop comes out to be false and for Loop exits and here we simply check whether it SW is equal to false or not but here s swap is true because we had perform one swap here so therefore the condition in if loog comes out to be false and friends here you can see with the completion of the second iteration of the outer for Loop the second largest element which is nine is at its correct position which is the second last position so your bubble sord makes the largest element tend to sing at the end of the array the second largest element tend to sing at the second last position and similarly it goes on like this so now we'll again execute for loop with I equal to 2 by incrementing the value of I so I becomes 2 2 is less than 4 we assign false to a swep variable because with this inner form we are starting our new iteration so here you can see as these two elements are basically sorted so we are using the value of I which is two to control the inner for Loop in this condition here so J is starting from zero and it will go till which is 5 - 1 which gives 4 - 2 which gives 2 so 0 is less than two so now we'll again start comparing these two elements and as 1 is less than two therefore they are at correct order so no swapping is done and also friend here you can see the importance of this Boolean variable because if you see the array is already sorted but the algorithm doesn't knows this so here when the J was equal to zero we didn't perform any Swap and it swep value remained false now we'll increment J by 1 so J becomes 1 1 is less than 2 so we simply compare the elements at the index one and two so 2 is less than 5 therefore they are in correct order so no swiping is done so this bullan variable Still Remains false we'll increment J by 1 so J becomes two and here you can see 2 is not less than two so therefore this for Loop will terminate because the condition in for Loop comes out to be false and friends here you can see at the last step we are simply comp comparing that whether is SW is false or not so here is s value is false which tells us that a is already sorted and we don't want to continue this algorithm further because we were keeping the track of the sing so in this step the condition in if blog comes out to be true and we simply break this for Loop so friends here we saw the demonstration of of the bubble short algorithm so our next lecture we'll see the demonstration of this algorithm in Eclipse I hope you like this video thanks have a nice day hello everyone so friend this lecture we'll code the bubble s algorithm and we'll simply test it's working so in Eclipse I have created one class as bubble sort and inside that I have created one method print array so this method will simply take the array and will simply print its content on the console so we have already discussed this algorithm in our previous lectures when we discussed about the arrays so I'll be using this print array method to Simply demonstrate that whether our array is sorted or not so inside this class I have provided a main method where I have created an unsorted array which we already discussed in our previous slide and at the first step what we are doing is we are simply calling the print array method and providing this array to Simply see the contents of this array before performing the sort so here you can see the array is not sorted so let's write an algorithm to sort this array so in this lecture we'll see about the bubble sort algorithm so we'll create a method as public void we'll give it a name as sort and to this sort method we'll pass the integer array which is the unsorted array so so for inside this method the first step we do is we simply calculate the value of n which is the number of elements inside this array so we simply do array. length and as per the algorithm which we discussed in our previous lecture we'll first create a Boolean variable is swed so we have created this variable to keep the track that in any particular iteration we performed any swap or not so if you have performed any swap then we are unsure that array is sorted or not also in any of the iteration if we haven't performed any swap then we can come to know that the array is already sorted moving ahead we first provide a for Loop which starts from zero and goes till n minus one and also friend we discussed that value of I will basically control the inner for Loop because as we are comparing the adjacent elements we need to stop at a point where we don't want to compare further so here with the start of any iteration we simply provide a value false to a swa variable and now we'll provide the inner for Loop where J will start from zero and J Will Traverse till n -1 - i j ++ so friends we already discussed that why we are providing this condition here is because we need to control the inner for Loop by the outer for Loop value which is the I so we are simply providing I here now inside this inner for loop our basic comparison will start so we'll simply start with comparing the adjacent elements that if the value of index J if it is greater than value at index J + 1 then we know that they are in wrong order so we simply perform a swap so inside the if Block in order to perform swap we create a temporary variable and we simply store the value at the jth index so that we can use this value to perform the proper swap so after we take out the value at the jth index what we do is now we can simply store the value at j+ 1 index to the J index because we need to perform a swap and the final step we simply store the value present in the temporary variable to the array at j+ 1et index so in this three steps we are simply performing the swap of the values present in the jth and the j+ 1 index because they are in wrong order as value at the J index is greater than value at j+ 1 index so after we perform swap we simply assign a value true to a swab variable to keep the track that inside this for Loop when we compar the adjacent elements we did perform a swap so after every iteration here what we do is we simply check that whether we performed any swap or not so if we didn't perform the swap we know that array is already sorted because all the Adent elements are at its correct position so we simply break from this algorithm and if we had performed any swap then the value would have been true so we are unsure till this point that whether array is sorted or not but if the value it hold is false then we are sure that array is already sorted so friend this is the bubble sort algorithm which we already discussed in our previous lecture and in this lecture we have simply provided the code for it so now let's test it's working so here what we do is we simply call the sort method we provide the array and after we have performed the Sorting we simply print the array again so if I run the code now so friend here you can see initially the AR aray was 512 9 10 which is the content of array before sorting and then we performed the sort on this array and after performing the sort we simply printed the array again and we found that array sorted with the all elements to its correct position 1 2 5 9 10 so the array sorted in ascending order in this tutorial we saw the demonstration of the bubbl algorithm we tested its working in the main method so friends I hope you like this video thanks have a nice day hello everyone so friends in our previous lecture we discussed about the bubble s algorithm so in this lecture we will discuss about the insertion s algorithm so let's discuss this algorithm in detail so here if you see insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands so when we play with the deck of cards usually most of the games are involved where we keep few cards in our hand and what we generally do is we keep them in proper order so how do we manage to keep them in proper order is we use the insertion sort algorithm so let's say we have this deck of cards which is lying in front of us and let's say we pick few random cards from the top of the deck so usually what we do is when we pick up the first card we simply keep it in our hand because it is already sorted and when we pick the second card the card which we have picked we simply compare it with the card which we have in our hand and based on the comparison we either keep that card before or after the first card the deck of cards which is lying in front of us are basically in random order or you can say they are basically unsorted form and the cards which we have in our hand are basically kept in sorted form so when we pick up up the third card from the random cards now the card which you have picked we simply compare it with the cards which we have in our hand so we compare the third card with second and then with the first card and based on the order which we are following we simply place the third card either after the second card or in between first and second card or just before the first card so similar let's say we have this unsorted array so using the insertion sort algorithm we divide the given array into two parts one is the sorted part and the other is unsorted part so how the algorithm works is from the unsorted part we take the first element and place at its correct position in the sorted array so here we are simply picking one element from the unsorted array and based on some logic we are simply putting that element into the sorted array at its correct position so this is done by shifting all the elements which are larger than the first element by one position so here let's say we are sorting the array in ascending order so the first element which we pick from the unsorted part we simply compare the element with each and every element in the sorted array and all the elements which are larger than the first element we simply shift them by one position and as soon as we encounter any element which is smaller than the first element we simply store this first element just after that and this process is repeated till unsorted array is not empty so friend let's see the demonstration of insertion sort algorithm with an example we'll take an unsorted array we apply the algorithm mentioned here and we'll see that how we can sort the array so friends here you can see that we have this array from index 0 to 5 so basically there are six elements with the value as 3 1 5 2 6 4 now let's say we want to sort this array in ascending order so how do we start this algorithm is we simply pick the first element so so here it is three and as we have picked the element three we know that there is only one element so it's already sorted so basically this algorithm starts from the second element because the first element is already sorted so friends in our previous slide we discussed that we divide the array in two parts one is the sorted part and other is the unsorted part so when we start our algorithm from the second element so the elements to the left are basically sorted and the elements to the right are basically unsorted so now what we do is from the unsorted part we simply pick the first element which is one and what do we do is we simply store this element let's say to a temporary variable so as soon as we store this element to a temporary variable what do we do is we simply provide a whole here that this part is empty so after providing this empty space What do we do is we simply compare one with the element in the sorted array now as we are sorting this array in ascending order we simply compare that whether one is less than three or not so here 1 is less than three so therefore one should come before three here you can see there is no space so what do we do is as we discuss in the previous slide we simply shift the elements which are larger than one by one position so here we'll simply shift three to this empty space so after we perform this shift that are there any other elements in the sorted array or not so here you can see there was only one element three there are no other elements so we simply Place one at its correct position so after placing one at its correct position you can see that now our sorted array has two elements one and three in sorted form so now we simply pick the first element from the unsorted array so we simply pick five we store it into a temporary variable and we create an empty space here now what do we do is we compare five with three and we know that three is smaller than five therefore five has to be placed after three which is is this spot only so there is no shift because the element to which we are comparing in the sorted array is already small from the element which we picked from the unsorted array so the position of five will not change five will be stored at its own position and here you can see that as three was less than five we didn't compare 1 with five because as this is a sorted array one will be by default smaller than five so after placing five at index two now our sorted arrays three elements 1 3 5 and from the unsorted array we simply pick the first element which is two we store this two into a temporary variable and and we create an empty space here now what we do is we compare two with five so 2 is less than five so we know that two must be Ling somewhere before five but here you can see in sorted array there is no space left so what do we do is we simply shift the larger element by one position and as here is the empty space we can simply shift it here so fire comes here and the empty space comes here so friends here we are not sure that whether this is the correct position of two or not so what do we do is we simply compare two with this element which is three so here you can see three is also greater than two so we know that two must be L somewhere before three so what do we do is we simply shift 3 by a position and as here is a empty space three comes here and the empty space goes here so friend we are still not sure whether two must be placed here or not so we simply compare two with one and here you can see that one is smaller than two so therefore we are sure that two must be lying after one and the position after one is empty so we simply store two at this empty position so friends after this step now we have four sorted elements and two unsorted elements so we simply pick the first element from the unsorted part which is six we store six in the temporary variable we create a empty space here and we compare six with five so as 6 is greater than five we know that it must be lying after five so after five we have this empty space so six will be stored at its own position so now our sorted part is five elements 1 2 3 5 and six which are sorted and in our unsorted part we have now only one element left so we simply pick the first element which is four we store it into a temporary variable and we create an empty space here now we compare four with six so four is smaller than six so it must be lying before 6 but there is no space left here so we simply shift 6x1 position here so six comes here and we have empty spot here so now we are not sure whether we simply put four here or not so we simply compare four with the element just before the empty spot which is five so that we are sure that whether four can be placed here or not so as 5 is greater than four therefore we know that four must be lying before this element but here there is no space so we simply shift 5x1 position to this empty spot and the empty spot reaches here now we are still not sure whether we need to place four here or not so we simply compare four with three now as four is greater than three we know that it must be lying after three and here you can see after three we have this empty space so we simply store four to this empty space so when after this step you can see the complete array is sorted so here we saw the insertion sort technique where we divided the array into two parts one was the sorted part and another was the unsorted part and with each step we simply picked the first element of the unsorted part and we simply placed it into its correct position in the sorted part and this we did till the complete array was sorted so friend in this lecture we saw the basic demonstration of insertion short technique in in our next lecture we'll see the working of the code step by step using an animation I hope you like this video thanks have a nice day hello everyone so friends in our previous lecture we discussed about the insertion sort and we saw the demonstration of the Sorting algorithm now in this lecture we will see the demonstration of insertion sort algorithm step by step so friends here you can see that this is the algorithm to perform insertion sort so let's say we are given an array having five elements which contains values as 5 1 9 2 10 so here you can see the values are in unsorted form so let's see the demonstration of this algorithm step by step to sort this array in ascending order so here the number of elements inside this array r five which are ranging from index 0 to 4 so friends while performing the insertion sort the first thing we encounter is the for Loop so here you can see this for Loop goes from I equal to 1 and it goes till I is less than n so friends in our previous lecture we discussed that when we perform insertion sort we usually divide the array into two parts one is the sorted part and the other is unsorted part so here you can see that when we start sorting this array all the elements are in unsorted part and no element is in sorted part so what we do is we simply pick one element which is the first element of the unsorted part so let's say we pick five and as soon as we pick five as five is the only element which we want to sort therefore we directly Place five to the sorted part because we don't have to compare five with any element so instead of doing this stuff we directly start from I equal to 1 which is this position because five is already sorted into its correct position so so usually this algorithm starts from I equal to 1 so here you can see that five is in sorted part and all other elements are in unsorted part so we always start from I equal to 1 and as I having value as 1 is less than 5 therefore the condition in for Loop comes out to be true so friends here when we perform insertion sort one rule of thumb is we always pick the first element of the unsorted part and we try to put it in sorted part by comparing one with all the elements in the sorted part and placing it into its correct position so when we perform this comparison in the sorted part all the elements which are larger than this first element we simply shift them by one position so that there is an empty space where we can simply put this element so here you can see the space are already occupied with some numbers so when we perform a shift there can be a chance that some numbers can be overridden so what we do is we simply store this value which we want to compare with the elements in the sorted part we simply store it into a temporary variable here moving ahead so friend now we want to compare this element with the elements present in the sorted part so here you can see as we have picked the first element of the unsorted part if we go one position back we'll get the elements of the sorted part so we simply do IUS one and to access the elements of the sorted part we simply store it in the J variable so here J becomes zero so usually the elements of the unsorted part are accessed via I and the elements of the sorted part are accessed via J so friends now we provide a while loop because we want to compare this element with each and every element in the sorted part and all the Elements which are greater than this element we simply shift it by one position so that there can be a space where we can simply put this element and as we are sorting this in ascending order so here the condition we provide in while loop is that J should be greater than equal to zero because inside this while loop we are decrementing J by 1 so we have to provide this condition that J should be greater than equal to zero because we don't want to go outside of this array and also why we are decrementing J by 1 is we need to compare this element with each and every element in the sorted part so that we can put this element into its correct position so the first condition is J should be greater than equal to zero so here J is equal to Z therefore this condition comes out to be true and then we provide one more condition as the element at jth index is greater than temp or not so here you can see the value of J is zero so the elemented index 0 is 5 and here you can see 5 is greater than 1 so we know that as we are sorting this array in ascending order one should be placed before five so therefore this condition in while loop comes out to be true and we want to find out the correct position of one so what do we do is in the first step as 5 is greater than 1 and as we discussed in our previous slide that all the elements which are greater than one we have to shift by one position so how we perform shift is as we have already stored one into this temporary variable therefore it's like a a hole here and we can shift five here so we simply assign the value stored at J index which is five two value at J + 1 at the index so J is zero and J + 1 is one so we are simply storing five to this place so here now five has been shifted to this position and after this shift we simply decrement J by 1 because now we want to compare one with the element just before five so we simply decrement J by 1 so as J is zero J becomes minus1 so here it means that now J is pointing to minus1 which is an index which is out of this array so friend as here you can see that in our sorted part there was only one element five so we compared that element with one and there are no more elements to compare so therefore this condition where J is greater than equal to Z comes out to be false because J is equal to minus1 so the condition in while loop comes out to be false and while loop exits and at the end we have found a position where we need to store one so that position is J + 1 because as J is pointing to minus1 so it means J Travel till minus one position to basically shift the largest Elements by one position so when we do J + 1 here we are simply storing the value one at index zero because as J is minus one J + 1 becomes zero so we are simply storing one at zero index so friend after performing this all steps now here you can see that 1 and five are basically two elements which are sorted so therefore with each for Loop iteration we will get one element which will be now part of the sorted array so here now 1 and five are part of sorted array and rest of the elements are part of unsorted array so here now we'll increment I by 1 so I becomes two so friends as we already discussed that we simply pick the first element of the unsorted part in order to make this element to be placed in its correct position in the sorted array so we simply start with storing the value at I index into a temporary variable and why we are storing into this temporary variable is because we want to create a whole here so moving ahead now in order to access the sorted array we simply do IUS 1 so the value of J is 1 and while loop we simply check whether J is greater than or equal to zero or not so J is greater than zero so this condition comes out to be true and then we simply check that the value stored at J index is greater than temp or not so here you can see value of J is 1 so the value at first index is five and 5 is not greater than 9 so therefore this condition comes out to be false and the while exits so here you can see that as we are sorting this array in ascending order we want a correct position for nine in the sorted array so as there are only two elements which are sorted 1 and five when we compared 9 with five we found that 5 was not greater than 9 so therefore the current position of 9 would be after five so here this V Loop exits and at the end we simply store the value 9 in the array at J + 1 at index so value of J is 1 when we do+ one we get two so we simply store the value 9 as index 2 so now here you can see the three elements 1 5 9 are properly sorted so therefore 9 will be now part of this sorted array we increment I by 1 I becomes three and now we simply pick the first element of the unsorted array so we simply store the value two into a temporary variable because now we want to place this two into its correct position in the sorted array so when we'll perform these steps we need to shift some of the elements by one position so that we can place two to its correct position so when we we will shift this Elements by one position we need to create a space here so what do we do is we simply store this value somewhere into the temporary variable because we need to refer this while comparing it with the elements in the sorted array so in order to access the sorted array we simply do IUS one so J will keep the track of the sorted array so now we'll perform the comparison we'll see that J is greater than or equal to Z so value of J is two therefore this condition is true so now we'll compare this two stored in this temporary variable with the element stored at jth index which is N9 so here you can see 9 is greater than 2 therefore the condition in y Loop comes out to be true and as 9 is greater than 2 we know that two must come before 9 so for two coming before 9 we need to create a space here so what do we do is we simply shift this value by one position by storing the value of J index into J + 1 index so J is 2 so this value 9 we are storing in j+ 1/8 index which is the third index so 9 comes here with a shift and as we have already stored this value at temporary variable we can override this part so 9 goes to the third index so now we have compared it with N9 so we simply decrement J by one position because there can be more elements which can be greater than two so J becomes one and as J is greater than zero this condition comes out to be true and the value stored at J index which is five is also greater than 2 therefore the condition in while loop comes out to be true and we simply shift 5 by one position by assigning the value of J index to value of j+ 1 index so we are simply shifting 5x1 position because value of J is 1 so this value we are assigning it to J + 1 which is the second index and then we'll decrement J by one because there can be more elements which can be greater than than 2 so J becomes zero now here as J is greater than or equal to Z this condition comes out to be true but the value stored at jth index which is 1 is not greater than 2 therefore we know that this value two will be stored somewhere after one and as we already shifted five to its correct position this position is actually a space where we can store two so here this condition comes out to be false and at the last step as J is pointing to zero we know that we need to store two after one so we simply store this temp value to j+ 1 index which is the first index so two comes here which is actually two's correct position now after this for Loop ends 1 2 5 9 will become part of the sorted array we simply increment I by 1 so I becomes four and now we simply want to put 10 to its correct position in sorted array so we simply store 10 into this temporary variable moving ahead so now as we want to compare the value sted temporary variable with the elements in sorted array we need to access the sorted array so we simply do I minus one and we store it into J so J becomes three which is the last element of the sorted array so as J is greater than or equal to zero this condition comes out to be true but the value stored at jth index which is 9 is not greater than 10 so therefore this condition comes out to be false and we simply store this value 10 in this array at j+ 1 index because 9 is at its correct position and as it is less than 10 therefore 10 should be stored just after that so we simply store 10 to J + 1 index so friends here you can see that now 10 will also be part of the sorted array and as there are no more elements left to be compared because when we increment I by 1 I becomes five and as five is not less than five therefore the condition in for Loop comes out to be false and this for Loop exits so friends here you can see we have sorted this array into ascending order storing in the form of 1 2 5 9 10 so friend in this lecture we discussed about the insertion s algorithm by demonstrating the algorithm step by step where we actually divided the rror into two parts the sorted part and the unsorted part and with each iteration we picked the first element of the unsorted part and we compare this element with each and every element in the sorted part to place the element into its correct position and how we place the element in its correct position is is by shifting all the larger Elements which was greater than this first element of the unsorted array so friend this is the demonstration of the algorithm step by step now let's go to eclipse and see the implementation of this algorithm and its working I hope like this video thanks have a nice day hello everyone so friends in our previous lecture we saw the demonstration of the insertion s algorithm step by step so in this lecture we'll code the algorithm and we'll test its working so here I have created one class as insertion sort this classes method is print array which simply prints the content contents of this array on the console which we already discussed in our previous lecture so here let's say we want to sort this array having five elements as 5 1 2 9 and 10 so when we'll print these elements on the console let's say if I run the code so here you can see it printed 5 1 2 9 and 10 so here the array you can see is not in sorted form so let's write the code to sort this array using the insertion sort so here I will be creating one method as public void let's say give the name of the method is sort so this method will take the array which we want to sort in the first step what we do is we simply compute the number of elements inside the array by storing the length of the array to the integer variable n and then as we discussed in our previous lecture that we start our algorithm with a for Loop where value of I will be starting from one and not from zero because the first element inside this array when we pick to sort we know that it's already sorted so we simply start from the second element so I starts from one and it goes till I is less than n so friends we also discussed that when we perform insertion sort we usually divide the array into two parts one is the sorted part and the other is unsorted part so here the value which is tracked by I is usually the unsorted part and the value with J TRX which will see later is usually the sorted part so here by providing this for loop with each iteration we simply pick one element and we place that element into its correct position by applying the insertion sort so we simply store the first element of the unsorted part into the temporary variable and after we store this now we simply access the sorted part so here you can see that as I starting from one so the element which is stored at the zero index is already sorted and we can access it via J so now J Will basically keep the track of the Ed part we provide a while loop where we provide two conditions that J should be greater than or equal to zero and as you want to compare the value stored into the temporary variable with each and every element stored in the sorted part we provide another condition as the element stored at the jth index is greater than temp or not so if this is true inside this while loop what we do is we simply shift all the larger Elements which are greater than temp by one position and how do we do it we simply take the value stored at J index and we transfer it it to the j+ 1 index so here we are simply shifting larger elements to Temp by one position and after Shifting the elements we simply decrement the value of J by 1 because inside this while loop we need to compare the temporary variable with each and every value of the sorted part so friend why we are shifting all the larger Elements by one position which are actually larger than values stored into this temporary variable is because we need to find the correct position of the value stored into this temporary variable so after we perform the shift by one position we decrement the value of J by 1 and then we again compare it with the value stored into the temporary variable and this Loop goes on till J is greater than or equal to zero so this is basically a boundary check that we don't go to the out of the boundaries of the array and after this V Loop we simply store the value stored into this temporary variable into its correct position which is at j+ 1 index because here we'll exit the while loop with these two conditions and as we already decremented J by 1 we not that the correct position for the value stored into this temporary variable would be at J Plus one index so friend after this for Loop completes for one iteration our sorted part increases by one value and with each iteration the sorted part increases and the unsorted part decreases and finally when this for Loop exits all the elements of the unsorted part now becomes part of the sorted part so friend this is the insertion s algorithm we discussed this algorithm in Greater detail in our previous lecture and in this lecture we have simply coded this algorithm so now we'll test it's working so here we'll call the sort method we pass in the array and after the sort happens we'll simply print the array again so this print array will be called before sort and this print array will be called after sort so if I run the main method now so here you can see the array is already sorted initially it printed 51 2 9 10 which was the unsorted array and then it printed 1 2 5 9 10 which is the Sorting of the array in ascending order order so friend in this lecture we saw the code for the insertion sort and we tested it working in main method I hope you like this video thanks have a nice day hello everyone so in this video we will discuss about the selection sort algorithm we will first understand what is selection sort and we will see a small demonstration of selection sort algorithm so here as we are performing selection sort we are basically sorting the elements of an array into ascending order so let's say we are given with this array with five elements S 3 1 5 2 6 we know these elements are unsorted and we want to sort them in ascending order using selection sort algorithm so in this algorithm what we do is we first divide this array into two parts one is the sorted part and other is the unsorted part so here you can see at the start all the elements are unsorted so our sorted part and unsorted part looks like this that all the elements currently are unsorted and there are no elements in the sorted part now what we do inside this algorithm is let's say we are given with this boundary what we do is we start with this boundary and we find which is the minimum element among these all the elements in the unsorted part so once we find out which is the minimum element among this elements we simply swap it with the the leftmost element of this boundary and as soon as we swap them we know that the minimum element which we found is at its correct position so for example here you can see when we pick the minimum element and swipe it with the leftmost element of the unsorted part which is this boundary after Swip the element now becomes part of the sorted array so for example among these five elements if we find out which is the minimum element we can find that one is the minimum element so what we do is we see which is the leftmost element which is three here and we simply swp these two values so it would look something like this that these elements are swabbed and we also know that as one was the minimum element among these all the elements one is at its correct position if we actually sort this array completely it simply signifies that now one is the part of the sorted array and this four elements are part of the unsorted array so this finding of minimum element in the unsorted part and swipping it with the leftmost element of the unsorted part is repeated till all the elements are part of the sorted array and there are no elements left in the unsorted part so the idea behind this algorithm is very simple we divide the are into two parts sorted part and unsorted part from the unsorted part we pick the minimum element and we swipe it with the leftmost element of the unsorted part so the element which is next to this boundary we simply swipe the minimum element with this and after we perform this Swip we know that the minimum element which we figured from this array is at its correct position so at the each pass one one element from the unsorted part becomes the element of the sorted part and at the last we only get the sorted part so let's see the demonstration of this algorithm with a small example so let's suppose we are given with this array having six elements index from 0 to 5 and they are unsorted so let's say if you want to sort them in ascending order Here length of this array is six so the first step we do is we divide this array into two parts sorted and unsorted part so initially all the elements are unsorted so therefore the sorted part has no elements and the unsorted part has all the elements now let's see what happens when we perform the first pass so here what we do is we simply start from the unsorted part and we find that there is one Element three so let's say we are assuming that three is the minimum element of this complete array now what we do is we go to its next element and we compare three with one and we check that whether 1 is less than three or not so here 1 is less than three so which means that our assumption is wrong and one will become our new minimum so one becomes our new minimum and simply we go on like this we check whether five is less than minimum so five is not less than minimum we move ahead we check whether two is less than minimum so 2 is not less than one so we move ahead and four is also not less than one six is also not less than one so here you can see after we completed the first pass we found that one is the minimum element among these all the elements so now what we do is we simply swp this one with the leftmost element of the unsorted part so the element next to this boundary we simply swp it with that so here we'll simply swp three and one so one comes here and three comes here and after first pass one is at its correct position so therefore now our sorted part has one element and unsorted part has the rest of the elements now we'll simply do the second pass and we perform the same steps at first we consider three is the minimum element We compare it with each and every element next to it so 5 is not less than three we move ahead so here 2 is less than three so two will become our new minimum we move ahead 6 is not less than two and four is also not less than two so after second pass we found that two is the minimum element among the unsorted part now after we found out that two is the minimum element what we do is we simply Swip it with the leftmost element of the unsorted part so we'll simply Swip it with three so two comes here and three goes here and we also know that two is at its correct position now so therefore now our sorted part is two elements and unsorted part is rest of the elements so we'll go with the third pass now we assume five is the minimum element and we compare with the rest of the elements we check whether 3 is less than 5 so yes 3 is less than 5 so therefore three will become our new minimum we compare whether 6 is less than 3 so it is not so we move ahead we check whether four is less than three so four is not less than three so after the third pass we came to know that three is the minimum element among these elements which are part of the unsorted array so after finding this minimum element we simply swipe it with the leftmost element of the unsorted part so leftmost element is the five so we'll simply sve 3 with five and now our sorted part is three elements and unsorted part is the rest of the elements we'll continue with the fourth pass we'll assume five is the minimum element among the elements in the unsorted part we compare it with the rest of the elements 6 is not less than five so we move ahead 4 is less than 5 so four will become our new minimum so after this pass among this three elements in the unsorted part we came to know that four is the minimum element and we will simply swp it with the leftmost element of the unsorted part so we'll simply swp five and four now our sorted part has four elements and sorted part as rest of the elements so our fifth part will start we assume six is the minimum element and we compare it with the rest of the elements so there is only one element which is five so we check whether five is less than 6 so yes five is less than six so five will become our new minimum and and after the fifth pass we found that among these two elements fif five was the minimum so we'll simply swap five with the leftmost element of the unsorted part so I will come at this place and six will go at this place after the Swap and once we perform the swap the minimum element which we set becomes part of the sorted array so friends can see that after the fifth pass Five came to its correct position and we are left only with one element so by default this element at its correct position so we don't have to perform these steps on the last element because it is already at its correct position so the only thing to consider here is if the length of a is six then there are at least five passes which is n minus one which is the length minus one so if there are six elements we have to perform five proces to get the array in sorted form so this was the basic idea behind the selection sort algorithm we usually do three steps first we divide the are into two parts sorted and unsorted at the start all the elements are in unsorted part and then we have apply the selection sort in different passes so with each pass what we do is we simply find the minimum element of the unsorted part and simply swipe it with the leftmost element of the unsorted part and after this swap the minimum element which we just found becomes part of the sorted array and this process is repeated till all the elements are part of the sorted array so friend this was the basic demonstration of the selection sort algorithm in our next video we will see the complete animation of the selection sort algorithm step by step I hope you have liked this video and in case you have liked this video then please like comment share and subscribe my channel thanks have a nice day hello everyone so in our previous video we saw a basic introduction to selection sort and we also saw a demonstration that how selection sort is applied on an array having unsorted elements and once the algorithm is applied all the elements become sorted so here let's suppose we are given with this array where the elements are unsorted so in selections s what we actually do is we divide the array into two parts one is the sorted part and other is is the unsorted part so at the start all the elements are part of unsorted part and we have this boundary here so what we actually do we simply find out the minimum element in the unsorted part so here let's say the minimum element among all these element is one so what we do is we pick one and we simply Swip it with the leftmost element of the unsorted part and once we swp them so it would look something like this and we know that one is at its correct position because we want to sort the elements in ascending order so after the swap is done the element now becomes part of the sorted array so the boundary goes here that we have now one element in the sorted part and rest of the elements in unsorted part so this process is repeated for each and every element on the unsorted part till this boundary reaches to the end of the array so when all the elements are sorted the unsorted part has zero elements and all the elements are in sorted part so in our previous video we saw step by-step demonstration of the algorithm now we'll see the stepbystep demonst ation of the actual code so here you can see this is the algorithm to perform the selection sort on an array and this algorithm will sort the elements into ascending order so let's say when we call sort method and pass in an array so let's suppose this is our array having five elements 5 1 10 2 and 9 now here you can see they are index from from 0 to 4 moving ahead in the first step what we do is we simply store the length of the array in an integer variable n so value of n is five because we have five elements moving ahead also friends in our previous video we discussed that we divide this array into two parts the unsorted part and the sorted part so when we start the gorithm the sorted part has zero elements and unsorted part has all the elements so here basically what we do we find the minimum element in the unsorted part and once we find that out we simply swipe it with the leftmost element of the unsorted part and once the element is swapped now that element becomes part of the sorted array and this boundary will get shift by one position so here you can see this outer for Loop Loop goes from I = to 0 to a value I less than nus 1 so here basically I will keep the track of this boundary and here you can see it will start from zero and it will go to less than n minus 1 which is 4 so it will go till three here so why we Traverse I to less than n minus 1 because when we are on the last pass the last element goes to its correct position and we don't perform this algorithm on the last element because we know that that element is at its correct position so we will see the demonstration of the algorithm and it will be more clear to you so currently we'll start with i equal to 0 and 0 is less than 4 so the condition in for Loop will be true and the for Loop will execute so here what whatever the value I is holding it will be simply the indexes of this array so it can be symbolically represented like this so in selection sort our first task is to find the minimum element among the unsorted part so here you can see we first assume that let's say whatever the value I is holding we treat it as the minimum value so here we create an integer variable and we store the value of I so Min will also become zero which signifies that we are assuming that value five is the minimum element among these all the elements and now we provide the inner for Loop now this inner for Loop is for actually finding the minimum value so here this is our assumption and in order to find the minimum value among all these elements we need to compare this minimum value with all the elements of this array and once we find any value Which is less than the minimum value our Min will point to that value so let's see how so here this form will start from I + 1 because here you can see we are assuming that five is our minimum value and I is pointing to it so we start this inner for Loop will J equal to I + 1 so here can see value of J Will become 1 which is 0 + 1 so which signifies that we are starting from this value because we need to compare now five with each and every value of this array so J starts from I + 1 and it will go till J is less than n so less than n will becomes four because we want to compare it with each and every element so last index of J would be four so let's move ahead and see how it works so in the first step we are simply comparing that whatever we assume to be the minimum value is the value at J index less than the index value which mean is holding so here you can see the value at array of Min would be five and array of J would be 1 so now we'll simply compare these two values and here we are checking that whether one is less than 5 or not so here you can see this condition comes out to be true so as we have found a minimum value now what we'll do we'll simply update the minimum to this value so whatever the value J is holding which is one now Min will point to this value holding a value as one so minan becomes one and symbolically it will point to an index one moving ahead we'll increment J by 1 because now we need to compare this one with rest of the elements so J becomes two now we'll compare these two values and we check whether 10 is less than one or not so 10an is not less than one so this condition comes out to be false we'll increment J by 1 so J becomes 3 now we'll compare these two elements that value of r at Min index is 1 and value of array at J index is 2 so we'll now compare compare these two values so here you can see 2 is not less than 1 so this condition comes out to be false we'll increment J by 1 so J becomes 4 and now we'll simply compare 1 with N9 and we'll simply check here whether 9 is less than 1 or not so 9 is not less than one so therefore this condition comes s to be false and now we'll increment J by 1 so J will become five which means that J is now out of these boundaries and this condition here you can see J should be less than n so J value is five and 5 is not less than 5 so therefore this for Loop will terminate and we simply reach here so here you can see that we have found out the minimum value among this Elements which is one and in selection sort what we do is we simply swipe it with the leftmost element of the unsorted part which is being hold by the value I so here we are performing this swap using this temporary variable so in the first step we are storing the value one into the temporary variable so temp becomes one and then we are simply swiping the value at I index which is five into this index so five will come here and at the last step we are simply assigning values toed temp into the IAT index which is this so we have simply swapped these elements and after we perform this swap we know that one is at its correct position because we need to sort all the elements in ascending order so now this one will go into the sorted part and rest of the elements will be still in the unsorted part so the call will reach here in the outer for Loop will increment I by 1 so I will become one so now I will point to this index which is one and the first step we are assuming that let's say this is our minimum value among all the elements so we are simply assigning value of I to Min moving ahead now as we need to find the minimum element from the unsorted part we need to provide this inner for Loop which will start from J = to I + + 1 so I is pointing to index one so J will start with index 2 and the value of J which is 2 is less than 5 so this condition comes out to be true so now we are again we are simply performing this check that whether 10 is less than 5 or Not by taking in the value at jth index and the value at Main index so so Min is pointing to index one and J is pointing to index 2 so we are taking these two values and we are comparing that whether 10 is less than 5 or not so this condition comes out to be false because 10 is not less than five we increment J by 1 so J becomes 3 so still you can see 3 is less than 5 so this condition comes out to be true now now we'll compare these two values we check whether 2 is less than 5 or not so yes 2 is less than 5 so this condition comes out to be true and as this condition comes out to be true and we need to find the minimum element among this elements so now our Min will point to this index because we have found a minimum value moving ahead will increment J by 1 so J becomes 4 and four is less than 5 so this condition comes out to be true now here we check that whether 9 is less than two or not so 9 is not less than two so this condition comes out to be false J becomes five so now this condition 5 is not less than 5 so this for Loop will terminate and we have found our minimum element which is two so we'll simply swap it with the leftmost element of the unsorted part which is being tracked by the value I so we are simply swapping five with two using this three steps so we'll quickly go over these three steps temp will have value two with this statement we will transfer five to this position by assigning the array value at I index to the array value at Main index so this becomes five and at last we'll store the value of temp into the aat index so this becomes two so friends here you can see after we perform this swap now two will also become part of the sorted part with each pass the sorted array is increasing and the unsorted part is decreasing so now we'll increment I by 1 so I becomes two and 2 is less than four so this condition comes out to be true so now we need to find the minimum element among this unsorted part so we are assuming that whatever the value I is holding currently it's the minimum value so we are simply assigning value of I to Min so value of Min will become two and now we need to compare 10 with rest of the elements so for that we need to provide this inner for Loop where J will start from I + 1 because we need to to compare this with other elements so I is already pointing to this element so we'll start J by I + 1 so J becomes three now we'll simply compare these two values and here we are finding that whether 5 is less than 10 or not so this condition comes out to be true so we have found our minimum element after this comparison so we'll simply update Min to this value three and we continue with our for Loop we'll increment J by 1 J becomes 4 and 4 is less than five so this condition comes out to be true now we simply check whether 9 is less than 5 or not so 9 is not less than five so this condition comes out to be false we'll increment J by 1 so J becomes 5 which is out of bounds of this array and here 5 is not less than five so this condition comes out to be false and our for Loop will terminate so here you can see we have found our minimum element which is five now we'll simply swipe it with the leftmost element of the unsorted part which is being tracked by value I so we are simply performing this s where five will come to this position and 10 will come to this position so here after we perform swap now five is at its correct position and now this will become part of the sorted array we'll increment I by 1 so I becomes three and three is also less than four so this condition comes out to be true now at the first step we assume that 10 is the minimum value so we simply assign the value of I to Min which is 3 so it will point to the third index and now we need to find the minimum element from the unsorted part so only two elements are left so we'll start our inner follow with J = to I + 1 so J will start with 4 4 is less than 5 so this condition comes out to be true and here we'll simply compare that value at J index which is 9 is less than value at Min index which is 10 or not so 9 is less than 10 so this condition comes out to be true and we have found our minimum element among these two elements so Min will be updated to four by assigning the value of J which is 4 to Min we'll increment J by 1 so J becomes five which means that five is not less than five so this condition comes out to be false and then as we have found our minimum element we'll simply perform a swap with the leftmost element of the unsorted part which is being tracked by I so 9 will come to this position and 10 will come to this position using this temporary variable so first 10 will come here and then whatever the value is stored here which is nine will come here so after this swep we know that 9 is at its correct position so this will be part of the sorted array so friends here you can see that at the end there were only two elements and as we sorted the second last element the unsorted part was left with one element so this algorithm should not be applied to this element because this is already sorted because this is at its correct position only now so therefore we provided this condition that I should go to less than n minus one so here if we increment now I by 1 I becomes 4 so I will come to this point but here you can see 4 is not less than four which makes sense because now I is pointing to the last element element and if it is the only element left then we are sure that the last element is actually sorted so friends here we saw the demonstration of the selection s algorithm step by step and once this algorithm gets finished we found all the elements sorted into the ascending order so now let's go to intelligent and code the algorithm and test it working so friends I hope you have liked this video and in case you have liked this video then I would request you to please like comment share and subscribe my channel thanks have a nice day hello everyone so in our previous video we discussed about the selection sort algorithm and we saw the demonstration of the algorithm step by step using an animation now in this video we'll code the algorithm into this sort method where we simply pass in the array which we want to sort and we'll simply apply the selection sort and test it's working in the main method So currently we are given with this array 512 910 and if I run the main method so here we will see that we are simply printing the array now using this print array method so 512 910 got printed now let's Cote the algorithm in this s method so in the first step what we do is we create an integer variable n which will hold the length of the array because we will use this value of n in the algorithm while we provide the for loops now at the first step we provide a for Loop which starts from integer I equal to 0 to a value less than N - 1 I ++ so in our previous video we discussed that we are actually dividing the array into two parts the sorted part and the unsorted part so basically this I will keep the track of the sorted and the unsorted part so at the start all the elements are part of the unsorted part so therefore the value of I will be zero and the value of I will go to less than n minus 1 so here you can see we have this five elements so the value of n will be five and if we do minus one it will be four so I will go from 0 to three now why this I will go from 0 to three is because if we see the indexes it starts from zero and three will come to this point so when we compare these last two elements and we sort them then we know that both the elements will be at its correct position so this algorithm should not go further ahead because if I will come to this point then we know that this is already sorted so we are keeping track of the I till less than n minus one and which we already discussed in our previous video in great detail so you can watch that video now inside this for loop as we want to find the minimum element in the unsorted part so what we do is we assume that that main is pointing to index zero at the start and we are assuming that the first element is the minimum element and after that we need to provide a for Loop now this for Loop will start with J = to I + 1 and this will go till less than n j++ so here you can see that we are assuming the value hold by an array at index is the minimum value so this is our assumption and in order to find the minimum element among the unsorted part we need to provide this for Loop where we will compare all the elements with the value hold by the minan index and as the Min is pointing to the aad index we are starting this inner for loop with J is I + 1 and J will go till less than n because we need to compare this minimum value with each and every element of the array so J will go till the last index and inside this for Loop we will provide a condition as if value at jth index is less than value at Min index then we know that we have found one more element which is less than the value at Min index so what we do is we simply update the minan value to point to J because we have found a new minimum value so now Min will point to the J index and this for Loop Will Go On Till all the elements are compared with the Min value and after this for Loop will terminate we know that we have found our minimum value whose index is being hold by the Min integer so after the for Loop we'll simply swipe this minimum value with the leftmost element of the unsorted part which is being hold by the value I because we already discussed that we divide the R into two parts the sorted part and the unsorted part and I will keep the track of that boundary so at the start I will point to zero which would be the leftmost element of the unsorted part so we'll simply swipe this minimum value with the value stored at the a index and we'll use this temporary variable so we first store the value at minimum index which would be our minimum value into the temp and then we will assign the value of I index to value at Main index and at the last whatever the value stored in temp we'll assign to IAD index so here you can see after we perform this swap one element reaches to the sorted part and then we increment the I by one so I becomes one and the rest of the algorithm is repeatedly performed on an array till we get all the elements into the sorted part so in order to understand the selection sort using an animation you can watch my previous video so this is the code for the selection sort now let's test it's working so after printing the array we will call the sort method we pass in the array and once this method gets executed we will simply print the aray again if I run the main method so here you can see initially ARR was 512 910 and after we performed the selection s it became 1 125 9 10 which is in ascending order so friend this was all about the selection s algorithm I hope you have liked this video and in case you have liked this video then please like share comment and subscribe my channel thanks have a nice day hello everyone so in this video we will discuss that how we can merge two sorted arrays in Java so usually in this problem we are given with two sorted arrays and both the arrays are sorted in ascending order and our task is to merge these two arrays in such a way that the resultant array is also sorted so let's go ahead and see that how we can merge two sorted arrays in Java so before we start in case if you are new to my channel then please subscribe to my channel so that you don't miss any update so here let's suppose we are given with this two arrays array 1 and array two and here if you see both these arrays are sorted in ascending order so array 1 has four elements 2 3 5 10 and they are sorted in ascending order and same with array 2 having elements as 4 6 11 and 15 now our task is to merge these two array in such a way that the resultant array is also sorted so the idea behind this algorithm is we create a resultant array whose length is the length of array 1 plus the length of array 2 so in this case array 1 is length four and array 2 is length four so our resultant array will have length eight because we need to merge all the elements of array 1 and array two into this result array so in this algorithm as these both the arrays are sorted in ascending order what we do is we simply compare the elements of array 1 with array 2 and whichever the element is smaller we simply put it into the result array so how do we perform this algorithm is we take three pointers one pointer will start from array one second pointer will start from array two and there will be third pointer which will start from our result array so the three pointers we create is I which will point to the zeroth index of array 1 J which will point to the zero index of array 2 and K which will point to the zeroth index of result array so here as both the arrays are sorted we simply compare the element stored at the ath index of array 1 with the element stored at the jth index of array 2 and whichever of them is smaller we simply put it into the K index of result array so here in first step we compare two with four because I and J are pointing to a index having value as 2 and four so here we see 2 is less than 4 so therefore we simply update this value to K index of the result array so it would look something like this two will come to this position now here as we have filled this value here so we simply increment I by 1 and as we have filled this position we also increment K by 1 so now we'll again compare the value aat index with the value of J index of both the arrays so we'll compare now three with four so here you can see 3 is less than 4 so we simply update the value 3 into this position and as we have used the value three we simply increment I by 1 and we have filled this position so we increment K also by one so now we'll again perform this comparison we compare five with four so now here you can see 4 is less than 5 so therefore we put this value four into this K index because our task is to merge this two sorted arrays and the result array should also be sorted so therefore we perform this check and whichever is the minimum value we simply put it into the result array so now we have used the value stored at jth index so we'll simply increment J by 1 and we have filled this value so we'll increment K also by one so here you can see wherever we are finding any lowest value in Array 1 or in Array 2 we are simply incrementing that pointer and why we are not incrementing the other pointer is because that value is still needs to be filled inside this array so now as we incremented J by 1 we'll compare 5 and six because those values are referred by I and J index and here we know that 5 is less than 6 so we'll simply update five value at the K index and and as we have used this value we'll increment I by 1 we have occupied with this position so we'll increment K also by 1 now we'll compare 10 with 6 so here you can see 6 is smaller than 10 so 6 value will be updated here and as we have used this value six we'll increment J by 1 and we have filled this position so we'll also increment K by 1 now we'll compare 10 with 11 so here you can see 10 is less than 11 so value 10 will be updated here we'll increment I by 1 so here you can see now as you are incrementing I by One I will be Crossing the boundaries of array 1 so now there is no more element left in the array 1 to be compared with the elements in the array two it means all the elements of array one are filled into the result array and we are only left with the elements of array 2 which are already sorted so now our task is to Simply put these values into its respective positions here because we don't have to compare these values with any other value because these are already sorted in ascending order so as we incremented I by one after filling the value 10 here we'll increment K also by one and now we'll simply copy the remaining elements of array 2 into this result array using the J pointer so the first step we'll simply copy 11 here then we'll increment J by 1 and we'll also increment K by 1 and we'll simply copy 15 10 into this K index we'll increment J by one so J has reached out of these boundaries now for array 2 and we'll also increment K by 1 so K is also reached to its end so which signifies that both these array elements are now part of this result array and as both the arrays were sorted in ascending order you can see the result array is also sorted in ascending order so here this is the idea of how we can merge two sorted arrays by simply using three pointers i j and k i will Traverse array 1 J Will Traverse array 2 and K will Traverse our result array we will simply compare the values stored at I and jth index of their respective arrays and whichever the value is small we'll simply update it into the result array at the K index and after we update these values whichever value we took either from array 1 or from array 2 we'll simply increment that respective pointers and as we are failing up the positions in the result array we will also increment the K pointer so friend this was all about the demonstration of how we can merge two sorted arrays and create a resultant array which is also sorted in our next video we will look into the animation of the actual algorithm which is involved in merging these two arrays so friend in case you have find this video informative then please like comment share and subscribe my channel thanks have a nice day hello everyone so in our last video we discussed about that how we can merge two sorted arrays in Java we discussed about the idea that how we can merge to sorted arrays so in this video we'll will see the step by-step demonstration of the algorithm but before we start in case if you're new to my channel then please subscribe to my channel so that you never miss an update so here you can see that this is the algorithm to merge two sorted arrays array 1 and array two into a result array and simply return the result array from this method merge so let's see the demonstration of this algorithm step by step so initially when we call this merge method we pass in the two sorted arrays array 1 and array two and we also pass the length of these two arrays with a variable as n and M so n will correspond to the length of array one and value M will correspond to the length of array 2 so when we call merge method here you can see that for this example we are taking two array which are sorted in ascending order having length is three so let's say we are providing this two sorted arrays having length is three and here you can see the elements are sorted in ascending order in both the arrays and now our task is to merge these two arrays into a result array and return that result array from this method so the length of these arrays are denoted by n and M having values as three so in the first step as we want to merge this two arrays all the elements should be part of the result array so first we create that array by name result and the length of that array would be n + m because we need to merge these two sorted arrays and our result array should contain all the elements of both these arrays so after this L gets executed we are provided with this array whose length is six moving ahead and as we discussed in our last video the idea behind this algorithm is we create three pointers i j and k we'll initialize it with zero value now what these pointers are the pointer I will Traverse array 1 starting from zero index so we have provided value zero pointer J Will Traverse array two starting from zero index and pointer K will Traverse the result array starting from zero index so here you can see the purpose of these three pointers are different so in this algorithm at any instant we are comparing the value stored at IAT index with the value stored at J index and whichever the value is smaller we are simply simply updating into the result array e k index so these two pointers are used for comparison and this pointer is used to fill this array and the filling of this array is sequential where we place in elements one by one and we'll increment K 1 by one and similarly this comparison also sequential we are finding the minimum value at each iteration and we are simply updating into the result array so here at the start of this algorithm we are providing this while loop now why we have provided this while loop is because we need to compare the value stored at ith index and value stored at jth index so it simply means I will Traverse the array 1 and J Will Traverse array 2 so in order to perform this traversal and comparison we are providing this V Loop and inside this V Loop we have provided two conditions one is this I should be less than the length of array 1 and J should be less than M which is length of array 2 now why we have provided this condition is because as we are comparing and incrementing values of I and J which you can see here so there can be a chance that J goes out of bounds for array 2 and I goes out of bonds for array one so when any of this pointer will exhaust its respective are we'll simply exit this V Loop because there are no more element left to be compared between these two arrays because one array is already exhausted so therefore we have provided this two condition so at the start I is pointing to zero J is also pointing to zero I is less than three and J is also less than three so therefore this V Loop condition comes out to be true now in the while loop we are comparing that whether value at IAT index for array 1 is less than value stored at J index for array 2 or not so here you can see so we are comparing two with three so here you can see 2 is less than three so this condition comes out to be true so therefore if block will be executed now as we have found a minimum value among these two values and we want to merge these two sorted arrays into this result array and SED form then what we do is we simply update the value at aat index for array 1 into this result array at K index so two will come here moving ahead now as we have used this value so we'll increment I by 1 So currently I is zero I will become one and after this this if else we will increment K by 1 because we have filled this position here so now we need to go to next position to get the next element so K becomes 1 we'll check both these two condition so 1 is less than three and value of J is 0 so 0 is also less than three so this both the condition comes out to be true now we'll again compare value at I index for array 1 with value at J index for array 2 so which is we are comparing five with three now here you can see five is not less than three so therefore this condition comes out to be false and lse part will be executed so in the lse part as 3 is less than 5 we'll simply update value of three to the result array so here we are assigning value stored at J index for array 2 into result array at K index so three will come here now as we have used the value three we'll increment J by 1 so J becomes 1 and we are not touching I because we need to still get this value five and store it somewhere into the result array so I will simply point to the same index we'll increment K by 1 because we have filled this position so for the new value we'll simply go to its next index so K becomes two 1 is less than three and 1 is less than three so this both the condition comes out to be true we'll compare value at I index for array 1 with the value of J index for array 2 so here we are comparing five with four now and here you can see 5 is not less than four so this condition comes out to be false and in the lse part as we have found the minimum value is four we simply update four into the result array by this assignment and as we have used this value we'll increment J by 1 and we have filled this position so we'll increment K by 1 K becomes 3 here still I is less than n and J is also less than m 1 is less than 3 and 2 is also less than three so this both condition comes out to be true we'll now compare five with 9 because those are the values pointed by I and J index and here you can see 5 is less than 9 so therefore this if block condition comes out to be true so now it's time to update value five into the result array and as we have updated value five we increment I by 1 so I becomes two and as we have filled this position we'll increment K by 1 so K becomes 4 so still this while loop condition comes out to be true because I is less than n and J is also less than M We compare these two values 7 and 9 we found that 7 is less than 9 so therefore this condition comes out to be true so we simply update value stored at aat index in Array one into the value a k index for result array so seven comes here and then we'll simply increment I by 1 so I becomes three so here you can see now I has crossed the boundary for array 1 we have used this position so we'll increment K by 1 K becomes five so friends now here you can see that array 1 is already exhausted so this condition I is less than n where 3 is not less than three so therefore this overall condition will come out as false and this value will terminate so here you can see whenever any of the array gets exhausted we'll simply break from this V Loop and then our execution ution point will reach here where we are encountering two while Loops so friends here you can see that there can be a chance that array 1 gets exhausted first or array 2 get exhausted first so when this Val will terminate we are not sure that which array gets exhausted first so therefore we have provided this two while Loops so here let's say for example eror 2 gets exhausted first so if arror 2 gets exhausted first there can be left over elements in Array one which needs to go into the result array so we are providing this while loop where we are simply traversing I to complete the array one get those elements from array one and simply fill it in the result array because as both the arrays are sorted we are simply copying the leftover elements from the respective array into the result array so this while loop is when array 2 will get exhausted and this V Loop is when array 1 will get exhausted so currently for this example you can see array 1 got exhausted so this V Loop will not get executed because the condition here is I should be less than n so 3 is not less than three so therefore this while loop won't get chance to execute because because array 1 is already traversed completely and we know that there are leftover elements in AR 2 because J is less than m 2 is less than 3 so whatever elements are left over in Array 2 will simply get copied into the result array because those elements are already sorted so we'll simply store value 9 into the result array by this assignment and after doing this assignment here for this small example you can see that there was only one element so we simply updated one element here but let's say if there are many elements and as this arrays are sorted so we can simply copy those leftover element directly into the result array because there are no elements left for array 2 to get compared with array 1 because array 1 is already exhausted and same thing goes when array 2 gets exhausted and there are leftover elements in Array 1 so these two for Loops are important because they simply copy the leftover elements from their respective arrays to the result array and there can be multiple Elements which are left over so therefore we are providing this V Loop so at the last step of this V Loop we are incrementing J by 1 and K by one because we have migrated value 9 into result array so J will now get incremented by one J becomes 3 which means now J has crossed the boundary of array 2 and we'll also increment M K by 1 so K becomes 6 so which means K has traversed the result array completely by filling out each and every position so now we'll again compare whether J is less than M or not so here you can see three is not less than three so therefore this condition comes out to be false which signifies that we have completely migrated all the elements of array to to result array so friends finally here you can see that we have merged these two sorted arrays into a result array which is also sorted so finally we'll return result from this algorithm so friends in this video we discussed the algorithm that how we can merge two sorted arrays so in case if you find this information useful then please like comment share and subscribe my channel thanks have a nice day hello everyone so in our previous video we discussed step by-step demonstration of how we can merge two sorted arrays in this video we'll actually code the algorithm and we'll test its working but before we start in case if you're new to my channel then please subscribe to my channel so that you never miss an update so here I have created one class as merge sorted arrays which is having a method as print array which takes in an array and print its elements on the console so we have discussed this print AR method in our previous videos so I will simply reuse this print array method to demonstrate how we can merge two sorted arrays in Java so here you can see I'll be creating one method as public whose return type would be an integer array because we want to merge two arrays which are sorted and we want to return back the merge sorted array having elements of array 1 and array two so the method name I will be giving as merge this method will take four things one would be the array one other would be array two the length of array one and length of array two which is being denoted by n and M so here you can see that array 1 and array two are already sorted arrays and we want to merge them together so the first step what we do is as we want to merge them we'll simply merge them in the result array so we'll create a result array now the size of this array would be n n+ M because you want to accommodate the elements of array 1 and elements of array 2 into the result array so the idea behind this algorithm is we create three pointers I which will start from zero so this pointer will Traverse array 1 from start to finish we'll create one more pointer which will start from zero and it will Traverse array 2 and we create one more pointer K which will start from zero and which will Traverse result array so here why we have created this three pointer is because pointer I will Traverse array 1 elements 1 by one and J Will Traverse elements of array 2 1 by one and we'll simply compare those two values stored at I and J index and based on our comparison whichever value will be small will simply store it into the result array at K index and after we store this value whichever value of that particular array we get as a small we'll simply increment pointer of that array and after filling the result array at gr index will also increment K by 1 so here in order to perform that we provide a while loop and inside that while loop we provide two condition one is I should be less than n and J should be less than M so these are nothing but boundary conditions where we are simply checking that whether I is in the boundaries of array 1 and J is in boundaries of array 2 and we have have provided this end condition because in this Val Loop we are comparing the value stored at ith index with the value stored at jth index for their respective arrays and in case any of this array gets exhausted which means that either I will cross over array 1 or J will cross over array 2 we simply break from this file Loop so inside this value we are providing a condition as if value of aat index of array 1 is less than value of J index for array two so here it signifies if array 1 element at index is less than a two element at jth index so if this is the condition then after this comparison this value is the smallest value and as we want to merge these two sorted arrays into a result array and that also should be in sorted form so therefore we simply update the smallest value at the K index which means storing array 1 element into result and after we store array one element we have occupied the aat position into the result array so we'll increment I so that we can go to its next index and similarly if this condition is false then in the lse part we do the opposite of it we store the value of J index for array 2 into result because here we know that if this condition is false then value stored at jth index for array 2 will be smaller than this value so we are storing that value into the result array and as we have used the value stored at J index we'll simply increment J by 1 so after storing the minimum value among these two values into the result array we have filled the K position in the result array so we'll also increment K by 1 so that K Travers to an unfilled position so that when this Val Lo will be executed again we are left with a unfilled position so after this V Loop gets terminate there can be two possibilities either array 1 got exhausted or array 2 got exhausted if array two got exhausted which means that all the elements of array 2 are now part of our result array and whatever leftover elements are there in Array 1 we simply copy it into the result array so for that we'll use the Loop we provide the same condition as I should be less than n because we are simply copying the leftover elements of array 1 now so we copy this and we'll increment K also by one after filling the position so here this while loop signifies that arror two got exhausted and similarly we don't know that which array got exhausted in this above while loop so we need to provide the same while loop for the array two as well we provide the condition as J should be less than M this will signify that aray 1 got exhausted first we'll increment J by one and we will keep rest as it is so friends here you see that why we have provided these two while Loops is because we don't know whether aray one got exhausted first or array two got exhausted first so if array two got exhausted first we are simply copying the leftover elements of array 1 into result and if array one got exhausted first we are copying the leftover elements of array two into the result using this Val Lo and while we are simply copying this elements from the respective arrays because those elements are already sorted and we don't have to compare it with any other elements whatever the comparison we need to do we have done it in this while loop so at the end we'll simply return the result array so friend this this is the code for merging two sorted arrays now let's test it's working in the main method so here I will be creating two arrays array one let's say I provide the value as 0 comma 1 comma 8 comma 10 these four values and here you can see these are sorted in ascending order and similarly I create ARR two let's say provide value as 2 4 11 15 and let's say 20 so these values are also sorted in ascending order now let's print both these array on the console if I run the code now so here you can see it is simply printing both the arrays on the console now we will call over merge method we pass in Array 1 array two length of array 1 which is denoted by n and length of are two which is denoted by m so this method will return as the result array so we'll store it into the result variable and finally we'll print the result array if I run the code now so friends here you can see that it returned 0 1 2 4 8 10 11 15 20 it merged these two sorted arrays and returned as the result array which is also in sorted form so friends this was all about the code and working of the algorithm now why this algorithm is important because the similar approach is usually used when we actually perform the merge sort which we will will be looking into our upcoming lectures so there will simply use this idea and we'll perform the Sorting of array using M sort so friends if you find this information useful then please like comment and share this video and in case if you're new to my channel then please subscribe to my channel so that you don't miss any new update thanks have a nice day hello everyone so in this video we will be looking into a sorting Technique we call it merge sort so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so what is M sort so here you can see that M sort is a divide and conquer algorithm so divide and conquer algorithm is very widely used algorithm to to solve the problem now as per the Wikipedia here you can see divide and conquer recursively breaks down a problem into two or more sub problems of the same or related type until these becomes simple enough to be solved directly so when we divide a complex problem into two or more smaller sub problems and we keep on doing it till those smaller problems are easily solved and after breaking the this complex problem into smaller sub problems what we do is we solve those smaller sub problems we take the solutions and then combine them to give a solution to the original problem so basically we divide a large problem into various smaller sub problems and we keep on doing it till those sub problems are simple enough to solve and once we solve them we have their Solutions so what we do is we we take their solution and we combine them so that we get the solution to our original problem so at this step when we are combining the solution of smaller sub problems and getting the solution to our original problem is actually the conquer part of it so let's see how this divide and conquer algorithm fits into M sort so when we are given an array and we want to sort them what we do is we first apply the Divide part now in this step what we do is we take the middle point of the array and divide the array into two halves and once we divide the array into two halves now the algorithm is carried out recursively on these two halves and it goes on Till There Are No More halves of array to divide so we keep on dividing it till there is only one single element left which is not further divided so after this divide step ends what we do is we then conquer and how we conquer is in this step from the bottom we take those smaller half arrays we sort them and merge The Divided arrays and get the sorted array so we'll see this divide and conquer with an example to make it more clear so for timing we divide an array into two halves and we keep on dividing them into two halfes still there is only single elements are left and those are not pretty much divided so when we pick those single elements those are already sorted so we simply merge them and get the sorted array and we keep on doing this till the complete array is sorted so let's see these two steps with an example so first we will see the Divide part so now let's say we are given with this array and we want to sort it in ascending order so in the divide part what we do is here we can see that there are seven elements 2 10 5 3 6 4 and 11 now we simply evaluate the mid position so here is three so how we evaluate this mid portion is we'll see later but here you can see that as there are seven elements from 0 to 3 we break it down into one array and from 4 to 6 we break break it down into other array so here you can see now this was our original problem to solve we break it down into two smaller sub problems and after breaking it down into two smaller sub problems we do it recursively again into this smaller sub parts so here what we do is after breaking it down into two parts we take this part and we further break it down into two parts so this algorithm is pretty much recursive in nature and now as this algorithm is recursive we take this smaller half and we break it down into two halves so here you can see that after breaking this 0 and 1 we are left with single single element 2 and 10 so here algorithm decides that okay we can't break 2 and 10 further down so what we do is the Divide part is done for this piece so then we conquer so in M sort a single element is already sorted and in the conquer step this is the smallest solution we have that let's say if the array had only one element it would have been sorted so now in the conquer part we actually merge them so in one of our previous videos we have discussed that how we can merge two sorted arrays so this is the first sorted array and this is the second sorted array so in the conquer step we merge them and we merge them in such a way that we compare their respective elements one by one and we try to merge them so here we compare two with 10 and we simply merge them to get the sorted array so after merging those two sorted array we are left with a larger sorted array so here 2 and 10 are actually sorted now this conquer is done for this particular step the algorithm then tries to break this part because as this is a recursive algorithm it breaks it like this first it breaks in four then two then 1 one and after merging the smaller subunits it takes the next unit and break it down into smaller pieces so it breaks five and three like this so five and three cannot be broken down further so now it conquers it so here it simply Compares 5 and three and we get three and five because three is smaller so three comes here and five comes here so here you can see that this is the first sorted array and this is the second sorted array and now we simply merge these two parts because the these are solved problems of our smaller sub problems so in the conquer step we actually merge them so after merging these two sorted arrays it looks something like this so two is compared with three it comes here then 10 is compared with three so three is smaller so three comes here then five is compared with 10 five is smaller so five comes here and then 10 goes here and this step is done so now algorithm will pick this part and try to break it down using the Divide stab so it will break it down like this 6 and 4 and 11 because there are three elements and here it will now first pick this part so it will break 6 and four like this and then it will merge 6 and 4 so which will become four and six so the only thing to keep in mind is in the conquer step of mar what we are doing is we are merging two sorted arrays and the result is a large sorted array so here you can see that this was sorted array this was sorted array we merged it in such a way that we got a larger sorted array similarly with this we got larger sorted array and as this part was actually sorted and this part was also sorted so we merged these two sorted arrays as well so we got this sorted array and similarly we did here so after sorting 4 and six as 11 is the only element left so it goes like this it comes here and then we have two sorted arrays we try to merge it so we get 4 6 11 and now here you can see the algorithm ISS okay we have one sorted array we have another sorted array now we can simply merge these two pieces together like this 2 3 4 5 6 10 11 so here you can see that the final array which got sorted is actually our original problem which we wanted to sort so friends here I will just go back so we'll go through this one more time we saw that this was the problem given to us and we wanted to sort it using mer sort so here we evaluated the midpoint of the array and we break it down into two smaller sub problems recursively so recursively how it goes is it breaks it down like this and then recursive it goes to here it break it down like this and then it again recursively go here then it break it down 2 and 10 and it sees that okay it can't be further broken down so it tries to merge it so why it tries to merge it because this is the sorted array having only single element and the single elements are already sorted so it treats it as two smaller sub arrays which are sorted and it tries to merge it in the conquer step so merge it like this 2 and 10 so one thing is important you watch my previous video where we actually saw the algorithm that how we can merge two sorted arrays and the resultant array is also sorted so we will get the sorted array so this recursion ends here it then goes to this side it takes 5 and three breaks it down like this it merges five and three which gives three and five so this part is done so once this part is done it sees that okay I have got one larger array here and here and both are sorted so it tries to merge them so we'll get 2 3 5 10 and after doing this part completely it then goes recursively to this part it breaks 6 41 into two parts 6 and 4 on one side and 11 on other side it recursively sees that okay I can break this down further it breaks it down 6 and 4 like this it merge them it becomes 4 and six and then it goes to this side it sees that okay 11 is only the single element left so it comes here and it sees that okay I have got two SED Aras like like this so in the conquer step I will simply merge them so when we'll merge them we'll get 4 6 11 and as we have done this step the algorithm sees that okay this is the one sorted array this is the other it simply merge both of these arrays like this so friend this is the basic idea behind divide and conquer algorithm when we are dealing with M sort in our upcoming videos we will see all these steps in Greater detail we will see the demonstration of the algorithm step by step so that this idea becomes more clear to you that how it is actually done I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day so friends before going into the actual algorithm of M sort so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update we saw that in divide step we saw that we break the array into two parts or into two sub problems and that we do recursively so at a high level I will simply show you the code so this code we will be discussing in a greater detail within animation in our upcoming video but just for for understanding that how it works so when we break the array into two parts we are not actually breaking the ARR from here let's say from 0 to 3 it goes like this and from 4 to 6 it goes like this we are breaking it based on the three pointers let's say low high and mid so usually error Remains the Same and we have something like let's say low points here mid points here and high points here so from low to mid we consider that this is the sub problem and from mid + 1 to high we consider it as a different problem but the array structure Remains the Same it's only the pointers which decides which is the left part and which is the right part so here you can see in the S method this this method gets called two times recursively so one is for going into the left side and one is going to the right side after breaking it based on the mid element and as this s is recursive in nature so here you can see usually at the start low points to zero and high points to the last index and let's say if we calculate mid so here it will be 0 + 6 - 0 by 2 which will give us 3 so mid comes out to be three so for example let's say we calculate mid as three so this division here is done based on calling of these two sorts so what we do is so when we call this sort we pass the ranges from low to mid so low to mid so it looks like that we are doing like this and for the right sub array it says from mid + 1 to high so this is the mid + one to high so it looks like this but the array remains like this only it's actually The Logical division based on low mid and high pointer and this we do recursively so when we call this we actually get this and it again does the same thing again and here you can see it again recursively calls this so this is low and this is mid and this is mid + one and this is high so it goes on like this till we can't divide them further so this condition low less than high help us in preventing that so here if you see low and high point to the same so we simply return from this and once we return from this it goes here then this s is called like this and here similarly this condition help us to make it come back so after these two steps end we actually merge the two sorted arrays so these are the sorted arrays and you can watch my previous tutorial that how we can actually merge the two sorted arrays but in merge sort we actually take the help of a temporary array which help us in merging the two sorted arrays so this we will discuss in a greater detail in our upcoming videos but here we will simply see a high level view of merch how it is actually done so here you can see that we saw that at the last step we take this sorted array we take this sorted array this is the left array and this is the right array and we usually merge it so we do something like this we compare the elements in the respect to arrays and we fill out the array like this and this is our answer that we get a sorted array so this is done bya merge method now let's see how we can take the help of temporary array and merge it so this is the same thing which we saw in our previous slide that so this is the left part and this is the right part so these are distinguished based on these colors so usually how we merge it we create a temporary array of the equal length and then we first copy all these elements like this so here it looks something like this so after we copy every element like this now what we do is this array is our original array we have took every element in the temporary array now we create the pointers which Traverse to left part and the right part and based on our comparison the original array is actually filled so I'll just remove this so here we take I for this left part and J for this right part and how we actually fill is in the original array we start from here let's it K We compare 2 and four denoted by I and J so 2 is less than 4 so we know that two will take this position like this and we are done with this part so we increment I and we also increment K because we are done with this filling now we compare three with four and three takes this place we are done with this element so we increment I we don't increment J because these values are not filled up and you can watch my previous video where we actually saw that how we can merge two sorted arrays so this is the first sorted array this is the second sorted array and the concept Remains the Same when we do the M sort so after filling three we increment K and then we again compare five and four so four is smaller so four takes this place so we are done with this element so we increment J and here similarly we do the filling so in the next iteration 5 is less than 6 so five comes here we increment I we increment K 6 is smaller than 10 so 6 comes here we increment J then 10 comes here and here you can see after filling 10 this element also gets filled so now there are no more element left in the left part and here you can see that we have only left with 11 so this goes out of the boundary and whatever the values are left in the right part we simply put it here because they are already sorted so anything which comes after 11 will be let's say 12 14 x y z but it will be greater than 11 so they will come directly like this so we simply copy the elements in the leftover part of the original array so it goes like this so this is the merge at a high level using the temporary array so friend there are two cases which we need to see so the case one is when the left are is exhausted so here you can see after filling two 2 3 5 into the respective position and even 10 here now your left air is exhausted so we don't touch this now because everything is filled up here and here you can see as we copied all the elements like this in the original array if you see six 7 and 8 whatever the values are here those are actually sorted and when we actually copied into the temporary array It came it like this only so here you can see we don't push it back like this because the right array values are already present in the original array in the same order 11 12 17 so we do nothing here once the left are is sorted we do nothing because right array is already having the elements here which are already sorted now case two comes when right a is exhausted so here you can see 4 5 6 10 11 these are all exhausted till this point so after putting 11 J goes out of this array and K comes to this part because we need to fill two more elements and our right a is exhausted so here you can see that when the right a is exhausted we have to do something to push left aray elements into this seven and eth position so how we do that we provide a small code which is like this so here you can assume that mid is this point and I will go till mid and we simply copy the leftover elements into the respective places using the I and K index so here you can see in the original array at K index we are assigning temp of I so this is the temp and this is the I so 12 will go to array of K like this and then we increment both I and K so K will go here and I will go here and this vile Loop will continue and we'll simply put 15 at this position by this assignment so after that this F Loop will terminate so friends here we need to keep these two cases in mind that if left AR is exhausted we do nothing because when we copied the element into temporary array when the left array got exhausted the right array left over elements were already present in the original array and de to in sorted form but in case two if right are is exhausted so here if this AR is already exhausted and all these elements are present here and there are elements left over in the left part so we need to provide some additional code like this to put it into the respective places so we will see this algorithm in much greater detail in our upcoming video because that is very complex algorithm so I just demonstrated at a high level that how it looks so when we will discuss that algorithm we will see all the details of sort method merge method and how this s method recursively calls itself and basically divides the array into two halves and later when the two halves are no longer divided further than how we actually merge them so friends I hope till this point you must have got a high level idea of how M sort Works in our upcoming video we will you will see a detailed animation of M algorithm which will make this idea more clear to you you can watch this video two to three times so that you can get an idea of the M sort at high level I hope you must have like this video and in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw at a high level that how mer sort Works in Java so in this video we will be looking into the algorithm and we will also see the stepbystep animation of the algorithm so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so here if you see at a high level we are going to sort this array having file elements so you just need to keep that at a high level how this algorithm works so that when we demonstrate actual algorithm you can relate to it so here we see the array has five elements so we divide the array into two parts based on the mid index so we evaluate the mid index let's say here it comes as two so how we break it we usually consider this as low this would be mid and this would be high so low to mid is the left subar mid + 1 to high is the right of so here you can see that we break it down logically using this three pointers like this low to mid is one side and mid + one to high on the other side so now after dividing the a into two parts we recursively break the left part further down so here this will be our low this will be mid and this will be high so we break it down into these two parts low to mid in the left and mid plus one to high on the right part and this algorithm goes recursively and we divide now these two elements so it will be divided something like this 95 and here we see we can't further divide 9 and five because these are the single elements so these are nothing but our algorithms base case that we can't divide them further so here you can see when the division ends for this part now is the time to conquer it so here this left sub array is actually sorted because it has only one element and the right is also sorted so now we have two sorted arrays and we try to merge them and we merge them in such a way that the resultant array is also sorted so we simply do the comparison and we come up with the five and N so this is the merge step so after merging the left side now we go to the right side so we pick two two can't be divided further down so then here you can see we have left sub array and right sub array both are sorted so we try to merge them so after merging it becomes 2 59 and after doing this part as this is the recursive algorithm we first go to the left and then we go to the right so here you can see for this point we have completed all the left side so now we go and perform the same steps on the right side we break it down into two parts then we go to the left and then we go to right so when we go to right we can't further break it down so here the single element is already sorted we try to break the right side we find that it has only one element so we can't divide them further down so what we do is we try to merge them so when we merge them it becomes 3 4 and here you can see now we have this two sub array which are sorted so we try to merge them so 2 59 and 34 we apply the logic of merging of two sorted arrays and at the end we will get 2 3 4 5 9 so just keep in mind that we will perform these steps when we will demonstrate the actual algorithm so that you can relate that how at high level this algorithm works so here you can see that this is the m sort algorithm where we have the sort method and this is the array which we want to sort in our previous video we also saw that how we can use this temporary array to merge two sorted arrays into the original array so here when we'll call this method so let's suppose we want to sort this array having five elements 9 5 2 4 3 so here this temp array is actually of equal length of our original array and at the start it mostly contains the default value which is zero so for Tim being I have just made it empty and here you can see that we want to sort this complete array from 0o to Fourth index so we provide low and a high value so usually at the start low is zero and high is array do length minus one so this array is of length 5 and fp2 minus one we get the last index so low will point to the zeroth index and high will point to the fourth index and here you can see that as it is a recursive algorithm this s method internally calls itself again with some different values so we need to keep the track of the sort method here in the call stack so we need to keep the track of these four things one is the line number so let's say if we are leaving this sort method and calling this sort so we keep the track of the line number because because when this sort method will end we need to return back to this method so this line number will help us that where we actually left and which sort method we left so we keep the track of the line number here and three Fields low mid and high so these three fields are very important because they help us in dividing the array and at the end they also help us in merging the array to make the array in sorted form so here at the start there will be One S method so here we saw that low is zero and high is four so friends here low should be less than high so this is nothing but our base case because as we are calling this algorithm recursively we need to provide a base case so that we come out of the recursion so in the simple terms let's say if we have this array 53 and using this two short method if you break it down like this 5 and 3 so here you can see at this point of time low and high will point to the same index so when we will call this s recursively on this element you will find that low is actually equal to high so therefore we can't divide this array further so we actually return and similarly with three we return and once we return then we know that five and three are two left and right array so we simply call the merge method and merge them and this we do recursively for each and every array which we have divided so we'll see later so for timing this is the base case so currently low is zero and high is four so this condition comes out to be true in our previous video we saw that m s is divide and conquer algorithm so this division goes on till our base case is reached and once we encounter the base cases then we try to conquer and by conquer we mean we try to sort two sorted arrays which we also discussed in our previous video so this merge method help us in doing that so here we need to divide this now in two parts and how we can do that so we try to figure out the mid element and how we can figure out the mid element is by using this formula so here we do low plus High minus Low by 2 so your low is zero plus high is 4 - 0 by 2 which will give us value is two it means this index so usually when you see the mer sort code you will find that this is somewhat different here we do something like low plus High by 2 so basically in the textbooks most of the time you find this low plus High divided by two which give us the mid element so why we actually do this here and not this is because here you can see this low and high are basically integer values so usually they have a particular range and if you cross that particular range we actually get the garbage values so if we do low plus high like this so in most of the cases this works but if low value and high values are at the very end of the integer value and if we do sum of it we'll actually get some garbage value so therefore if our ARR is very huge this condition give us the garbage values so we try to avoid this and we use low plus High minus Low by two because if we do high minus low we will come back into the integer range only so basically this we use to avoid the Overflow of integer value so now here you can see that we have calculated mid as two so mid becomes two here you can see mid is pointing to index 2 so now what it suggest is from low to mid this would be our left part and from mid + 1 to high this should be our right part so now we are bring breing this arror into two parts using this three variables which are low mid and high so we are not actually breaking the complete array we are simply dividing the array based on these three values so from low to mid this is our left part from mid + 1 to high this is our right part and we know that we have to call this algorithm recursively because we need to still break it down further take till they are not further divided so here you can see after calculating the mid we are now going into the left side of it to divide it further so we will divide this three elements further so here you can see that we are going from low to mid and as we are leaving this short method at line number four so first we will update the line number here and then we will call the sort method so this s method will be called so here we can see we pass mid as two so this mid for this short method became high so now there will be one more method on the call stack which is high as two because we have called this short method from 0 to 2 because now we need to further break it down this left are array so initially there was complete array now we are trying to break this left array further down so high is two and here for this short method high will come to this point low is less than High We again calculate the midpoint so here midpoint would be 0 + 2 - 0 by 2 which is is one so mid becomes one we update the mid here it looks something like this so now what it suggest is this boundary again divides the error into two parts so from low to mid we have left and mid + 1 to high we have right so now again recursively we try to break the left part from low to mid so here we are again leaving this method at line number four so we'll update the line number four here and here mid is one so for the next short method this mid becomes the high so now there will be one more method on the call stack with high as one and for this short method high will come to this position so low is less than high now we again compute the mid element so here 0 + 1 - 0 by 2 which will give us 0 so now mid becomes zero we update it here so mid points to zero I'll just remove this so now we have calculated the mid it means we again have one boundary from low to mid which is the one element and mid plus one to high which is the other element so here you can see that now we are again calling sord because currently our array is of two elements and we can still further break it down to one one element from low to mid which is the zero and mid + 1 to high which is 1 2 1 so we are leaving this s method at line number four so this mid is zero so here you can see low is zero and high become Zer because we have called the S method with mid value is zero and this mid value for this short method becomes our new high so we'll simply Point High to Zer as high is zero so friends here you can see that now we have reached our base case because we we can't divide the single element further so at the start we had this full complete array then we had this small array and then we had this small array and now we are actually having this array so we can't divide nine further down so it means we have reached our base case and we have to return from here so as we want to return from this sort method the call will reach to this sort method and we need to begin from line number four again so we'll see how so this execution Point reached here and we know that we had left its previous s method at line number four so we will start from there and when we had left this s method low mid and high pointed to 0 0 and 1 so we again provide them their own values High becomes one mid becomes zero so it was something like this when we left so now we move ahead so here we are done breaking this left part now this two short method actually help us in getting the left part of the array and right part of the array and then we merg both of them here to make a sorted array so usually this left and right part are also sorted which we will see later and in the merge method we are actually merging two sorted arrays so we'll see how so now we need to break five or mid + 1 to high further down so we need to leave this s method now and we need to call this s again and we are living at line number five so we update line number five and there will be one more method on the call stack with values as low will be one and high will be one because when we had left this sort method mid was pointing to zero and when we called this s again we provided mid + one so it means our new low becomes one and high Remains the Same so it looks something like this for this s method that low is pointing to one and high is pointing to one like this and here you can see we can't divide five further down so this is our base case so now we have to return from this method and once we return from this method the execution point will reach here and that method will be removed from the call stack so we had left at line number five so we start from there and when we left this sort method low pointed to zero midp pointed to zero and high pointed to one so we provide them their own values like this so we move ahead so so friends here you can see that in this algorithm we are actually recursively going down and down and we are dividing the array into two parts so at the end we are only left with single single Elements which cannot be divided further which are actually encountering our base case so after this two s method now it's the time to merge both left part which we got from this s and the right part which we got from this s so here you can see 9 and 5 you can think of it a small array having only one element and when array is only one element that array is considered as sorted because there is only one element so now this merge method will take this left part and the right part because they have only single single element and compare these two elements in such a way that both these elements become sorted so that we will see in the merge method so we are leaving this s method at line number six now so we'll update line number six here and here we have this merge method we pass the array the temporary array low mid and high so because we require all these three values to actually count to know that from low to mid we have left part mid + one to high we have the right part so these are the three values so in our previous video we saw that how we are actually doing the merge first we are actually copying all the elements from the original array to Temporary array and how we are copying it we are only copying that much part which we want to merge so from low to high so here low is zero and high is one it means we are only copying this and this element so it looks something like this we will Traverse this for Loop quickly so 9 comes here and five comes here and this for Loop ends so now we have copied the elements like this here and we will now merge these two sorted arrays which is having only single elements left and right so here we actually take three pointers one will point to the left sub array so here I will point to the left sub AR J Will point to the right sub aray because we know that it is starting from mid + 1 and K will help us in merging these two sorted arrays back into the original array so we'll see now so I is zero it is pointing to this left sub array so you can think that this array is like this left and right J is one so J is pointing to the right sub array and K is zero so K will basically start from low because we are merging this two sorted arrays based on this range so when we copied this element from any particular range we need to put it back into that range only so we are starting from k equals to whatever the value low has So currently it is pointing to the zero index so here in our previous videos we actually discussed that how we can merge two sorted arrays so the idea behind this algorithm or this merge method is pretty much the same here I will go till it is less than equal to Mid so I will Traverse the left part and J Will Traverse the right part so these are the last indexes of these two small ARS So currently both the condition comes out to be true because 0 is less than equal to Mid and J is less than equal to high so here you can see we have two small arrays of single single element which are inherently sorted and now we need to merge it in such a way that final array also is sorted so how we do that is we are taking temp p with I index and temp Val J index which is 9 and 5 and we are checking whether 9 is less than 5 or not so 9 is not less than five so this condition comes out to be false and the else part will be executed so it means at this position among these two values whichever is the smaller we'll place it there so currently temp value at jth index is smaller which is five so five goes to the K index of original array so it goes like this and here we have placed five at its correct position so we simply increment J so J becomes two but we know that currently there was only one element but there could be a POS possibility that we are trying to merge a very huge array which is equally among the left and the right part but currently we have only this one element and as we have filled this position we'll increment K so K becomes 1 now here you can see this condition comes out to be false because J has crossed the limits of high as J value is 2 and 2 is greater than 1 so this V Loop will terminate and here you can see once the while loop gets terminate we have only placed five here we need to place nine at its correct position so we are providing this small for Loop and we also discussed in our previous video that once the right array is exhausted we need to provide this small while loop so that all the elements of the left subar are directly copied back so they are copied back with this condition which was similar to here that I should be less than equal to Mid So currently I is less than or equal to Mid and using this V Loop we are simply copying back the element from the a index to the K index so 9 goes here and after placing 9 to correct position we have used this 9 so we'll increment I I becomes 1 we have filled this portion so we'll increment K also K becomes two and here you can see that we have merged this left and right sub array so here now this condition comes out to be false so here you can see after this merge method ends we sorted left and right both were two sorted arrays and we merg them so we got the result array of two elements which are now sorted so now we'll leave this method and we'll go back to the S method where we actually left so the point will reach here back we had left at line number six which was this part so now here you can see so when we had left low mid and high pointed to 0 01 based on the values we kept here so it was something like this so here you can see now this s method will end because there are no more lines to execute and also you will find that after this merge method ends in the original array we have five and 9 actually sorted into the range of low to high so this method will end now and once this method will end it will reach to this point because we had left this s at line number four so so we again start execution from line number four we provide the respective values to low mid and high so when we had left this sort this was our condition so now we move ahead with our execution so here you can see this sort method actually sorted the left part so here you can see if this is the line This array which is our left is sorted now so now we try to go to the right part using this sort method so we provide mid + 1 and high so mid + 1 is the range for the right part and it goes till high so now we'll again leave this method at line number five so this short method will be called again with lowest mid + 1 so when we will leave this method mid was pointing to one so in the call stack there will be S method where low will be now two which is like this here and high will point to two because the high remains at its own position mid was one previous to it so for this method it became mid + 1 so mid + 1 is two and this two became our low for this short method so it means now we are going to the right side recursively to divide that array further down so here you can see we only have this one element so we have encountered our base case so we return from here we reach here we had left at line number five so we start from line number five and now here you can see we provide these values to their respective variables low was Zero mid was one which is is the index one and this was our line which divided the left and right so this is the left and this is the right so here you can see when we had called merge method previous to that we actually merged two small arrays having single element five and 9 and whatever was the result that was sorted then we went to the right and we found that that the right part has only one element so it is already sorted so now this merge method will take a bigger sorted array and we try to merge with the right sub array so this merge method will be called this is our temporary array high is two mid is one and low is is zero so from low to mid so from low to mid this is the left part which is sorted and from mid + 1 to high this is our right part now we are actually merging a slighter bigger array so we'll go over this merge method quickly we copy the elements from the original array to the temporary array from low to high so 5 92 will be copied to Temp at the respective positions so we'll go over this for Loop quickly five comes here nine comes here two comes here and this for Loop will end so friends here you can see that now we have a left part and the right part which are sorted and we need to merge these two sorted arrays and after merging it we need to transfer it back to the original array so this is the boundary for left and this single element is in the right so it's very much similar to what we discussed previous to it I will be traversing the left part and J will be traversing the right part so J will start from mid + 1 mid + 1 is 2 and I will start from zero like this and K will start from the low which is zero so now we'll again merge this two sorted array based on this V Loop provided here so I is less than mid and J is less than equal to I so both the condition comes out to be true now we compare the element ith index with the jth index which is 5 and 2 so 5 is not less than two so this condition comes out to be false and into the original array we first place the smallest element which is temp of J so temp of J is 2 so two goes here and after using this we increment J so J points to three and after filling this position we increment K now here you can see that the right are is exhausted because J value is 3 and 3 is greater than 2 so this condition comes out to be false so here you can see that we actually placed all the elements of the right sub array into the original array but the left sorted array Still Remains and as it is already sorted we'll simply copy it back to the respective K position using this V Loop so I is less than equal to Mid we copy five to the K index which is one so five comes here then we'll increment both the pointers because we have filled this position and we have used this element so I becomes one and K comes to Second index I is less than equal to Mid we copy 9 to index 2 we fill this position so K comes here and as we have used this position so I comes here so now this y Lo will terminate because value of I is 2 2 is greater than 1 so this condition comes out to be false so friends here you can see now slowly we are merging the arrays and we are actually getting a bigger sorted array so it started with single single element then then we got two elements 5 and 9 and now we are getting three elements 2 5 9 so we go back to the S method where we left so here we left at line number six where these were the default values for low mid and high and this was the boundary so here you can see now we have sorted the left part and the right part in in such a way that now they are completely sorted with this much range so this merge method is ended call will reach here so this is the line number where we left this short method and the respective values were 0 2 and 4 so high was pointing to Fourth index mid was pointing to the second index when we actually left at the first sort so now here you can see we have completely sorted the left side of it now we simply go to the right side using this sort method which is going from mid + 1 so this range is mid + 1 to high so when we'll call this short method again mid + 1 becomes our low so here we'll first update the line number there will be one more method on the call stack where low will be three because mid + 1 is 2 + 1 which became our new low for the right part and high is actually Four only so we are simply placing this into the respective indexes for this short method low is less than high we calculate the mid now here you can see first we did this for the left part and we keep on breaking it till we got a single elements now we are simply doing it for the right part so now low is 3 + 4 - 3 by 2 so this will give us value as 3 because 1 by 2 is 0 and 3 plus will give us three so this will give us three now so here you can see now we have got our two boundaries low to mid is the left part and mid + 1 to high is the right part so first we will go to the left left part and try to divide the array we'll update line number we'll call the sort method with lowest three and when we had left this s method mid was actually pointing to three so for this s method here this mid becomes our high so value is three so it looks something like this so we have reached our base case and we can't divide four further down which is at index 3 so we return back I'll just remove this so we had left at line number four so we start execution from here low mid and high pointed to three three and four like this so here this four cannot be divided further and as this left part is only one element it is inherently sorted and now we go to the right part whilea this s method we update the line number and here we are leaving with mid + 1 which will become our new low so mid + 1 is 4 so in this short method low became four and high is actually at its own position four so it looks something like this this is our base case because low is actually equal to high it means we can't break three further down so we return we had left at line number five so we start execution from line number five and at that moment low mid and high were 3 3 4 so we'll assign those values back to them three so here you can see for the right this is single element array which is the left and this is the right and both are sorted so we simply merge them to make it a bigger array which is also sorted so we'll call the merge method so this was the condition when we left the sort and came for the merge so it was 3 three and four so here you can see we are not touching now this part because this left part is already sorted so therefore we have provided this low mid and high because now we'll copy the elements from the original array to the temporary array from low to high which is from 3 to Fourth index so only these two elements will be copied here we'll see it quickly four will be copied here and three will be copied here because we are simply assigning the value with a index of the original array to Temp array and this for Loop will end so now our task is to merge these two sorted arrays this is the left and this is the right via this temp AR so I will be traversing the left part J will be traversing from mid + 1 which is the right part and K which will start from the low which is the index 3 because we don't have to touch this part now we have to only sort in this range like this so here I is 3 J is 4 because J starts from mid + 1 and K is 3 I will Traverse to the left part J Will Traverse to the right part and K will help us in merging them to the original array so I'll just remove this stuff so here you can see I is less than mid and J is less than equal to high so the Y Loop will execute We compare the IAT index value with the J index value which is 4 and 3 so 4 is not less than three so the lse part will be executed it means we take three which is temp of J and we put it into the original array at its correct position because we need to sort this two smaller arrays so three comes here we have used this element and and we have filled this position so we'll increment J J becomes 5 which is now out of the boundary for this smaller right array we'll increment k k becomes 4 and here you can see the right a is exhausted completely so we'll break from this V Loop and then we have provided this Val Loop because we need to still place the elements of the left sub array back into the original array and as the left array is already sorted we simply copy it back to the original array via this assignment so I is less than or equal to Mid we assign temp of I to K index of array four comes here then we'll increment I and K because we have used this element I becomes four and we have filled this position so we are incrementing K also so this Val Loop will terminate now because we are done with our task of placing both the elements into their correct position within their range and here you can see initially it was 43 and now it is 34 which is sorted in this particular range so we go back and we had left at line number six so here you can see current status of array is something like this 2 5 9 3 4 so the left part is sorted the right part is sorted and these were the values for low mid and high when we left so now this s method will end because there are no more execution steps so now call will reach to the previous s method we had left at line number five and at that moment low mid and higher 0 2 and four so this is the very starting point where we left the first sort method so this was the condition so now here you can see we have a larger left array and a larger right array and both are actually sorted so 259 and 34 into their respective ranges they are sorted it means we have two sorted arrays and using this merge method we will merge these two sorted arrays in such a way that the resultant array is also sorted so here one thing this Step at every point when we called merge method we did merging of two sorted arrays so at the start we had only one one element then we got two elements then it became three like like this and here it became two and now finally we are merging a left array of three elements and right array of of two elements so let's see this merge method now we have updated the line number six here so these are the values for low mid and high 0 to 4 and this is our current original array so now here you can see from low to High We copy all the elements to the temporary array because in the merge we actually do the merging based on this ranges here low is zero and high is 4 it means from 0o index to four we'll copy every element to the temp array so we'll quickly go over this for Loop two comes here five comes here nine comes here so these are simple assignments so now this for Loop will end so here why we are copying this elements into a temporary array because this temporary array is helping us with this actual merge which we are doing here and it is helping us putting the elements into their correct position in the original array so here the left are is from low to mid so 0 to 2 is the left array so this is the boundary for left and right array and mid + 1 to high is the right array so I will Traverse the left array and J Will Traverse the right array which we already discussed in our previous merge method I is z J is mid + 1 which is 3 and K is zero because we need to merge this element from the low to high so we have starting K with low IJ comes here and K comes here and here you can see this is the boundary for left and the right sorted arrays so we'll quickly go over this step because we have already discussed what it does I is less than equal to Mid and J is also less than equal to High We compare the I and J index value which is 2 and 3 so 2 is less than equal to 3 so this condition comes out to be true so we are simply copying now two to K index because this is the smaller value among this two so it becomes two and here we have used this value so we'll increment I I will become one we have filled this position so we'll increment K 1 is less than 2 and 3 is less than 4 so both the condition comes out to be true we'll compare I and J index values which is 5 and three and here 5 is not less than three so this condition comes out to be false we put the smaller value at the kth index of the original array by this assignment so three comes here we have used this value so we'll increment J J becomes 4 we have filled this value so we'll increment K both these condition are still true we'll compare 5 and four five is not less than four so this condition comes out to be false so we'll simply put the jth value at K index of the original array so four comes here we have used this value so we'll increment J J becomes 5 we have filled this position so we'll increment K so friends here you can see now this condition is true but this condition is false because 5 is not less than equal to 4 it means the right array is exhausted completely so this while loop will terminate and once the right are is exhausted we know that whatever the ments are left in the left array those are actually sorted in their respective array so we simply copy them one by one to the original array using this small while loop so I is less than equal to Mid we copy temp value at I index into the original array at K index so we are simply assigning five to this portion we have used this value we'll increment I I becomes 2 we have filled this position so we'll increment K and similarly we'll place the last value at its corresponding index so 9 comes here this value is used I becomes three this is fill so K becomes 5 so now this y Loop will terminate because value of I is 3 and 3 is not less than equal to 2 so this merge method will end and here you can see now finally we have sorted complete array 2 3 4 5 9 so we go back to the method call where we left the sort and we called the merge so execution point will reach here at line number six and this values will be pointing to 0 2 4 and friends here you can see the original array is now properly sorted 2 3 4 5 9 and there are no more lines to be executed after that so this s method will end so all the method in the call Se has ended and we have got our sorted array so friend this was the complex animation of this m sort which I depicted based on this call stack I hope you must have got some idea of how it works internally so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw the demonstration of the mot algorithm via an animation step by step so in this video we'll actually code the algorithm and we'll test its working in the main method so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here if you see I have created one class as M sort which is having print array method which we have already discussed that it is used to print the elements of an array on the console so here we will be creating the method as sort and as we discussed in our previous video that this short method will take the original array one temporary array which will basically help us in sorting the original array we will take the range from low to high so usually at the start low is zero and high is actually pointing to the last index of the array because we want to sort the complete array now in this method we provide a condition as low should be less than high now this is basically a base case because this short method is actually recursive in nature we will see later so in this algorithm we are actually dividing the array into two parts the left part and the right part and we will keep on dividing them till the left and the right part contains only single element because they can't be divided further and when low will be equal to high it means we are having only single element so we need to return from this method because we can't divide the array further down so when low is less than high now we will divide the array into two parts so for that we need to figure out the mid index so here we evaluate mid so we use the formula low Plus High minus low divided by 2 so here you can see these are nothing but indexes we can use this formula which will evaluate as the mid index so this formula also takes care of the integer overflow condition let's say our ARR is huge which we have already discussed in our previous video if the AR is very small and it fits into to the integer size we can also use this formula low plus High ided 2 because here you can see why we are using this formula is because these are two integer values and if you're doing addition of it let's say if low and high are at any particular value of integer when we do sum of it it crosses the integer limit so therefore we will get some garbage value so therefore on the safe side we do this we do minus of both the ranges so that the overall value is still in the integer range so after evaluating the mid now as this is a recursive algorithm will call sort again so we break it down the array into two parts and the range would be for the left it will be low to Mid and for the right it will be from mid + 1 to high so here you can see this is the recursive algorithm and it keeps on dividing till there are only single elements left which can't be broken further down so after getting to that point as single elements we treat them that they are already sorted because there is only one element from there on we try to merge them together and this merging keeps on going till the final array sorted so in the merge method we pass the array we pass the temporary array we pass low mid and high why we are passing all the three values is because in the merge based on load to Mid that will be our left sorted sub array from mid + 1 to high will be our right sub array which is sorted and we are simply merging two sorted arrays to get a bigger sorted array so we'll code the merge method now so here you can see we have this original array and we have this temporary array we know the range that It Go goes from low to high low to mid is our left sub array mid + 1 to high is our right sub array so before merging the two sorted arrays we can't directly merge them in the original array so in order to merge the two sorted arrays we take the help of this temporary array what we do is we provide a for Loop which starts from low and goes till High index so what we are doing is now we are simply copying the elements of the original array into the temporary array so this is what we discussed in our previous video in Greater detail so here we do temp of I array of I now we have got our range from low to high in our temporary array and we also know that from low to mid we have the left sub aray which is sorted from mid plus 1 to high we have a right sub array which is sorted and now we need to merge these two sorted array such that the resultant array is also sorted so in one of our previous videos we saw that how we can merge two sorted arrays so we will apply the same algorithm here so for more understanding you can watch that video so so here we will create now three variables i j and k so here I will [Music] Traverse left sorted subarray J Will Traverse right sorted subarray and K will merge both arrays into original array which is this so if I is traversing the left sorted sub array we know that it should start from the low because from low to mid we have the left part and J should start from mid + one because we know that the right sorted sub array is from mid plus 1 to high and we also know that as we are merging the two sorted array within a range from low to high K should also start from low and it will go till high so after creating these three pointers we will now compare each and every every element of the left and the right sub array and whichever element is small we try to fit in that element into the original array at K index so this is the basic idea behind merging two sorted arrays such that the resultant ARR is also sorted so we have provided while loop and the condition we provide is I should go till mid and J should go till high and if any of this condition breaks the wi Loop will terminate so here what this condition suggest is when we are merging the two sorted arrays there will be a point where either left array will get exhausted or the right array gets exhausted so whichever gets exhausted this condition will break respectively and we will come out of the while loop so inside this while loop now we'll try to compare the left aray I index value with right arrays jth index value and as these two arrays are already sorted that's why we are doing the comparison with the respective indexes so we do if temp of I is less than equal to temp of J so here it means whichever value is present at the aat index it means the left sub array value is small so at the original array at K index we will put temp of I and after placing the temp of I we know that left AR is one element is at its correct position so we'll increment I and else we do the other way around array of K temp of J and we'll increment J by one position because we have taken up one element from the right sub array and here you can see we are actually filling the original array at K index so after this F block s k index is filled up so we also increment K by one position to fill in up the next element so this value will again go on like this till any of the array is exhausted so here you can see that now there are two cases which can arise either the left are gets exhausted or the right are gets exhausted so here when the left eror gets exhausted all the elements of the right sub we don't copy it back to the original array because those elements are already at their correct position in the original array because when we are copying the elements from the original array to Temporary array and as both the arrays are sorted so the elements of the right sub array which are left over will usually be at their correct position in the original array so this two cases we discussed in Greater detail in our previous video now we only need to keep in mind is if the the right array gets exhausted first then we need to write some logic to put in the left array left over elements into the original array so for that we provide a while loop and the condition is exactly the same because this I is pointing to index from where the leftover elements are starting and we can simply copy it back to the original array so what we do is we can simply copy it something like this temp of I k++ and I ++ so it is a simple Loop which is copying the elements at I index of temporary array into the original array at K index and after copying it we are incrementing both the pointers so once this method will end the smaller left and right sub array will be sorted and then as it's a recursive algorithm working like this so it keeps on merging the left and the right sub AR till the point all the elements are sorted in ascending order so now let's test it working in the main method so here we have created this array 95243 here we will call the sort method we'll pass the array which is our original array and we need to pass the temporary array so which is of length same as our original array so we'll do new in array. length we pass the lowest zero and high is a do length minus 1 because at the start low is at the zeroth index and high is at the last index which is a. length minus one and after doing the sort we will print the array and we'll see whether this five elements are actually sorted or not if I run the main method so here it sorted as 2 3 4 5 9 now let's suppose if I put one value here as minus one if I call it again so here you can see it it sorted in ascending order so friend this is all about the M sort algorithm so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss that how we can sort an array having zeros ones and twos so we need to sort an array in such a way that zeros are at the start ones in the middle and twos at the end so this problem is also known as Dutch national flag problem because each number basically correspond to one of the colors in the flag so for example Zer is let's say given is red one to White and two to Blue so when we sort an array having Zer ones and twos zeros are at the start ones are at the middle and two are at the end so therefore this problem is also known as Dutch national flag problem so in this problem we are given an array containing only zeros ones and twos so let's say if we take this example we have 0 1 1 2 0 1 2 so these are currently random numbers and when we actually sort them we get zero at the start one in the middle and two at the end so it looks like Dutch national flag like this now our task is to sort the array in O of n time complexity and O of one space complexity because if we sort this array using the language specific sort method then the time complexity will be n login but as we know that there are only three types of numbers zeros ones and twos we can leverage this idea and Achieve o of n time complexity so let's see how so friends before we start the discussion in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so friends here you can see that this is the piece of code which actually does the Sorting in O of n time here we have one while loop which does all the trick so in this video in order to demonstrate at a high level that how this algorithm works I have just mentioned the code here in our next video we will see the demonstration of this code step by step so let's see at a high level how this algorithm will work now for example we are given an array of seven elements from index 0 to 6 and the numbers are Z's 1es and twos so 2 0 2 2 0 1 1 now we need to sort this array in such a way that zeros are at the start ones in the middle and twos at the end so this is start this is middle and this is end so so friends the basic idea behind this algorithm is we actually use three pointers which is i j and k so here in this algorithm each pointer has a special task to perform so at the start I starts from zero J starts from zero and K starts from the last index so I starts from zero J starts from zero and K starts from the last index now here you can see that after that we are providing a while loop where the condition we are providing is I should be less than equal to K so here I is our main pointer which will actually Traverse the array in this direction and when it Traverse in this direction K also Travers in this direction and this Loop will go till I is less than or equal to K so once I crosses K this file Loop will terminate and our array will be sorted in zeros ones and twos format so here the I is our main iterator of the array now its main job is here we can see at the start we have to provide zeros in the middle ones and at the end twos so whenever I will encounter zero let's say here it is encountering zero so we know that we have to throw zero to the start so basically when zero will be encountered it will be thrown to J and whatever value J will hold it will come at the place of I so zeros will be at the start and J will help us in achieving that when two will be encountered I will throw two to end and to the end we have K so it will throw it to the K and take its value to the aat index so this will achieve this part when I will encounter one it will do nothing it will simply Traverse ahead because one is already in the middle so this is the Crux of the algorithm that we have three pointers and three numbers when I will encounter zero it will swipe that number with j when I will encounter two it will swipe it with K and when I will encounter one it will just move ahead and keep one at that position only so here you can see at the start the numbers are in unsorted form so we usually draw four regions like this one region is for zeros other region is for ones and the third region is for twos and one region is just Tok Mark which are the unknown elements till now or unvisited elements till now so at the start all the elements are unknown so they are marked as unknown and they range is from I to K so from I to K so every number is unknown so every number has sck now slowly when I will move ahead it will try to encount C these numbers and try to explore them so these St will come in these three regions marking for the zeros ones and twos at the start from I to K all numbers are unknown from start which is the zeroth index to J minus one so J is actually pointing to zero index if we do minus one will reach here so currently there is no such area or range from J to IUS 1 J to IUS 1 which is also unknown area from k + 1 to end which is the last index so if we do k + 1 will'll go out of this so this is also the unknown area so at the start all the elements are unknown and all the regions are unfilled now we'll slowly move ahead and try to fill each and every region so let's see how we can remove this unknown elements and fill the zeros ones and twos and one thing to remember Zer ones and twos will be filled in a proper order Zero's at the start one's in the middle and twoos at the end so we'll see it later here so here you can see at the start array of I is two so this condition is false this condition is also false and this condition is true because array of I is equal to 2 so now what I will do here we saw that whenever I will encounter two it will simply swap two with the value which K is holding or index K is holding so when we will do swap so two and one which is being referred by I and K in the swap method we will simply swap them so one will come here and two will come here so here our one task is done successfully that we have placed two at its proper position here so 1 2 is at its proper position and we know that when this while loop will run one element has become known now and which is that element which has become known is this that two is at its correct position also friends as we have filled this position we will move K to this direction because for the other two which is here for example it should come here right so K will move to this position and it keeps on moving in this position as many as twos are encountered because we need to swap two with the value of the K index so we do K minus minus so K comes here now here you can see as K is here we know that from k + one to the last index we have two so here we will see this range at every moment of this while loop and we will figure out that where this sck will go so if you see here k + 1 k + 1 is this index to the last to the end which is the same index we have to mark twos because one number is known so this tck will go away and this sck will come here which says that from I to K still the numbers are unknown and only one number was known which is placed at its correct position we have provided tick here now here one thing to notice when we do this swap two will come here and at this position there could be zero 1 or two any of the three number so we are not sure which number is actually getting swabbed here so I will be at the same position only we will only move k so this is the one difference so in the next iteration of while loop here you can see now this condition will be false and this condition will be true because area of I is one so we discussed when we encounter one we will simply move ahead because ones will be in the middle so we'll simply increment I so I will come here and as I will come here here here you can see that unknown is from I to K which is this portion now because this number is known from start to J minus 1 we have zeros so J is still here J minus one is out of this area from J to i - 1 we have to Mark 1 so J to i - 1 which is this part we have to mark one so this element is known so it will go away and Mark will come here because we have found one and we have placed at its correct position in this range so these ranges are important it will help us in traversing the array and also relocating the values of Zer ones and twos moving ahead now here you can see array of I is zero so this condition will come out to be true so here here we have discussed that whenever I will encounter zero it will throw it to J and take its value so here 0 and 1 will be sbed by this method 0 comes here 1 comes here so here you can see now one has actually changed this position initially one was here we have marked here now one has actually changed the position then what we'll do we will increment I and J both so why we incrementing I because here we saw that whenever we encounter I as one we simply move ahead and if you see this range one is always one step behind the I so range is from J to IUS one so whenever I will point to one it will simply move ahead so this is the range that one is one index behind the I so we will do I ++ and j++ so why we are doing j++ because we have placed Zer at its correct position now another zero should come here so we are doing j++ so J comes here and now if you again look into this ranges from I to K these are still unknown and one number is known which we placed here and we took one and placed here so from start to J minus one start to J minus one we have zeros so one tick will come here because we have identified 1 Zer so this will go away it will come here and also here you can see that from J to IUS 1 J to IUS one this portion is actually our one so now this tck will go away and it will come here because we have swabbed 0 and 1 so 0er is now at the start one is in the middle and two is at the end and in the middle we have unknown elements so this is how this algorithm Works let's see further iterations now array of I is two so this condition comes out to be true so we know that what we need to do we need to Simply Swap this value with K so one will come here and two will go there one comes here two goes there and then we will decrement k because the next two value should come here so this position is filled and one more number is now known so if we Mark again from k + 1 to n we will Mark two so k + 1 this range will be marked as true so this tick will go away and there will be one tick here in the middle we have unknowns also friend one more thing that here why we are moving I when are of I is Zer and we are not moving I when are of I is 2 because when we are swipping it with array of K we don't know what value it will be it can be 0 1 2 any value but when we are swipping it with array of J which is here we are sure that there will be only one single value one because we have started traversing I from the middle and whenever we are encountering two we are throwing it here and whenever we are encountering one we are simply moving I ahead so we are leaving one behind so that will be the only value which will it will be swapped so therefore it makes no sense to keep ey in the same place so we move I also with it but here we don't know whether it's zero 1 or two which is being SED so therefore we are keeping eye at the same place so now in in this iteration array of I is 1 which is this condition so we simply move I ahead I comes here this element is known because one should be in the middle so this thing will go away because unknown is from I to K and I to K is this range this element is known we have to put this element here from J to IUS one J to i- one which which is these two numbers so one tick comes here now in the next iteration area of I is 2 so what we do is we simply swipe and move K in this direction so we are simply swipping 0 and two so 0 comes here and two comes here and then we are decrementing K because we have filled two at its proper position so we are moving K here so k K comes here this element is known it will go away and it will come here because from k + 1 to end we have to provide two so these are twos k + 1 to end now only one element is unknown so in the next iteration I is still equal to K and array of I is zero so we'll simply Swap this zero with the jth element here so 0 comes here 1 comes here this is the proper place of 0o so we increment J and as we have placed one here we have also seen that whenever we encounter one at the ath position we simply move ahead so we are also moving I ahead so I comes here and J comes here so now every element is known so this stick will go away and where this stick will come it will come here because we have just placed zero at its correct position so we'll mark this as true and as we have swapped zero N1 so this stick will go away and it will come here so it would look something like this so now if we match the range we will see that unknown are from I to K so I is actually cross the boundaries so every element is known now so it's blank from start to J minus one this is start this is J minus one will reach here so this is actually our zeros which is being marked properly from J to IUS one we have marked ones so J to I minus one so this is the place for ones we have marked it properly from k + 1 to end we have Mark two so K is here k + 1 is this to end we have all the twos which is what we have ticked here so friend this is how this algorithm Works basically we need to keep the track of three pointers I is doing main work it is encountering different values at different positions when it encounters zero it swipes it with J when it encounters two it swipes it with K and when it encounters one it does nothing it simply moves ahead so you need to go through this algorithm few times to understand how these regions are getting plot and how the zeros ones and twos are actually segregated that way in our next video we will actually see the detailed demonstration of this algorithm step by step but to demonstrate this in high level I have just used this regions so that when we encounter this algorithm step by step we can directly come to know that which element is where so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss the algorithm step by step that how we can sort an array of zeros ones and twos in our previous video we saw at a very high level that how this algorithm Works in order to understand this video you need to watch that video first so let's see the demonstration of this algorithm step by step so friends before we start in case if you if you new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update here you can see that we are given with the algorithm where the method name is three number sort which takes in an array now this array consists of zeros ones and twos and we need to sort that array in a linear time so let's see the demonstration of this algorithm step by step now let's suppose we are given with this array having seven elements 2 0 2 2 0 1 1 and we need to sort this array in such a way that zeros are at the start ones in the middle and twos at the end so when we will call three number sort method we will pass in the array so friends in our previous video we discussed that we can solve this problem using three pointers I J and K we also discussed that I is the main iterator which will Traverse from 0er to a value less than or equal to K and we also discussed that how this three pointers help us in sorting the array so at the very beginning I starts from zero J also starts from zero and K starts from the last index which is sixth index now as we need to sort this array in linear time we have provided a while loop and the condition in while loop is I should be less than equal to K so here I will travel in this direction K will travel in this direction and when I will cross K this y Loop will terminate now at the start value of I is Zer and K is 6 so this condition comes out to be true so inside this value we have provided three conditions array of I which is the value at aat index it can be equal to Zer it can be equal to 1 or it can be equal to 2 so any of this condition will come out to be true now here what we do is when I will encounter zero it will throw it to J and take its value so J is mostly behind I and when we encounter zero we know that zero should be at the beginning because we need to sort the array in such a way that zeros are at the beginning so it's the responsibility of I and J to put zero at the beginning so whenever I will encounter zero it will throw it to J and take its value whenever I will encounter two it will throw it to K and take its value so here K is at the last index and we know that we need to place two at the end so I will throw two to K and take its value and whenever I will encounter one it will do nothing it will simply move one step ahead because the one is already in the middle so J keeps the track of placing zero at the beginning k keeps the track of placing two at the end and I whenever encounter one simply move ahead and do nothing so here at the start array of I is two so therefore this condition comes out to be false this condition also comes out to be false and this condition comes out to be true so we know that whenever I will encounter two it will simply throw the two to K and take its value it means we are swapping the value with the K index so we will call swap method we will pass the positions of I and K and here it will swap them so I will be demonstrating swap directly this we have seen many times in our previous videos so when we will swap I and K one will come here and two will go there it means we have swapped value at a index with value at K index we have thrown two at the end and after placing two at the end we know that this two is actually at its correct position so now we decrement K because the next two will come here here so we do K minus minus so K becomes 5 moving ahead I is still less than equal to K now array of I is 1 so this condition comes out to be false this condition comes out to be true and whenever we encounter one we do nothing we simply move I by one position because you don't have to touch one it's already in the middle range so we move I one position ahead I becomes one moving ahead I is still less than equal to K now here you can see array of I is zero so this condition comes out to be true so when array of I encounters Z or I encounters Z it will simply swipe it with j and take its value so when we will swipe it with j 0 will come here and one will come here so here now 0 is at its correct position because we need to arrange zero at the start so after placing zero at its correct position the next zero should come here so what we do is we increment J and I both and as I is pointing to one we know that we need to Simply Traverse I also by one position so we do I ++ I becomes 2 and we do J ++ J becomes one so now next zero will come here I is still less than equal to K now area of I is 2 so this condition comes out to be false this condition also comes out to be false now this condition comes out to be true so it means we need to throw this two to K and take its value so when we will perform swap one will come here and two will go there and now two is at its correct position here so we'll decrement K so K becomes 4 also friends here you can see that when we are swiping with K we are only decrementing K we are not moving I ahead because when we are swiping it with k whatever value is here there could be three possibilities it can be zero it can be one or it can be two so we are not sure that what value we will encounter here so then therefore we are keeping I at the same position but when we are swiping it with J we know that there could be two possibilities zero or 1 so when we encounter one we know that we have to move I by One Step but when we encounter zero it means that I and J are pointing to the same index and when we will do swap zero will come at same position only and then we will move both the pointers together ahead so the maximum time the value which we swap between I and J is one so therefore after this swap when I will see that here it is one it will simply move ahead by one position but with K we don't do this because we can get three possible values 0 1 and two and we are not sure that what values it is getting sved with now again I is less than equal to k a of I is 1 so this condition comes out to be false now this condition comes out to be true because area of I is equal to 1 and we know that when we encounter one we simply move I by one position because one is already in the middle area so we simply increment I by 1 position I becomes three I is still less than equal to K now array of I is two so this condition is false this condition is false and this condition will be true so when we encounter two we simply throw it to K and take its value so two will come here and zero will come here like this now this two is at its correct position so we will decrement k k becomes 3 now here I is equal to K so this condition is still true array of I is zero so this condition will be true when we will encounter zero we need to throw it to J and take its value so that zeros are at the start so when we will do swap so Z will come here and one will come here it means Z is now at its correct position and as we have encountered one here we first move I by one position so I becomes four we have placed zero at its correct position so we'll move j also by one position J becomes two so friends here can see now this condition comes out to be false because I is actually greater than K so so this while loop will terminate and here you can see that we have sorted the array in zeros ones and twos form where zeros are at the start ones in the middle and twos at the end so friend this is all about the algorithm we usually take the help of three pointers i j and k i and J starts from zeroth index K starts from the last index when I will encounter zero it will simply swipe it with J because J's responsibility is to place zeros at the start when I will encounter two it will simply swipe it with K because the responsibility of K is to put two at the end and when I will see one I's responsibility is to place ones in the middle and as I is already in the middle it will simply move ahead so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss about a basic introduction to quick sort in this video and in upcoming few videos we will discuss completely about quick sort so quick sort is a sorting technique where we get a collection of elements and we sort them in ascending or descending order so in quick s here if you see when we discussed m s we saw that it was a divide and conquer algorithm so by divide and conquer we mean that let's say if we are given a complex problem we try to divide that complex problem into smaller sub problems and when those smaller sub problems are not further divided we try to conquer them and when we conquer each and every smaller sub problems we reach to the solution of our original problem so quick sort is also divide and conquer algorithm it involves three steps the first step is the pivote selection so in pivote selection what we do is we pick an element from the array and Mark it as pivote now this pivote element can be the first element last element or any random element we just take any element and Mark it as p good so here let's suppose we are given this array and we want to sort this array using quick sort so as we discussed the first thing we do is we take a pivote element now this pivote element can be the first element any random element or the last element so we can take any element as pivote in this tutorial we will take the last element as our pivote vot so here the last element which is at index 8 the value is three so this is our pivote so this is the first step we take a pivote and we can take any element as our pivote now after taking a pivote what we do is whatever the element we have taken as pivote now we actually partition the array so by partitioning we mean that we reorder the array such that all elements greater than pivote comes after the pivote and all the elements smaller than pivote comes before the pivote the elements equal to pivote can go either side of the pivote so whatever the pivote we took which we saw in our previous slide it was three so then we partition the array in such a way that all the elements which are greater than pivote comes after the pivote and all the elements which are smaller than pivote comes before the pivote so we are actually reordering the array and the elements which are equal to pivote can go on either side it can go on the left side or on the right side so why we are doing this partitioning is this is the important step after we perform the part partioning the pivote is actually at its correct sorted position now what it means is let's say three is the pivote and these are the remaining elements so all the elements greater than pivote should come after the pivote and all the elements which are smaller than pivote should come before the pivote so here three is the pivote so now we'll check 9 is greater than pivote it comes here because as it is greater than three we know that all the elements which are greater than pivote will go after the pivote minus 3 is smaller than 3 it comes here 5 is greater than three it comes here 2 is lesser than three it comes here 6 is greater than three it comes here it comes here - 6 comes here 1 comes here and three is the pivote so it it is at this position so here you can see these are all the elements which are smaller than pivote and these are all the elements which are greater than pivote we are not concerned about the order of the elements here it's - 3 then it is 2 then it is - 6 so we are not concerned about the order here here it is 9 5 6 8 like this we are only concerned about the partitioning of this array in such a way that this is the left part which is smaller than pivote and this is the right part which is greater than pivote so why we are actually doing this partition here you can see I'll just remove this so when we actually partition the array based on what we discussed here you can see that three was our pivote all the smaller elements are just before the pivote and all the greater elements are just after the pivote and it can be in any order but here you can see that after this partitioning one unique property with this pivote is let's say this is low index and this is high index and this is any jth element so after this partition in this array from low to J minus one which is this portion is less than equal to area of J which is our pivote which is less than equal to J + 1 to high like this so when we do this partition this holds true and if you see when we sort this array so this is the sorted array so the elements are arranged in ascending order but here you see that the difference between this partitioning and the sorted arrays the pivote after the partitioning and after the Sorting doesn't change its position it's actually at its correct position after the first partition so here if you see three was our pivote after partitioning came at index 4 and if we sort this array you will see that in the sorted array the pivote doesn't change its index it will still at be at index 4 so this is one critical information about quick sort that it partitions the array and all the elements which are smaller than pivote comes to the left and all the elements which are greater than pivote comes to the right but this pivote after partition is actually at its correct position even after the array is sorted so this is the second step of quickshot the partitioning step moving ahead now here you saw does this pivote and this partitioning it is actually the Divide part of the algorithm where we are actually reordering the array in the partitioning step and now how we will conquer this is based on this recursion step whatever we did above now we recursively apply the above steps on the subarray formed on the left side of the pivot and on the right side of the pivote so these two steps we will apply on all the elements which are lesser than pivote and on all the elements which are greater than pivote recursively so this step which we discussed that after this partitioning the pivote is at its correct sorted position we don't touch the pivote after the partitioning we take the left part of the pivote we take the right part of the pivote and we apply the above steps recursively on the left side and on the right side so here pivote in the sorted AR at its correct position like this but when we do the first partition this one particular element is sorted here you can see in the sorted array pivote doesn't change its position and it is at its correct position so we can think from the first partition we have sorted one element and now when we are discussing the recursion part the third step what we do is we take the left side of the partition we take the right side of the partition we leave the partition as it is at its correct position now we apply the same steps of choosing a pivote and then partitioning on the left side of the array and on the right side of the array so this we keep doing recursively till all the elements are at its correct position first partition gives one sorted element if we do this recursively with the left part and with the right part there will be a time that all the elements will be properly sorted and they will be at its correct position so the recursion step is important so these are the three important steps in quick sort pivote selection partitioning and then doing the recursion of these two steps on the left side of the pivote and on the right side of the pivote and when this recursion will end all the elements will be properly sorted and they will be at its correct position so this was the basic introduction of the quick sort at a high level in our next video we will see how we do this pivote selection and the partitioning and after that we will see that how this recur help us in sorting the array taking the help of this first two steps and applying them recursively so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss that what is quick sort partitioning in the part one of this video we discussed a basic introduction about quick sort so in this video we will be discussing what is quick sort partitioning so friends in our previous video we discussed that quick sort is a divide and conquer algorithm which basically involves three steps pivot selection partitioning and recursion in pivote selection we actually pick an element and Mark it as payot the payot element can be the first element last element or any random element from the array and the second step is the partitioning step where we reorder the array such that all the elements greater than pivote comes after the pivote and all the elements smaller than pivote comes before the pivote and the elements which are equal can go on either side of the pivote so usually in the partitioning step we actually get a left part and the right part and in the middle we have pivote so once the partitioning is done pivote is somewhere in the middle also we discussed that after this partitioning the pivote is at its correct sorted position so here you can see at whatever index pivote comes after the partition if we sort this complete array the pivote will lie at the same index only so it means means after the partitioning one of the element is sorted so in the recursion step we apply this pivot selection and partitioning recursively in the left side and in the right side and we keep on doing that till the complete array is sorted so in this video we will see that how we do pivote selection and partitioning so let's say we are given with this array so here we can choose any element as our pivote but here choose the last element as our pivote so three is the pivote and as we discussed in our previous video that after we partition and reorder the array in such a way that all the elements smaller than three comes before three and all the elements greater than three comes after the three so it would look something like this that this part is the left part and this this is the right part and this is our pivote so if you see when this array will get sorted completely so this is the sorted array so here you will see that the pivote after the partition was at Fourth index and once the array got sorted completely it was still at the same index because when we partition the array in such a way that this condition holds true which will discussed in our previous video as well after the partition the pivote is actually at its sorted position so now let's see how this partitioning happens so here is the algorithm to partition the array so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update also please like this video and watch it till the end so here you can see the let's suppose we are given with this array of nine elements 9 - 3 5 2 6 8 - 6 1 and 3 so when we will call partition we are actually partitioning complete array it takes low and a high pointer so low actually starts from the zero index and high starts from the last index because we need to partition the complete array so low starts from zero and high starts from 8 so when we do partition of the array the first thing we need is the pivote so we can select the pivote as the first element last element or any of the random element in this array so here we will choose the last element as our pivote so array value at higher index which is the eighth index will give us our pivote so pivote is three this value which is at array of high now after this pivote selection what we do is we reorder this AR in such a way that all the elements smaller than pivote comes in the left part then comes the pivote and all the elements greater than pivote comes at the right part so this reordering is done by two variables I and J both are starting from low which is the starting index of our array or the starting range of the array from where we need to do the partitioning so I starts from low which is zero index and J starts from the low which is zero index so friends now we actually Traverse each and every element of this array and we provide a while loop where condition is I will Traverse till it is less than equal to high so friends the basic idea behind this algorithm is why we are creating two pointers if you see closely then we have this four pointers so usually from low to a minus 1 we actually have smaller elements and equal elements to pivote means all the smaller elements to pivote comes from low to J minus one including the elements which are equal to pavot from J to IUS 1 we will have all the greater elements to pivote and from I to high the elements are yet to be traversed so after every execution of while loop you can see these conditions and you can figure out that how this ranges works so at the start from I to high every element is yet to be traversed and low to J minus1 and J to ius1 goes beyond the array so therefore there are no elements in these ranges currently I is less than equal to I so this condition is true now we are trying to explore the first element which is nine so here what we do is in one of our previous videos where we saw that three number sort or how we can sort 0 and 1 we apply the small part of the same logic here as well so what we do is this N9 which is at array of I and this three which is our pivote there can be two possibilities area of I can be less than equal to pivote or area of I can be greater than pivote so if array of I is greater than pivote it means whatever value we have here is actually greater than pivote so here you can see we know that greater elements lies from the range J to IUS one so when array of I is greater than pivote what we do is we simply move I by One Step and if area of I is less than pivote we perform a swap between I and J and then we move j and I simultaneously so you will understand why we are doing this once we perform few of this iterations so at the start array of I which is N9 is greater than pivote so this condition comes out to be false so if aray of I is greater than pivote we simply Traverse I ahead I becomes one and we reach to index one so here you can see that why we actually traversed I one step ahead when pivote was lesser than array of I 9 was greater than three so greater element should Lie from J to IUS 1 so here you can see J to IUS one so this element so this is the only range which can help us to figure out that it has the greater elements to pivote you will understand more about these two ranges and these two points when we Traverse ahead now I is less than equal to high so this condition is true array of I is - 3 -3 is less than equal to pivote so this condition comes out to be true so when array of I is less than equal to pivote we simply swp the value with I and J index so after we perform swap we will see why we are actually doing that so these three steps I will be going somewhat fast because we have already discussed how we can do this spping so minus 3 will come here and 9 will come here now after this we minus 3s came here 9 has came here so here when array if I encounters a value lesser than pivote it simply throws it into this direction because from low to J minus one we need to put the smaller and the equal elements to the pivote so how I can throw it to in this direction is by swipping it with j and after we perform this swap we increment J and I both because this value is placed at its proper position that it is lesser than the pivote so now we'll increment J also so J becomes one and as these two elements are already exploded we will increment I as well I becomes two now our execution Point reaches here and here you can see that from low to J minus one we have smaller and equal elements to pivote so from low to J minus one which is this element this range are the smaller element elements to pivote from J to IUS one J to IUS one this element is in the range of the greater elements to pivote so these two condition are still holds good I still less than or equal to high so this condition comes out to be true and the while loop will execute now five is greater than pivote so this condition comes out to be false and once this condition comes out to be false we know that we need to Simply Traverse I ahead I becomes three so now here you can see this part is smaller elements range and this and these two elements 9 and five are greater than pivote so it is separated by J and I in such a way that from low to J minus one we have smaller elements from J to I minus one we have larger elements so therefore when array of I is greater than pivote we simply Traverse I ahead we do nothing and when area of I is less than equal to pivote it means we have found one element lesser than pivote so we simply throw it to the starting range and we simply shift the larger element range ahead so here initially 9 was here which was the larger or the greater elements to pivote when we did the swap nine actually shifted in this direction so that there could be a place for the elements which are smaller than pivot to come in this direction so now similarly we will do this for the rest of the elements from I to high the elements are yet to be traversed currently I is less than equal to high so this condition comes out to be true 2 is less than equal to pivote so this condition is true so now here you can see we know that two should lie somewhere in this range at the starting range and J keeps the track of the smaller elements from low to J minus one so at J we have one greater element and we need to put two somewhere here so that that this two comes at its proper position but here we already have nine so therefore we do this swap so that N9 can come here and this range of the greater element is still maintained in the middle somewhere and it simply shifts in this direction so I'll remove everything so now we'll do this swap two will come here and nine will come here 2 came here and 9 came here so the range of Greater elements simply shifted in this direction because we need to create a space so that smaller elements can come in this direction we'll increment J now we will increment I because this element which was here is actually being traversed so from low to J minus1 we have smaller elements range from J to IUS one we have larger elements range or greater elements range I still less than equal to high so this condition is true 6 is greater than pivote so this condition comes out to be false it means six is at its proper range we don't have to touch this we will do I ++ so I simply moves ahead I becomes five now this element also got into the range of Greater elements because from J to IUS 1 we have the greater elements to pivote I is still less than high so this condition is true so the while loop will execute now array of I which is 8 is greater than pivote so this condition is true therefore this condition comes out to be false and as array of I is greater than pivote we do nothing we simply Traverse I ahead I becomes six and this element becomes part of our greater elements range from J to IUS 1 I is still less than equal to high this condition is true now - 6 is less than 3 so therefore array of I is less than equal to Pivot now we need to throw this pivote in the left Direction and we know that J is actually keeping the track of that so this condition is true first we perform swap between I and J so that this minus 6 comes in this range and we simply shift the one of the greater element in this direction so we'll perform this swap using a temp variable so - 6 came here and 5 came here so after placing a smaller element at this spot we will increment J J becomes three because for the next smaller element this would be the right place so we increment J as well and as we have already traversed whatever the value was here at this index we will also increment I so I becomes 7 so here you can see this range from low to J minus one we have smaller elements from J2 IUS 1 we have greater elements to payot value of I is 7 so 7 is less than equal to high which is 8 Now 1 is less than equal to 3 so this condition comes out to be true we need to throw this one because it is lesser than or equal to Pivot in this direction so that it can come in this range we simply swap I and J so one came here and nine came here so here you can see when we are actually encountering a value lesser than pivote we are doing this Swap and putting that at the starting range and whatever value J is pointing from J to IUS one we have greater elements so at J we have one greater elements so we are simply Shifting the range which is greater than the pivote just ahead so 9 came here but still if you see the range is intact all the elements which are great greater than payot are in sequence the order will not be maintained but the range will be maintained so now after using this spot we will increment J J becomes four and we will increment I because this element is traversed and it got shifted here so we simply Traverse I ahead I becomes eight so here you can see from low to J minus one this range is of smaller elements J2 IUS one this range is of Greater elements now for the last time this V Loop will execute because I is equal to to high so here you can see that now we are actually encountering the pivote itself and this is one critical step because we need to put this pivote at its correct position somewhere between the range of smaller and greater elements to Pivot range so this equal to condition does that and it is very important so currently array of I is equal to pivote so 3 is equal to 3 which is the pivote and we can place this three because smaller and equal elements to pivote will lie from low to J minus one and J is at the spot which can take lesser or equal values to the pivote so three at index I will be sved with J so three comes here which is our pivote and six comes here which is the value greater than to pivote so after placing an element which is less than equal to pivote at its correct position using J we will increment J so that next element can come here but as there are no elements but still we do this j++ so J becomes five and we will increment I because we are done with this element so I becomes 9 which goes out of the boundaries of this array so this condition comes out to be false because value of I is 8 and I is 9 so I is actually greater than high so this Val will terminate and here you can see that in quick sort partitioning when we do this partitioning at the end we need to return the index of the partition that from which index the partition is happened so here we can see that from low to J minus one we have smaller and equal elements to pivote so I will redraw this low to Jus one smaller and equal elements to pivote J to i - 1 so I value is 9 so J 2 i - 1 which is still eight these are the elements greater than pivote and from I to high we have traversed all the elements so if You observe closely J is actually pointing to a place where the next smaller elements to Pivot will come so we will simply return J minus one because we know that from low to J minus one we have element smaller and equal to pivote so three comes here which is at index 4 so we will return the index of the pivote so in this partition whatever value we written is actually the index of the pivote after the partitioning which is J minus one so index 4 will be returned so This Is How We Do partitioning and this partition method is very frequently used in the quick sort similar kind of logic is used when we do sorting of 0o and one or putting even or odd integers in certain sequence or we sort the three elements 0 1 and two so for 0 and 1 this code is pretty much similar so this partitioning logic which you are seeing here is very important for many of the algorithms and this traversal with this range is very important to understand because the same logic applies to many of the algorithms so we will see the partitioning logic how it applies to quick sort in our next video we will see that how this recursion happens where we apply the same logic of partitioning in the left side of the array which have smaller elements and the right side of the pivote which have the greater elements so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss about quick sort recursion in part two video quick sort we discussed that how we can partition an array so in this video we will see that how we can perform quick sort recursion so in the previous video we discussed about the pivote selection that we pick an element and Mark it as pivote the pivote can be any random element it can be first element last element or any random element now based on what we choose as our pivote we do the partitioning we reorder the array such that all elements greater than pivote comes after the pivote all elements smaller than pivote comes before the pivote the elements equal to pivote can go on either side of the pivote and once this partitioning is done based on the reorder of the array the pivote is actually at its correct sorted position so this we already discussed in our previous video so in this video we will be looking into the recursion part where after partitioning the array we perform these two steps the pivote selection and partitioning recursively on the sub array formed on the left side of the pivote which has the smaller elements to pivote and on the subarray formed on the right side of the pivote which has the greater elements to pivote so here about two steps we perform recursively on the left side of the pivote and on the right side of the pivote so let's see at a high level how this recursion looks so let's say we want to sort this array using quick sort so here you can see that this is a small piece of code which does the Sorting it takes in an array and it takes in a Range that from which index to which index we need to do the sorting and here you can see that the first step we are doing is the partition step and once once we get the partition index now we have two arrays one is on the left side of the partition and one is on the right side of the partition so we recursively call the S method which is the same method from low to P minus 1 which is the left part and from p + 1 to high which is the right part and this happens recursively because the method is called itself again and again after the partition we are actually rearranging the array in the partition method in such a way that the element present at the partition index which is the position of our pivot that element is correctly sorted and placed at its proper position so with one partition we can get one element and place that element at its correct position such that that particular element is sorted and we will keep on doing this recursion till low is less than high so this is our base case so at a high level let's see how this recursion looks in our next video we will see the stepbystep demonstration of this quick sort algorithm but for time being we can just see at a high level that how this recursion looks like so here at the start we need to sort this complete array so this will be our low and this will be our high now low is less than high we call the partition method so in the partition method we take the last element as our pivote like this so three is our pivote now after this partition method will end we get the index of the element three that where it belongs so in our previous video we saw that how we can perform this partition and we took the same example so in the first partition you will see that three comes at index 4 and in the partition the array is rearranged in such a way that all the elements lesser than pivote comes in the left side all the elements greater than pivote comes on the right side so here we are doing The Logical division of the array and we are partitioning into two parts left and right so we are not breaking the array it's just for the demonstration purpose that it looks like this if you see the index from 0 to 3 we have smaller elements from 5 to 8 we have elements greater than the pivote so this is the pivote index now after we get the pivote index if we sort this array directly you will see that in the sorted array 3 will be always at index 4 it means when we we perform this partition one of the element is sorted and it is placed at its correct position so once it is placed at its correct position we don't touch this element now what we do is we call the S method on the left side recursively so it goes deep down like this and the range we took is low to P minus one so p is the pivote and this is p minus one so now we will call the sort by taking this left side only this four elements and this will happen recursively low should be less than high this would be our base case so here when this s method will be executed for this left array you can see that this short metal will be executed again low will be the same but high will become P minus one so this would be our high low is less than High now we will again call partition method we will pass in the array we will pass in low and high so now in the partition method only these four elements will be reordered because we are providing the range of low and high in the partition at the start low and high were the complete range of the array from 0 to 8 now this partition method will only partition 0 to three so in the partition method we will first choose the pivote element which we have discussed that we choose the last element now we need to do the reordering such that all the elements lesser than one should come on the one side and all elements greater than one should come on the other side so here we will see that the partition method will reorder the are in such a way that it looks like this this much part are the elements which are lesser than pivote and this much part are the element which are greater than privot which is 1 but here we will see the index which we get is two because it Returns the final position of the pivote so index 2 will return here in the first partition index 4 was written so based on this P minus one we took the left side of the array and we did the partition again so now here if you see if we sort this array completely you will find that three is at Fourth index which is sorted and after the second partition one will be at second index so this element is also sorted so now we don't touch one here if you see we again go on the left side from low so this was our low and this is our p and this is our high so we again call sort method from low to P minus one which is we are taking the left side of the array so when this s method will be called again again low will be at the same spot but high will become this spot so it means now we are actually picking up this two elements and we are trying to sort them and we are trying to apply this logic so this will be our low and this will be our high low is less than high so it means we have two elements so we can again do the partitioning of the array from low to high so in the partition method we will take the last element as our pivote and now we will partition the array in such a way that all the elements lesser than minus 6 will go on the left side and all the elements greater than minus 6 will go on the right side so this partition method will reorder only these two elements now because we are providing the ranges and it will touch the array into these ranges only so it looks like this so as there are no elements which are smaller than minus 6 so - 6 will be the only element on the left side which is at index Zer and -3 is greater than - 6 so this will lie on the right side so friends here you can see that now this is our low and this is our pivote index so after we get the pivote index we will again call sort on this one element we will try to sort its left part from P minus one so p is at zero index if we do p minus one it will go minus one so here if you see when we partition the array pivot was at zero index it is the only element now so on the left side of pivot we have no elements so if we call S method again passing in low as zero and high as P minus one so it will take the value of the new high as minus one so here we will reach the base case and we will simply return from this method because low value is zero and high value is minus1 so therefore we can't further divide Min - 6 and at whichever index Min - 6 will be there that will be the properly sorted position for the element minus 6 so now this method is done because when we call S again we will reach this base case and we will return so this method will be done so now this s method will be executed and we go to the right side of the pivote it means now we are taking in the elements which are greater than - 6 which is the only element minus 3 so p + 1 p + 1 will be our new low this will be our low and and high will remain the same index so here if you see we will again encounter the base case low is actually equal to high so it means we can't divide from low to high further down so based on this base case this short method will end and the call will reach here again and the S method which we called from here this will also get end so minus 3 will be also at at its correct sorted position like this so here with these two sort methods we are going in this direction and then we are going in this direction so with this sort we went to this direction this is sorted and with this sort we went to this direction which is sorted so we will return back to the left side and here you can see when we'll return back here when we had called sort on this part we went in this direction and as we are returning back from here so we will return return from here like this and now when these two elements are sorted we will go in this direction to sort the greater elements to this pivote because we are doing this algorithm recursively so first the left side is done and once that left side is done we go on the right side so this side is done completely here now we go on this side so here two is the only element left so this will be sorted because the base case be fulfilled for this element low and high will be at the same spot because this is our p and if we are going on the right side we do p + 1 so p + 1 will be the index 3 which will be our low and high is already at index 3 so this is sorted like this so now execution point will reach back here and here you can see left side is not properly done so it will go back here and now we perform the same steps recursively on the right side of the elements which are greater than three which is our index 4 so now we perform the same step on this right side so if we are going on the right side we are doing p + 1 we are going on the right side the low will be from p+ 1 to high so this is p this will be our low and this will be our high because this High has not changed its value so now we will partition it again based on what we saw here so six will be over the pivote and now when we will partition it it would look something like this so six is properly sorted now we go on the left side first so f is the only element left so it will encounter the base case this is our p and this is our low so for the left side if we do p minus one to take all the elements which are lesser than six this will become our high and as high is equal to low we will return from the recursion and five will be at its correct position so we go back like this and then we try to sort the right side so we call the recursion again by taking p + 1 to high so this was high like this and if we do p+ 1 this will be our low now so now we are actually partitioning two elements so we take N9 as the pivote we do the partition so where pivote lies at the E index there is only one element which is lesser than pivote which is on the left side of the array and there are no element ments which are greater than pivote so after the partition at whichever position the pivote lies this is the properly sorted position for element 9 and we are left with only one element so we first go on the left side like this we take from low to P minus one because if we do p minus one we'll get the left side range so this will become our new high and as this is the only element left low is equal to high so we can't divide or partition this piece of sub AR further so it will be also at its correct position like this so if I remove everything so here you can see that we are performing the recursion on this array recursively and we are doing the partitioning and with each partition one one element is getting sorted and placed at its correct position so if you try to combine all these indexes you will see that if we sort this array the array would look like if I just plot it here it will look like first - 6 - 3 then 1 2 3 5 6 8 and 9 so if you see that this would be our finally sorted array and if you see the indexes of all the elements from 0 to 8 you will see that at 0 we have - 6 like this at index one we have minus 3 sorted index two we have one at index 3 we have two index 4 we have three at fifth index we have five sixth index six seven index we have eight and at the eth index we have nine so here you can see that how this recursion and this partitioning is helping us to perform the quick s so friends here if you see at the start we took complete array we took a pivote we did the partitioning all the elements lesser than p were on this side and all the elements greater than pivot were on this side then we recursively took the left part we took the pivote and we did the same steps like this then we took the left part again we did the same steps and finally we got - 6 and - 3 at 0 and 1 index which are sorted and after taking this left and right part and sorting them this left part was done properly then we picked the right part of this pivote and this was sorted and after we sorted this all the elements were done for the first left sub aray then we went to the right part and we did the same steps again we first went on left then we went on the right we first went on the left then we went on the right and at the end you see all the elements are at their proper indexes so if you sort this array you will get this array so friend this was all about the quickshot recursion if you didn't understand any of the recursion logic here in our next video we are going to see the stepbystep demonstration of the quickshot algorithm there it will make sense that how this recursion is happening where the sord method is again calling this s method two times after partitioning we go on the left side first and then we go on the right side so we will understand this recursion in our next video with a detailed demonstration I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video of quick sort we discussed about the quick sort recursion so now in this video we will see the stepbystep demonstration of the quicksort algorithm and we will see that how the algorithm Works via an animation so this is the quickshot algorithm and we will see the step by-step demonstration of the algorithm so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never never miss any update so in quick short algorithm we have this sort method which takes in an array which you want to sort and we pass basically a range that from low to high we need to sort so at the start let's say we want to sort this array having six elements 5 2 0 1 6 3 so when we will call sort method we'll pass in the array the low will be zero and high will be array. length minus one which is the last index so low is zero which is pointing to 0 index high is five which is pointing to the last index so we are telling that we need to sort this array completely from zero index to fifth index and here you can see that this s method is recursively calling this s method again here and here so in order to demonstrate the the recursion we are using this call stack which will have the method calls and the state of the method stored in low p and high so when this sort method will be called there will be one method on the call stack by name sort low is at zero index high is at fifth index and P is the index of the pivote which we will be calculating here moving ahead so here we know that quick sort is divide and conquer algorithm so here we actually divide this complex problem of sorting into smaller sub problems which means that we are dividing this array into two parts and we keep on dividing the array into this recursive sort methods based on Range low and high so when low will be equal to high or low will be greater than high when low will be equal to high so it will be something like this that low is equal to high it means we can't further break down the array because it has only one element so therefore when this condition will arrive we need to Simply break from this recursion because this s method is recursively calling this s and it keeps on going so when low will be equal to high or greater than high then we need to tell recursion that we have reached our base case and we need to stop the recursion So currently low is less than high low is zero and high is five so this condition comes out to be true so friends in our previous video we discussed that how we actually do the quick sort we first do the pivote selection where we pick up a random element from an array and then we actually partition the array and we partition the array in such a way that the elements which are smaller than the pivote usually lie on the left side and the elements which are greater than pivot usually lie on the right side and the equal elements can go on either side so here this is the first step we actually call the partition method we pass the array we pass the range from low to high So currently we are telling that we need to partition this complete array and in this partition method we actually do the pivote selection and reordering of the array so this method we have discussed in our previous videos in a greater detail you can watch that video to get more understanding but here also we will see that how this partition works so when we will call partition method we are leaving this sort method so the execution point will leave the sort method and the partition method will be on the call strike so before we leave this s method we need to store the state of this s method that low was at zero and high was at fifth index and as we are leaving this short method we need to keep the track of line number because once this partition method will end we need to begin this short method from line number three only because we are leaving this short method at line number three so here we will update the line number three like this which tells that we are leaving this s method at line number three and when we will come back to this s method we will start our execution from line number three and when we will start our execution low will be at zero and high will be at five so we are simply storing the state here so now we'll see this partition method with this array low as zero and high as five so we are partitioning this comp complete array we have discussed this method in Greater detail in our previous videos you can watch that video so that once we go through it again you will get more better understanding so first we do the pivot selection we can choose any random element from the array as our pivote we can choose the first element or any element in the middle or the last element so here we choose the last element as our pivote which is denoted by the end of this range so pivote becomes array of high which is three so this is our pivote and after this pivote selection our job is to do this partition elements lesser than three will go on one side which is on the left side elements greater than three will go on the right side and the elements which are equal to payot can go on either side so when we perform the partition we take the help of two variables I and J here I and J both starts from low currently low is pointing to zero index so we are not starting I and J from zero index we always start it from the low index because currently as we are partitioning complete array lowest pointing to zero there could be a chance that we only need to partition these three elements so at that moment low will be a third index so we need to Partition from third index to fifth index so therefore we create two pointers I and J both starting from low I is zero because low is pointing to zero J is zero now as we need to partition we need to provide a while loop where we Traverse each and every element of the array using the iterator I it goes till it is less than equal to high so this is very important algorithm and it is used in many problems here what we do is we have this four pointers and once we partition the array it looks something like this smaller and equal elements to pivote are on the left side then we have the pivote and then we have the elements greater than pivote so this is the ranges and if you use this four pointers the range varies like this from low to J minus one we have smaller elements or equal elements to pivote from J to IUS one we have the elements greater than pivote and we have discussed this in Greater detail in our previous videos as well from I to to high we have elements yet to be traversed so at the start we need to Traverse every element so from low to J minus 1 and from J to ius1 we don't have any elements because all the elements are yet to be traversed therefore we have provided this condition that this V Loof will run till I is less than equal to high so we'll see how this algorithm works and also we need to keep this if condition in mind so here when we are partitioning we need to compare each and every element with the pivote and if it is less than pivote the first thing we do is we simply swipe the values at I and J index in the array because as this element is less than equal to pivote it should come at the starting range because we need to partition it that way so we will see how this three steps work and if the element is greater than pivote we do nothing we simply leave the element there and we Traverse I ahead so so this condition is true I is less than equal to I so in the if condition we check whether area of I is less than equal to payot or not so we are simply checking whether 5 is less than three or not so 5 is greater than three so this condition comes out to be false so when array of I is greater than pivote which is our case we simply leave that element there and simply Traverse I ahead so I becomes 1 I still less than equal to high now area of I which is 2 2 is less than 3 so this condition comes out to be true and once this condition comes out to be true we know that we need to swap the values at I and J index it means we need to swap 5 and two so here why we are doing this swap is we need to partition the AR in such a way that smaller element should come at the starting range then our pavot should come and then the elements greater than pavot should come so when array of I is less than equal to pivote we simply throw the element which is at aat index to J index and take its value so when we will do this swap I will go over these steps quickly five will come here and two will go there so two came here and five came here and we know that now we need to increment J and I both so why we are incrementing J is because J has placed one of the smaller elements here so this space is occupied so J moves ahead J becomes one one and we will simply Traverse I also ahead because this element is also explode so I becomes two so friends one thing to note here is irrespective of any of this condition is met we simply Traverse iead in both the cases so therefore it is written here now I is less than equal to high array of I which is zero it is less than 3 so this condition comes out to be true so we need to throw 0 to J and take its value by doing this swap so 0 goes here and five comes here so friends here you can see that as 5 is greater than pivote the elements which which are greater than pivot they are actually shifting in this direction but the element which are lesser than pivot we are simply throwing it to J to put it at that particular index and J actually holds one of the greater element to pivote because from J to IUS one we have the elements greater than pivote so J is actually pointing to one of the greater elements than pivote and once this swipe is done we are simply taking a greater element and shifting it ahead and by doing this swap we are creating one space here so that the elements which are lesser than pivote can come here so therefore we do the swap we throw whatever the element is at the I index to J and take its value so this spot is filled now properly so we will increment J so J becomes 2 we will increment I I becomes 3 this condition is still true I is less than equal to high 1 is less than three so this condition is true so we perform these steps again so we are performing this swap using this temp variable so five comes here and one goes there and after filling this position with a value smaller than pivote we move j ahead so J becomes three and we have explored the arror till this point so we move I also ahead I becomes four so friends here you need to keep watch on these two ranges from low to J minus 1 we have the elements smaller than pivote which is true from J to IUS one we have elements greater than pivote so this is j i minus one so five is actually greater than pivote so these both the conditions are true when we are doing these steps now I is still less than equal to high so this V Loop will execute array of I which is six is actually greater than pivote so this condition comes out to be false so when array of I is greater than pivote we know that this element is greater than pivote and it is at it proper position so we don't touch this element we simply move I ahead like this so still you can see from J to IUS 1 we have elements greater than pivote so therefore when we encounter a value greater than pivote we simply move ahead and when we encounter a value lesser than or equal to pavot we simply throw it into this direction so that we can perform a swap between I and J now I is actually equal to high so this Loop will run one more time and now here you can see our pivote and array of I are the same elements so why we are running it one more time is because smaller than or equal to pivote so we have got a value equal to pivote so we need to make it lie in the range of low to J minus one so J is holding a value greater than pivote so we do this swap here so five comes here and three goes there so it means our pivote has landed into its correct position then we will increment J J becomes 4 and we will increment I I Bec become six so as I has become six this while loop will terminate because value of I is five so friend this partition method does two things first it Returns the index of the pivote which is J minus one which is three and second it takes in the original array and reorders it such a way that all the elements smaller than pivote are on the left side and all the elements greater than pivote are on the other side so when this method will end we will return return J minus one which is the index of this pivote from where this partition has happened so the execution point will reach to this s method and the array has been reordered we have left the S method at line number three so we will start from line number three three this partition method has written a value of P which is the index of pivote which was three so value of P will be three like this here so this is what we saw in the partition that all elements smaller than pavot are in this side and greater than pavot are on this side so friends here you can see that if I sort this error directly the sorted array would look like 0 1 2 3 5 and 6 and here you can see that once this partition is done when we are putting all the smaller elements before the pivote and all the greater elements after the pivote so when we sort this array completely you can see that the index of The pivote Remains the Same three is at index 3 and after sort also it will be at the index 3 because here it's 0 1 2 3 4 5 index so it remains at the third index only so this is one important step in the partitioning that after the partition pivote is actually at its sorted position so now what we do is we don't touch this pivote because it lies at its proper sorted position now our task is to perform this pivote selection and partitioning on the left side of the pivote and on the right side of the pivote and de to recursively so this s method will keep on calling itself till the base case is reached so now we call the S method again and this time we only take this three elements and we try to to sort them so here we are calling the sort method we are passing in this array low value will be zero only high value will become P minus one because we are calling this short method with P minus one it means we are taking it this range this is p so this will be P minus one so when this s method will again gets called our high will become P minus 1 so as we are leaving this s method and we are calling this s method so first we will update the line number here and we are storing the state of the low p and high so we update line number four here and we leave this s method and again call the sort method so this short method will be called with lowest zero and highest P minus one so this was our P previously p - 1 which is 2 so here now we are doing the sort from low to P minus one so this is the range of our array which we need to sort now so high becomes two P minus 1 which is 2 so our new high became two low is less than High so now we'll partition only the left side of the pivote which is this three elements so we will leave at line number three this short method so this partition method will be executed again and now we are not taking in complete array we are taking the array from range low to high which is 0 to 2 index like this so This partition method will only touch this three ele elements so first we select the pivote which is the last element of this range so array of high will become our pivote so one becomes our pivote we start the partitioning with a value of I and JS low which is zero and as we already discussed how this algorithm works we'll go over this quickly we need to keep these ranges into mind and these two conditions into mind so I is less than equal to high this V Loop will execute array of I which is two it is greater than pivote so we do nothing we simply move ahead we do I ++ I becomes 1 I still less than I now aray of I which is zero it is less than equal to P it means we need to throw it to J and take its value so we do this y swap so 2 comes here and zero goes there so zero goes there and as JS filled this position properly we'll increment J J becomes 1 will also increment I I becomes two I is actually equal to high so this Loop will run one more time to put this pivote at its correct position now one is equal to Pivot so we do this swap again so two comes here and one goes there then we increment J J becomes two and we increment I so I becomes three and this while loop will terminate because value of I is 2 and J is 3 so 3 is not less than equal to 2 so here you can see that now we need to return the index of the pivote which is at J minus one which is this and here you can see that when we did partition of these three elements these are actually element which are lesser than pavot which is one and these are the element which are greater than pivot which is two So currently it has only one one element so we have reordered the array and we are returning the pivote as one so execution point will reach here we know that we have left at line number three so we start from here this method return return the value of pivote as one so P becomes one like this so friends we know that after doing this partition we recursively call the S method again and this time we go from low to P minus one which is the left side and then we go from p + 1 to high which is on the right side so first we go on the left side so here you can see this recursion is happening till the array is getting divided so now when we will leave this short method we will first update the line number here which is four and then we will call this s method where low will be zero and the value of high we passes P minus 1 so P minus1 will be zero so this value will go to high and this value will go to low in the next short method so we have updated the line number and we have called this s method again so it looks like this that this low which was Zero is zero P minus 1 which is zero index so high becomes zero so it looks like this so friends here you can see now low and high are pointing to the same index it means that we have left with only one element and we can't divide this array further down or partition this array further down because we have only left with one element so therefore we have reached our base case so low is equal to high so this s method will end and this s method will be removed from the call strike and the execution point will reach here back so it looks like this this method was removed from the call stack and execution Point reached here we know that we left this s method at line number four so we start from line number four and when we had left this s method low was at zero P was at 1 high was at two so we position them back to their respective indexes high was at two P was at 1 and here you can see that we are done with this left part now so this short method is done and now we go on the right side so we call this s method again now this time we are passing the value of lowest p + 1 so p is 1 and P + 1 is 2 so when we go on the right side the value of low changes and when we go on the left side the value of high changes here you can see if you're going on the left value of high changes if you're going on the right value of low changes so now we will leave this short method we first update the line number here that we are leaving at line number five and we are calling this short method with p + 1 as our low which is two and high as two so there will be one more method on the call stack with lowest two and highest two so it would look something like this this moving ahead here you can see that now we are actually partitioning the elements which are greater than P which is only this element two which is only one element as low is equal to high it means we have reached our base case and we are telling to this s method that please stop the recursion and go back so this method will be removed from the St because we can't divide two further down and the execution point will reach here so when this s method was left we had left at line number five so we start from line number five and at that moment value of low p and high are 0 1 and two so we give them their respective indexes so it was like this and and now after executing line number five there are no more lines left to be traversed so this s method will also end and the execution point will reach to this s method because this s method was actually being called by this s method so this method will be removed from the call stack and when we had left this s method we had left at line number four so we start from line number four and at that moment value of low was Zero p was three and high was five so we give them their respective indexes so this was the state when we had left this s method so here this short method is done it means so it means that when we had done our first partition the pivote came out to be index 3 and in this s method we went to the left side of the pivote and we did the sorting and here you can see these three elements are sorted so we had done with this method now our task is to go on the right side call sort method again recursively we pass the value of low as p + 1 because we need to now go in this direction and high Remains the Same so here we are leaving this short method we'll update line number here which is five and we are calling this short method passing in low value as p + 1 which is 4 so it looks like this low becomes p + 1 which is 4 so it looks like this low is less than high it means we have two elements it means we can divide this two elements further down so we call the partition method again we passing the range from low to high we are telling we need to partition the array of these two elements only so this is our range so when we are calling this partition method we first update the line number here and we have stored the state already in low and high so line number three comes here we leave this s method we call this partition we need to partition from low to high that is in this range we are not touching this side because we have already done the sorting and partitioning of these elements so we are now only touching these two elements array of high will be our pivote so first we are doing the pivote selection so five becomes our pivote we create two pointers I and J which start from fourth index and then we perform the same step which we have discussed already we provide a while loop and the condition is I should be less than equal to high we need to keep four things in mind these two ranges and these two conditions so array of I which is six it is greater than pivote so we simply Traverse ahead we do nothing we do I ++ I becomes 5 I is equal to high so this condition is true now array of I is five and five is our pivote as well so therefore when array of I is equal to pivote we need to throw whatever value is at ath index to J and take its value so we first perform the swap so six comes here and five goes there we have placed five at its correct position which is our pivote position so we increment J and then we increment I so now this while loop condition comes out to be false because value of I is six and high is five so we simply return the pivote index which is at J minus one so J minus one which is the fourth index so we return four from this partition method and we have also reordered the array in such a way that all the elements lesser than pivote are on its left side So currently there are no Elements which are lesser than pivote because we are not touching this side we are touching from low and high so from low to J minus one low to J minus one we have element smaller than or equal to pivote which is true and from J to I which is 6us 1 which is only this El having a value greater than pivote so we simply return index 4 from here so the execution point will reach here we had left this s method at line number three so we start it from line number three the partition method returned the value as four we have placed four here so P becomes 4 now we go on the left side of the pivot from low to P minus 1 so here you can see low and P are pointing to the same element so when we call this s method we first update the line number which is four and then there will be one short method on the call stack so here when we had left this s method we called this s method from low to P minus one so when we did P minus 1 our high became three so here you can see that low is actually greater than three so it means we have reached our base case and which makes sense because there are no elements on the left side of the pivote to be divided further down so we simply return from from this method and the execution point will reach here we had left at line number four so we start from line number four and low p and 5 had values as 4 4 5 so we give them their respective values 4 4 and 5 and now we go on the right side of the pivote which is at p + 1 to high so p + 1 is index 5 so first we update the line number here because we are leaving this sort method and then we are calling sort so there will be one more method on the call stack with p+ 1 as our new low which is five and high remains five only so it looks like this so here we can't divide this six further down it means we have reached our base case low is actually equal to high so this if block will not be executed so the condition in if loog comes out to be false and we simply leave this method so this method will be removed from the call stack and the execution point will reach here we had left this short method at line number five so we start from line number five and at that moment low p and high at four four and fifth index so we reassign them their indexes like this and as there are no more steps left to Traverse for this s method so this sort method will also be removed from the call stke and the execution point will reach you here so when we had left this s method we had left at line number five so we start from line number five and at that moment low p and high were at 0 3 and fifth index like this and also friends here you can see that after line number five we have no statements to execute so this s method will also be removed from the call stack so friends here you can see after after every method got removed from the call stke we have actually performed the Sorting of the array we have used the quick sort and we have sorted the array so friend this was all about the step by-step demonstration of quick sort algorithm where this s method recursively calls this s method one is when it goes on the left side of the pivote which is the smaller elements and one when it goes on the right side of the pivote which are the greater elements to pivote in this partition method we do the pivote selection and reordering of the array in such a way that smaller or equal elements are on the left side then our pivote comes and then the elements greater than pivote comes so this steps we do recursively till all the elements are sorted so friend this was all about quick start algorithm I hope you must have liked this video in case if you are new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we will be discussing a coding problem squares of a sorted array in Java so if you see in this problem we are given an integer array which is sorted in ascending order so here you can see this is the input -4 -1 0 3 and 10 so it's sorted in ascending order now what we need to do is we need to return an array of integers such that we need to square them and whatever is the outcome we need to Simply return that array so for example the output would be 0 1 9 16 and 100 so how this output came is after squaring each and every number you will see the array will become Min -4 into -4 will give us 16 -1 into -1 will give 1 0 into 0 will give 0 3 into 3 will give 9 10 into 10 will give 100 so this is the array which will be generated after we Square each and every element now the complexity part is we need to sort this array and return from the method so after we sort this part it will become 0 1 96 100 so Friends The Brute Force approach would be we simply Square the array so it will become like this 16 1 0 9 100 and then we again use arrays. sort we pass in the array and we get this result array but this is a Brute Force approach which is not very efficient so if you see at the last step if we sort the array the time complexity will be n log n so which is not good we need to see that whether can we do it in O of n because this operations are constant and if we iterate each and every element once we get o of n time complexity so let's see the algorithm and its demonstration step by step so here is the algorithm so here you can see it is only taking one for Loop and we are not sorting the array anywhere so let's see the demonstration of this algorithm step by step but before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so we'll call this method if pass in the array so let's say if we take this array - 4 -1 0 3 and 10 so the length of the array is five so at the start we simply calculate the length of the array by doing array. length and we store it in integer variable n so n will become five now as you want to square each and every element and return this this array all together in a sorted form we'll first create our result array so this result array will store all these elements squares in sorted form so we'll create this new array we pass in the length as five so it will look something like this so these are the default values of the integer array so here the idea is we take two pointers I and J so I will start from zero and J will start from n minus one which is the last index so it would look something like this that I is pointing to zero index and J is pointing to the last index which is four so here if you see when we do the square squares of any negative number we usually get the result in positive side of the numbers so therefore this problem becomes complex because if suppose our array had only positive numbers then this problem would have been straightforward we just do the squares and as the array is already sorted the squares would have been in sorted form but here as we are including this negative numbers here you can see 3 is greater than -4 but if we take theare squares of both the numbers -4 into -4 we will get 16 and 3 into 3 we'll get 9 so before doing squares - 4 is less than 3 but after doing Square this number 16 is actually getting greater than 9 so it means when we will return the result of the squares in sorted form this -4 Square will come after 3 3 Squares because 9 will come before 16 so this algorithm becomes very tricky to find the exact position of these negative numbers among the positive numbers so what we do is we try to fill this result array from the end so here we create a for Loop where K starts from n minus 1 so K is starting from 4 because value of n is 5 so it means we will try to fill this result array from the last why we are doing it from the last because this is the extreme point where we are sure that what value will come so for example this array sorted so here will be the smallest number and can be negative and here will be the largest number so if we do square of these both numbers and we try to compare them we will get one value for sure which will be greater than overall all the numbers squares and we can simply put it here so let's say for example if we take -4 and 10 so -4 into -4 will give 16 10 into 10 will give 100 so if we compare 16 with 100 we are very much sure that 100 is greater than 16 and any number in the array won't get bigger than 100 because we are actually comparing the extremities of this array so here let's say if it would have been -1 if we would have done the square we would have got 121 and 10 square is 100 so we are very much sure that if we are comparing the extremities we will get a square which will be the largest among all the numbers and we can safely put it in the last index so this idea will be more clear when we will actually see the demonstration of this algorithm so I'll just remove this so here K is value is 4 and it is greater than or equal to zero so this condition is true so here you can see why we created these two pointers and we pointed at the extremities because as the array sorted in ascending order the element Square won't be necessarily sorted in ascending order so here what we do is we take the absolute value of the value at I index and the absolute value at the J index so what does absolute method returns is let's say if the value is minus 4 it will give us 4 let's say if the value is minus one it will give us 1 let's say if the value is 10 it will give us 10 so it gives the absolute value without without the sign of it so here we're actually comparing the numbers without their sign and why we are doing it because this negative sign when we do Square this becomes minus into minus becomes positive and we actually do the square of the number which will give us 16 so it's + 16 so this minus doesn't play any role in the Square part but as these numbers are sorted and we can encounter negative values as well so therefore we are comparing the absolute values of the start and the end so here if you see the math. absolute value of I will be 4 and J will be 10 is not greater than 10 so this condition comes out to be false so the lse part will be executed so this actually signifies that we can safely take 10 do its square and place it into the end of the result array because we are very much sure that this value can be safely placed here because we have compared it with the extreme left value so here we do 10 into 10 which is 100 and we simply put it into the result array at K index now after placing it we know that we have used this value so we'll simply decrement J so J becomes three now we'll simply decrement K because we have used this place and K is still greater than or equal to zero so friends here you can see the importance of doing math. absolute we are actually discarding this negative signs and as the array is sorted we are comparing the extremities of I and J index and whichever will be the greater number that square will come directly here so here math. absolute of area of I will be four and m. absolute of array of J will be three only so 4 is greater than 3 so this condition comes out to be true so we simply assign the square of this value minus 4 into the result array at K index so -4 into -4 will give us 16 so we'll simply assign 16 here and as we have used this minus 4 we'll increment I so I will point to index 1 we'll decrement K because we have used this spot K is greater than or equal to0 now we'll do math. absolute of minus1 which will give us 1 and math. absolute of 3 which will give us three so this condition comes out to be false because 1 is not greater than three so we can safely put 3's Square here which will be 9 we have used this spot so we'll decrement J now so J becomes two we'll decrement K because we have filled this spot K becomes 1 and 1 is greater than or equal to Z now we do M do absolute of minus1 which will give us 1 and M do absolute of 0 which will give us zero so 1 is greater than Z so this condition comes out to be true and what we do is we simply assign -1 into -1 which is 1 into this spot we have used this spot so we'll increment I I becomes two we'll decrement K because we have used this spot so K is equal to0 so this condition still comes out to be true and here we are left with only one element so 0 is not greater than Z because math do absolute value of 0 is 0 so this if loog condition comes out to be false and we simply assign 0 into 0 which is 0 to this spot so it becomes 0 now we have used this spot so we'll decrease J so J becomes 1 which will Point here we'll decrement K because we have used this spot so K becomes minus1 it means it has gone outside of the boundaries of the array therefore this condition will come out to be false and here you can see at the end we will simply return the result so this is the result where we have squared each number and after squaring each number you can see the result array is still sorted and we have used this algorithm without using ar. sort so the time complexity of this algorithm is O of n so we'll simply return the result so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thank thanks have a nice day hello everyone so in our previous video we saw a problem squares of a sorted array we saw the animation of the algorithm step by step so in this video we'll actually code the algorithm and we'll test its working in the main method so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in our array util class I'll be creating one method as public static will give a name to this method as sorted squares so this method will take in an array and what this method will do is it will do the square of each and every element of the array and whatever the array it will return that array will also be sorted and this array is already sorted so in our animation video we saw that we can solve this problem using two-p pointer technique so here first we'll create an integer variable n this will store the length of the array then we will create one pointer I which will start from the zero index and 1 pointer J which will start from the last index so the last index will point to array. length minus one now as we want to return return a sorted array so we'll create a result array the size will be the same as our input array now here what we will do is we'll provide a for Loop and inside that for Loop we will try to fill this result array from the end so here we will start from k equals to n minus1 because n minus1 is the last index and it will go to when K is greater than or equal to Z K minus minus so from K - 1 it will go to zero and with each iteration it will get decrement by one position so friends here you can see that this array is actually sorted array so if I take this example so here you can see that this array can contain negative values so if the array contain only positive values this problem would have been very easy we would have just done the square of each and every number and simply place it into the result array at their respective indexes but as this array contains the negative elements also so here for example let's say it was given something like this so we can't directly do the square of each and every number and put it into the respective position because this will result something like this -4 into -4 will give 16 -1 into - will give 1 0 into 0 will give 0 and 3 into 3 will give 9 so here you can see we can't directly just Square the numbers and put it into the respective position because this array is not sorted and we want to return the sorted array so one thing is we just square and at the end we just do the Sorting explicitly and return but that would be a very bad algorithm time complexity wise because we are actually using the Sorting technique so in this algorithm using this for Loop we will try to sort this array properly so that it would look something like this that zero should come here then 1 then 9 and then 16 so usually in order to do that what we can do is we try to compare the absolute extreme values so whichever value is greater we do their Square and we simply put it into the last index and similarly we go on doing like this so for example if we do the absolute value of minus 4 we'll get four and we see that 4 is greater than three so it means if we do 4 into 4 or -4 into -4 we'll get 16 and we can safely Place 16 at the end and after filling this position we just come to this position and after using this minus 4 we just shift here so in the next iteration we simply compare the absolute value of minus one which will give us 1 and we'll compare 1 with three and we see that 3 is greater than 1 so we simply do 3 squ and we put 9 at this position and similarly we keep on doing like this so here the main idea is to take the absolute values of the extreme values try to compare them and whichever is the greater do their square and put it into the result array at the index which is starting from the last index which is n minus one so here we provide a condition as if math. absolute of array of I so we have created this two pointers one would be at the start and other would be at the end if it is great great than math. absolute array of J so what we can do is if the absolute value of ith index is greater than absolute value of J index then in our result at K index we will assign array of I into array of I so we are doing the square of this number and we are assigning it to the result array after doing that we know that we have used for example we have used this position of the I so we simply increment I because we need to now take another value because we are done with this value let's say for example and else then we can simply assign array of J into array of J and as we are assigning array of J and it is basically starting from the last index so it signifies that we have used this value for example and now we need to go one step before to it so what we do is we do J minus minus and after the first iteration of for Loop in our result array let's suppose if we take this example 16 got occupied at this place so we are doing K minus minus because now we need to fill this position we have filled this position now we need to fill this and with each itation we will fill one one position and at the end we'll simply return the result so friend this is the algorithm now we will test its working in the main method so here I will be using this array which we discussed in our slide as well here we will get the result array we will call sorted squares we pass in the array and at the end we'll simply print the array and if I run the main method so here you can see that we got the answer at 0 1 96 100 so this zero came from this zero this one came from Min -1 9 came from 3 16 came from -4 and 100 came from 10 and how it came we simply squared them and using this for Loop we actually placed them at their respective portion so that the final array is also sorted so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem rearrange sorted array in Max Min form so let's see what this problem is and how to solve this so in this problem we are given a sorted array of integers in ascending order now we need to rearrange the array in such a way that the First Position will have the largest number which is the rightmost number the second will have the smallest second will have the smallest which is the first number the third will have the second largest so the third number will be second largest and it will go on so fourth number will be second smallest and here it will be third largest third smallest and then fourth largest so friends the only constraint is that we can't create a new array and do this rearrangement we need to solve this problem in O of one extra space so here if we create a new array of same size which would be our result array then this problem becomes simple because then we can create one pointer here and one pointer here and we can alternatively put the elements in the array and return so the space complexity of the problem will become o of n because we are creating a new array and then we are putting the elements in Max Min form so if we are using o of one extra space it means we need to modify the same array and return it back so let's see how we can solve this problem in of one extra space let's suppose we are given with this array which is sorted 2 3 5 6 8 9 and our output array will become like this 9 2 8 3 65 so 9 is the largest two is the smallest 8 is the second largest 3 is the second smallest and so on so as the array is sorted we know that we can get the largest element if we start start from this index which is the max index so this pointer Max index will help us in giving the largest then second largest then third largest and so on and the smallest elements will be given by main index so here both these pointers will help us in giving largest and smallest numbers second largest and second smallest summer so main index will travel in this direction and and Max index will travel in this direction and here we will have a iterator i which will travel one one element in this direction because we have to solve this problem in O of one extra space we can't create a new array and simply put the elements an alternate fashion so somehow we need to modify the original array only so we create this pointer which will travel in this direction and try to fill the elements in this form also friends here you can see in the output array nine being the largest so if I write here largest if you see the indexes of the largest elements 9 is at zero then comes the second largest 8 which is at two third largest at four so for this simple array if I write the indexes it will be 0 2 4 and for the smallest it is 1 3 and 5 so the indexes would be 1 three and five so here if you see we need to arrange this ARR in Max main form and to place the elements in respective indexes we have this idea that the largest numbers will be placed at even indexes and the smallest number will be placed at odd indexes so this is one thing we need to keep in mind so this iterator when it will travel in this direction at whichever index it is we will first deduce that whether it is an even index or odd if it is an even index then we will take the help of Max index take that value and somehow place it at the index denoted by I and if the I is an odd index then we will take the help of Min index take that value and somehow place it where I belongs so I will write here Max index main index so we need to keep this information in mind that the largest will be at even index and will be placed with the help of Max index which will be starting from the last index the smallest will be at odd index the numbers will be provided by main index starting from the zero index main index after placing one one smallest element will travel in this direction and Max index after placing the largest element will travel in this direction so if you closely observe between these two arrays you will see we need to arrange the r in maxman form so at the start when I will be at zero index here we know that we need to put nine at the first spot so as we can't create a new array we need to put nine somehow here but here you can see we have already two because two will lie in this index after the output but two will see there is a three and if you see three will lie in this index here and when we will place three here it will see that it has six because six will lie in this index here and it has eight so eight will lie in this index and similarly if you see we can't directly replace the elements because it has already one element which we need to place it at its correct index so that it looks in Max Min form so friends the trick to solve this problem is instead of storing 9 directly here what we can do is we take 9 we take two we apply some formula and generate let's say a integer let's say we combine 9 and two in such a way based on such formula and we get a number X so we will store X here instead of N9 so why we are storing these number is so as we are storing a combination of number based on a formula now let's say if I take an example here we have eight now this eight we need to somehow place it index two here like this so let's say to this number I denote it as a and this number let's say I denote it as B so we'll take b and a and apply some formula and generate a number X so this x we will store here instead of it directly we will store a number X which will be a combination of b and a 5 and 8 now while we are storing both the numbers is in the output aray eight should come here but five will be lost so we need to prevent both the numbers because if I put eight directly here then five will be lost and we can't figure that what we need to place at this index because five should come here in the output array so this x we store in such a way we will see the formula later this x we store in such a way that it will help us in giving a back and B back so that after storing X here in the resultant array at this index will somehow deduce a and when we will reach here we take that X and we can somehow deduce B so that we can place five directly here so this is very important that we are using some formula here and storing a number X and this x will help us in generating getting a and b back so here what we do is as the array is sorted the last index will be the maximum value we will take a variable which is greater than our largest number so here what we can do is we can simply do 9 + 1 let's say 10 we are going to last index we are taking that value and adding one we will see why we are doing that so friends the formula we use to store two numbers is let's say if the I is that even index we need to store the largest number and that largest number will be given by Max index here and the max we have is 10 so let's say if we are at index zero and we need to place 9 here like this so if I use this formula so at this index what we will store we will store the whatever the value here we have which is the two which is important for us because this is our let's say B so we take two we take the number which we are shifting which is N9 we do modulus by 10 which is 9 divided 10 will give us a remainder and we do multiply by 10 now here you can see it will give us two the remainder is N9 into 10 the number is 92 so at array of I we are storing the number 92 it was 2 and we are storing 92 so here if I write number 92 so here you can see this number is our X and how we can deduce A and B back is 92 the max which we took let's say if I divide 92 by 10 so we will get 9 which is our a and if I do 92 mod 10 we'll get the remainder which is two so here you can see this largest number which you are taking it is generating a number which is storing our both the integers the number which you are shifting here and the number which is already here so we can deduce 9 and two back so now let's see how this algorithm will move ahead so this mod you will understand when we reach here so now I will come here and we assume that Max index somehow has placed this value here so the max index will now come at index 4 to take the second largest value like this so now I is at odd index so now we will use the formula for odd index we will take the help of Min index the formula is pretty much same only the value in array for Max index and Min index is changing here so now here you can see that this step will be more clear to you why we are doing this modulus so at index one we need to put the smallest number we are taking this formula so we take the value here which is three because we don't want to lose this value and here you can see we'll take the value at Main index So currently if I take the value at Main index it is not two two is gone we have 92 so I will simply write 92 mod 10 into 10 now you will understand that why we are doing first mod is because there could be a chance that we get an overridden value so here we have 92 and we know that from X we can deduce our overridden value which was two and the number which is transferred here so 92 ided 10 will give 9 92 mod 10 will give remainder which is two so here therefore we are first taking this remainder so that first we get the original value and even if this value is not overwritten let's say it's were two only so 2 mod 10 this will again give us two only so here so here this formula is important that we are doing mod with the max value first to reduce our original number and then we are simply multiplying it by 10 so that something like this can happen so 3 + plus 2 into 10 the remainder is 2 so it will give 23 so here this number 23 is suggesting that that we will store 23 here and now this value is overridden 23 comes here and what it is telling is it is storing two numbers the number which is getting shifted here and the number which was already here so we'll go over this quickly now because we have a fav amount of idea what we are doing so for two it is an even so we use this formula so we take the value five plus we are using this formula value at Max index is 8 so we are doing 8 mod 10 into 10 so here you can see that this value is not overridden so therefore even if we do mod 10 we get the same value back so 5 + 8 into 10 which is 85 so we are storing 85 here for this index I and then I will come here and this Max index will come here and as we have used this two also here so we will move the main index to here so now as I is at three which is odd index we need to take take the smallest value we move wind index in this direction because we assume that we have placed two here somehow the step which we did previous 285 while we place 23 here so main index used this value and it shifted here now at this spot what we do is we are taking this formula because value of I is three so here we take 6 23 like this the remainder will be three it will give 36 so here now this value will become 36 this has been overridden and this has also been overridden so these are the now original values at these spots now after taking the help of main index main index will come here we will move I ahead and now value of I is four we will take the largest number and we'll use this formula so 8 plus the value at Max index is 36 mod 10 into 10 so this will give us 8 + 6 into 10 it will be 68 so we are storing 68 here so this 8 will be overridden with 68 so this value will be overridden and Max index will come here because it has used this value I will go here and at the last index being an odd index we will take that value 9 because we are using this formula we are taking the value 9 then plus value at Min index which is 85 because main index is pointing to index 2 so 85 mod 10 into 10 9 + 5 into 10 so this will give us 59 so we are storing 59 so I'll just remove this now everything so now instead of these numbers we have a combination of numbers so let's say if I denote this number as X and we need to get back b and a so we know that will give us a will give us B we know this formula already so now we will iterate this array one more time and now what we do is we need to store 9 here which is our a so what we do is 92 ided 10 will give 9 so 9 comes here here 23 / 10 2 comes here and similarly 85 divided 10 will give 8 36 divided 10 will give 3 68 divided 10 will give 6 59 divided 10 will give 5 so this is how this combination numbers will give us output array which is our answer so friends these are the formulas we need to keep in mind and now let's move ahead and see the demonstration of this algorithm step by step so we have method arrange maxmen which takes in an array and here you can see that we are not creating any additional array so this problem is solved in O of one space complexity so friends before we start if you want to master algorithms and data structures then you can subscribe to my channel and click the Bell icon so that you never miss any update so we call arrange maxmen we pass in the array so this is our original array which is here and this is our resultant array which is our output array so here as we will modify this array this number will be getting overridden so to understand what the previous number was you can refer this array because this is our original array moving ahead we create a Max index starting from the last index array. length minus one array. length is 6 minus one will give five so max index will start from here because this Max index will give us the largest then second largest then third largest and so on we'll create a main index starting from zero this main index will give us smallest then second smallest and third smallest and so on so as the array sorted we have created two pointers starting from very extreme ends and then we will evaluate a max value which we already discussed that we simply take the value at the last index which is the maximum because this array is sorted we do + one so max will become 10 and now we will apply the for Loop where we are traversing I in this direction starting from zero and going till fifth index via this condition So currently I will start from zero index 0 is less than ar. length which is six so friends in our previous slide we discussed that first we evaluate whether this I is at even index or at odd index so if I divided by two if it gives remainder as zero it means it is an even index and if I mod 2 doesn't give us a remainder zero it means it's an odd index So currently value of I is zero so I mod 2 will give remainder as zero which means that we are at even index and as we are at even1 index we know that we need to place the largest numbers which will be given by Max index at odd index we will put the smallest numbers that will be given by main index so here we are using the same formula so as I is at zero index we are taking the help of Max index to take the maximum value and place it here so we will store a modified number here which is the combination of this and this number so we will take 2 plus value at Max which is 9 mod 10 which is our Max into 10 so this will give us 92 so we store 92 here and then we decrement Max index assuming that Max index has placed 9 at its proper spot so the max index will come at index 4 like this we will increment I I comes at index one now I mod 2 will give remainder as one so therefore we know that 1 is an odd integer so the lse part will be executed so now here we will take the help of Min index to get us the smallest numbers the formula is pretty much the same which we already discussed in our previous slide here we will take this number which is three we will take the number at Min index which is 92 we will do mod 10 multip by 10 we are doing mod 10 is because we need to get back the original number which was two so 92 mod 10 will give us 2 because we need to put two here somehow so in the output array here you can see two will come here so at this index we need to place two so therefore from 92 first we are deducing two why this modulus so 3 + 2 into 10 this will give us 23 so 23 will come here so now we assume that main index has taken two and somehow placed it at its correct spot so this value and this value we assume that we have used up so we increase min index value so that we can get a second smallest value now now main index becomes one we will increment I I comes at index 2 I mod 2 which is 2 mod 2 which will give us zero so it means 2 is even index so we apply the formula we take this value 5+ now we take the value of Max index because we need to put eight somehow here so 8 mod 10 5 + 80 it will give us 85 so 85 comes here now we will decrement Max index because this value is used up Max index becomes three so it means we have used up this value now we will increment I I comes a third index which is odd index so this condition will fail because 3 mod 2 will give us remainder is one which is not equal to zero and here we will take the help of Min index and take the second smallest value now so we will take this value which is six we take 23 we'll do mod 10 because at index 3 you see the number we are shifting is now three should come here in the resultant array so first we need to deduce this three back so 23 mod 10 will give remainder three which was our original number here and then we do multiply by 10 so this will give us 6 + 30 36 so 36 comes here and now we assume that we have placed three here properly somehow so this number will be used up and Main index will come to this spot so we'll increment Min index like this we will increment I I comes to this spot the value of I is four which is an even index so this condition comes out to be true we take the value8 and here we will take the help of Max index because we need to put the max value here so first we will deduce what number we need to shift so we'll take 36 mod 10 into 10 this will give us 6 into 10 60 8 + 60 will give 68 so 68 comes here and then we have used this six also so we will decrement Max index now it will come at index 2 now we will increment I I becomes five 5 is still less than 6 5 mod 2 will give a remainder is one so therefore the lse part will be executed and here we will take help of main index so at Main index the original value was five and we know that five needs to be come here so first we need to deduce 5 out of 85 so we'll use this formula we take 9 here plus so this formula will help us in getting five back so we'll take 85 mod 10 into 10 this will go 9 + 5 into 10 which is 59 so 59 comes here and then we will increment Min index because we have used this value also so now when we will increment I I will become six and 6 is not less than 6 so therefore this for Loop will terminate now which makes sense because we have used up all the values so now this is our modified array at the start we have taken this array which was our original array we transformed it into this array and now our task is to transform this array into this array so for that we are using this for Loop and we have already discussed how we can do that is let's say we take 92 we know that we have stored both the numbers the number which was getting shifted here and the number which was already here we can deduce both the numbers so let's say if I denote 92 as X so here x will give us a yaa X by Max which is our 10 here and X will give B via X Mod Max so if I take 92 if I do 92 by 10 we'll get 9 which is our a if I do 92 mod 10 it will give us 2 which is our B and our task is to store the largest element here we know that we can get it via division so weate this array back from I equal to 0 it will go till the last index so we'll go over this formula quickly because it is very simple so I is zero now at the same spot we are taking 92 dividing it by Max which is 10 and storing it back at the same index only so here it will come 92 divided 10 will give 9 like this moving ahead I becomes one 23 ided 10 will give 2 we increment I again I becomes 2 85 ided 10 will give 8 we increment I I becomes 3 36 ided 10 will give 3 will increment I 68 ided 10 will give 6 we increment I five is still less than six because array dot length is six so this for Loop will execute one more time for the last index 59 divided 10 will give 5 and now when we'll increment I it will go beyond the boundaries of array so this for Loop will terminate and here you can see after this for Loop will terminate our algorithm will also end and here you can see that now we have got our output array which is in Max Min form and one thing to notice we have modified the same array which we received so therefore we have used o of one extra space so friends in order to understand this problem more you need to go over this video two three times to understand these formulas which is helping us to store two numbers instead of one and then here we are deducing one of the number out of it so this x is giving B year and a year so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss about the introduction to graphs so friends what is a graph so friends below you can see a figure it represents a graph here it contains few notes say 1 2 3 4 5 and these five notes are connected through some lines so a graph is a nonlinear data structure used for storing the data so we can store the data inside a graph but it's not a linear data structure like arrays and Link list so friends it is a set of vertices so here you can see 1 2 3 4 5 are nothing but vertex of the graphs and it also has a collection of edges that connects a pair of vertices so here you can see two Vortex are connected by an edge so in a graph if we take any two Vortex and if you want to connect them we just provide an edge so here you can see between this five Vex there are six edges 1 2 3 4 5 and six so in simple terms we can represent a graph as set of vertices and a collection of edges that connects a pair of vertices so friends why graphs are important so here you can see so friends here you can see a graph which is nothing but social networking site so in computer applications graphs help us to implement social networking sites such as Facebook and Twitter and we can term it as social networking graph so friends here in this social networking graph the names of people which you can see here as anit John Bill Kathy and Max we can see them as the vertices of the social networking graph so if you consider an example of Facebook then friendship between two people can be represented as an edge of the graph so here you can see see Bill is friend to KY and Kathy is friend to bill so therefore there's a link between them which is nothing but friendship link so we can represent this graph where people are the vertices and the friendship link between them is nothing but the age another application of the graphs would be the web content over the Internet so friends let's suppose we are having few web pages as google.com ud.com youtube.com twitter.com and facebook.com and let's suppose from google.com there is an edge to.com so this Edge is nothing but a link and similarly let's say from Udi there is one link which can take us to facebook.com and from Facebook to Twitter and from YouTube to Twitter and vice versa so here we can take the web pages as the vertices of this graph and the links as the edge between these vertices so friends in computer application this web content can be represented as a graph where web pages are nothing but the vertices and the edge which connects between them is nothing but the link so friend this was the introduction to graph in our upcoming tutorial we will discuss the graphs into further detail I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how we can represent a undirected graph so one of the way in which we can represent a graph is adjacent Z Matrix so friends first of all what is an undirected graph so here in the figure you can see five notes 0 1 2 3 4 so these notes are nothing but the vertices of the graph and you can see here an undirected edge so here between the vertex 3 and Vertex 4 there is an undirected edge so what what is an undirected edge The undirected Edge doesn't have any direction so if suppose we are on Vortex 3 then we can go to Vex 4 and if suppose we are on Vex 4 then we can go to Vortex 3 and as say there is no Direction between the two vertices so a graph which has this two edges are termed as undirected graph so if you take an example then social networking graph which we discussed in our previous tutorial is nothing but an undirected graph so let's suppose in a social networking graph there is a set of vertices which is nothing but the names of people so let's suppose John is a friend to Max so here John and Max are nothing but the vertices of the graph and the friendship between them is nothing but the edge of the graph so here if John is friend to Max then it implies that Max is also friend to John so it is nothing but an undirected graph so so here John is front to Max is same as Max is fr to John so the social networking graph can be seen as an undirected graph where edges are undirected they don't have any Direction moving ahead so friends graph can be represented by two dimensional array which is nothing but a matrix so let's suppose we are given this undirected graph where Z is connected to one one is connected to two two is connected to three and three is connected to zero so in order to presentent this graph in a data structure we usually use the Matrix which is nothing but a twood dimensional array so friends here if you see there are four vertices so therefore we create a four Cross Four Matrix so this four Cross Four Matrix goes from indexes 0 to 3 and this Matrix is nothing but a 01 Matrix so why we call it a 01 Matrix because in order to represent an edge between two vertices we just provide a one which signifies that there is an edge between the two vertices so friends here you can see from 0 to 1 there is an edge so when we want to represent an edge in Matrix we follow this rule that the first vertex is the row and the second vertex to which this Edge is going is the column so if I take an example then between 0 and one there is an edge so in the graph we can represent it as from zero row to one column there is an edge which is nothing but one similarly if we are at node one and if you want to go to node zero then there is an edge so from the first row to zero column there is an edge and as it is an undirected graph therefore we can go both ways from 0 to 1 and 1 to 0er so let's suppose if you want to go from 3 to 2 so from the third row second column there is an edge which can be represented as one and similarly it is an undirected graph therefore from two we can go to three so from the second row to third column there is an edge also here you can see that from node 3 to node one there is no Edge therefore from the third row to First Column there is no hedge therefore we have represented it as zero because it signifies there is no hedge between 3 and 1 so the Matrix wherever you want to represent an hedge we usually put one and wherever we want to represent a no hedge then we put zero so friends here we use the Matrix to represent an undirected graph I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss the adjacency Matrix implementation of an undirected graph so friends in our previous tutorial we discussed what is an adjacency Matrix and how we can represent an undirected graph into it so friends in this tutorial we will see how we can Implement an adjacency Matrix to represent an undirected graph through a demonstration so friends let's suppose we are given an undirected graph with four vertices as 0 1 2 3 where 0 and 1 are connected through an hedge 1 and two are connected through an hedge 3 and two are connected through an HED and 0 and three are connected through an hedge so friends using this code here we can actually represent this undirected graph into a form of Matrix so let's see this demonstration step by step so in our previous tutorial we discussed that using a matrix we can represent at a graph so here in our Java class graph we are having this adjacency Matrix and in the Constructor we are initializing this adjacency Matrix with the number of notes in the graph there is a method add edge which takes two parameters let's say u and v so here suppose if you want to add an edge between 0 and 1 so 0 would be U and one would be V so through this code we can add an edge between u and v so we'll see it demonstration step by step so let's suppose in our main method first we initialize the graph with the number of notes so here you can see there are four notes so we are passing the number as four here so now the execution step goes into the Constructor of graph where notes is having value of four so in the Constructor we simply initialize an object of Matrix by providing the value of row and column as the value in the notes which is nothing but four so after execution of this step it will create a two dimensional array which is nothing but a four cross4 Matrix so it would look something like this so here it will be represented as an adjacency Matrix which is a 4 cross4 Matrix moving ahead so friends here you can see that from 0o to one there is an edge so by calling Ed edge method we pass 0 and one because we want to create an edge between 0 and 1 here we simply apply this rule that between a row and a column we just provide a one which represents an edge so if you want to represent an edge between 0o and one so zero will represent a row and one will be representing as a column so between 0 and 1 there would be an H which will be represented by one so let's see how so as the value of U is Zer and V is 1 so here in order to represent an hedge between 0 and 1 in The Matrix 0a 1 we provide a value as 1 so in The Matrix 0 and 1 we just provide a value of one so it would look something like this so This represents an edge between 0 and 1 which is zero row and one column moving ahead so friend in the Second Step what we do is as this graph is undirected graph there is no Direction between the edge therefore we can see it something like as there is an edge between 0 and 1 and we can also see it as there is an edge between 1 to zero so friends this information we need to store into the Matrix so in the first step 0 to 1 we provided a value as 1 so similarly in the Second Step from Row 1 to zero column we'll provide a value as one so it would look something like this so in an undirected graph basically an edge represents a two points into the adjacency Matrix because because if you are at vertex zero then we can go to vertex one because there is an hedge and if we are at vertex one then we can go to vertex 0o through this Edge so therefore in The Matrix this Edge represent this two points that from zero to one there is an edge and from 1 to zero there is an edge moving ahead now we want to add an edge between 1 and two so we simply pass the parameters as 1 and two So Into The adjacency Matrix to row one and column two we need to provide a value one to represent an edge so it would look something like this moving ahead now similarly we have to provide an hedge from row two to column 1 so we provide a value as one so this represent an edge between row two and column 1 moving ahead similarly vertex 2 and Vortex 3 are connected through an edge therefore in The Matrix from the row two and column 3 will provide a value as one moving ahead and similarly from the row three to column 2 will provide a value as one because if you want to Traverse from third node to node two we know that there is an h and that can be figured out through this Matrix that we can directly figure it out that from Row three and column 2 is there any Edge or not so if the value is one we can come to know that there is an edge moving ahead and the last stage is between vertex 3 and vertex 0 so it would be represented as Row three and column 0 which is this value will provide a value as one moving ahead and finally from the row zero to third column we'll provide a value as one so friends this is how we can represent an undirected graph into a matrix and also one point to note that as it is an undirected graph therefore for each Edge there will be two two values of one into the graph which will be actually demonstrating a two-way graph here from 0 to 1 there is a way and similarly from 1 to Z there is a way so into the Matrix we represented it something like from 0 to column 1 there is an edge and from one row and zero column there is an edge so friend this is how we can represent a graph in the form of a two- dimensional array which is nothing but a matrix in my next tutorial we will actually code this algorithm into the eclipse I hope you like this video thanks have a nice day so friends here I have created one class by name graph which is having a main method so into this class we'll code the implementation of graph through adjacency Matrix so first we'll create an integer variable and we'll give it a name as V so this V is nothing but a number of vertices in the graph we'll also create one more integer variable we'll name it as e so this e would be number of edges in in graph we'll also create a two- dimensional array which would be our adeny Matrix and it would represent a graph soate so it would be a two dimensional array and in the Constructor we will initialize this three values so this graph Constructor takes in number of nodes so here simply we can assign noes value to V and as we are in the Constructor of graph therefore value of e would be equal to zero because till now there are no edges into the picture and finally we'll initialize the Matrix with the number of notes so if suppose the graph is four notes therefore this should be a 4 cross 4 Matrix we'll also create an add asge method which will actually add an edge from U to V and vice versa therefore here simply we can do is to U row and V column we'll assign a value of one which represents an edge and Vis Versa will do from V to you because it is an undirected graph so therefore for every Edge in The Matrix there will be two points which will be representing an edge after adding The Edge we'll increment the count of edge by one so it would be e++ so friends in in our main method we'll create a graph and add an edge between few nodes so we'll create an instance of graph and we'll provide a value of four so this will actually create a graph of four nodes and also it will create an adjacency Matrix which is of 4 cross 4 so we'll actually create a graph which we saw in our previous tutorial We'll add an edge from zero to one then from one to two then from two to three and finally from three to zero so friends here we have added four edges which we actually saw in the slide of our previous tutorial here I will create one method which will give us the string representation of this graph I will name it as two string so first we'll create a string Builder we'll append V which would be vertices e would be our edges and then we'll simply provide a for Loop now this for will iterate over each and every vertex and inside this for Loop we'll append and now we'll provide one more Loop which will iterate over the adjacency Matrix for a particular vertex so here we'll append so here we are simply printing The Matrix so SB and finally we'll return sb. two string so here we'll simply print G and if I run this now so friends here you can see that there are four vertices as we have passed a value into the graph as four and there are four edges because we have created four edges from 0 to 1 1 to 2 2 to 3 and 3 to 0 and below is the string representation of this graph which is nothing but our adeny Matrix so this Matrix we discussed in our previous slide you can refer that slide and you can come to know that it represent the same Matrix which we discussed so friends in this tutorial we saw the implementation of the graph using an adjacency Matrix I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss the representation of an undirected graph through adjacency list friends in our previous tutorial we discussed about the representation of undirected graph through adjacency Matrix so in this tutorial we will discuss one more way to represent a undirected graph that is through adjacency list so this adjacency leads to nothing but an array of Link list so friends let's suppose we are given an undirected graph having four nodes 0 1 2 3 and from zero Vortex there is an edge to vertex one from vertex one there is an edge to vertex 2 and from vertex 2 there is an ed to vertex 3 and finally from vertex 3 there is an HED to vertex 0 so friends this undirected graph can be represented as an adjacency list which is nothing but array of list so here you can see there are four notes so we create an array of Link list having the size as four so here you can see each and every index hold a link list and what this link list contains friends let's suppose we are on vertex Z and there is one H to vertex one and one H to vertex 3 so friends these two edges from the vertex Z is represented as in the array index0 Z the link list which it holds has node one and node 3 so this structure tells us that from node zero there is an edge to one and there is an edge to node 3 similarly if you can see from vertex 2 there is an hedge to vertex one and vertex 3 so in order to represent this structure at index 2 we have node 3 and node one so it signifies that from two there is an ed to three and from two there is an edge to 1 similarly here you can see that from three we have 1 Edge to two which is this Edge and from three we have 1 Edge to zero which is this Edge so friend this is one more way to represent an undirected graph that is by using an array of Link list so the length of this array is same as the number of vertices in the graph so friends then our upcoming tutorial we will discuss more about adjacency list we'll see it code and working through animation I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss about the implementation of the undirected graph using adjacency list so friends in our previous tutorial we discussed about the represent ation of an undirected graph through an array of Link list we also discussed that how this undirected graph can be represented into an array of Link list so friends in this tutorial we will look into the code and see its demonstration step by step so here is the code to implement a graph using an array of Link list so we'll see the working of this code step by step through animation and we will see that how we can represent this undirected graph into an array of Link list so let's start so in the step one we initialize a graph and we pass in the number of vertices the graph can have so here if you see this undirected graph has four notes therefore we are passing the value as four so into the Constructor the value of nodes is four so in the first step what we do is we have taken this instance variable which is nothing but an array of Link list so we initialize this array of Link list with the number of notes so it would look something like this that here you can see an array of Link list so as currently the link list is not being initialized so they point to null moving ahead so then we provide a for Loop and we iterate over each and every vertex and to this array of Link list it will initialize the link list to each and every index so as I starts from zero therefore at zero index it will initialize a link list so it would look something like this currently link list is empty and head is pointing to null moving ahead then I becomes one and similarly at the index one it will initialize a link list moving ahead I becomes two so index two it will again initialize the link list and similarly at the index 3 it will initialize a link list so now I becomes four therefore the condition in for Loop comes out to be false because four is not less than four so friends here we have created an array of Link list and to each index we have a separate link list so here you can see from vertex 0 to vortex one there is an edge so we'll call this add edge method and we'll pass the value as zero and one stating that there is an edge between 0 and 1 so friends value of U is Zer and value of V is 1 and also in our previous tutorial we discussed how we can represent an undirected graph into an array of Link list so what we do is as there is an edge from 0 to one therefore the zero index link list we add one so first we get this link list at the zero index and add one to it so it would look something like this that at the zero index link list we are adding one moving ahead and similarly as this is an undirected graph therefore from vertex one there is an edge to vertex 0 therefore to the link list at vertex one will add the value zero so it would look something like this so here it represents that from zero there is an HED to one so the link list at zero index has an edge to one and similarly here you can see from the vertex one there is an edge to vtex 0o so it is represented by the link listed index one has a value zero which signifies that there is an edge from 1 to zero moving ahead then we can also see that there is an edge from 1 to two so we call this add edge method by passing one and two so in the first step what we do is the link list at index one we add the value two so it would look something like this moving ahead and similarly the link list at index two we will add value one so at index 2 We'll add the value one so it would look something like this moving ahead now there is one more Edge from The Vortex 2 to vertex 3 so this can be demonstrated as to the link list at index two we will add the value three so here to a link list at index two we will add the value three so it would look something like this moving ahead and as it is an undirected graph therefore to the link list at index 3 we will add the value 0 two so it would look something like this moving ahead so in the last step there is one more H from the vertex 3 to vertex 0 so we'll pass the value as 3 comma 0 so in the first step what we do is the link list at index 3 we will add the value zero so it would look something like this moving ahead and similarly the link list at index zero we will add the value three so friend this is a code to implement an undirected graph through an array of Link list here you can see that each and every node is been represented by an index of this array and in order to represent an H we simply add those value into the link list of that particular index so here you can see that from zero there is 1 H to 1 and 1 H to 3 so at the link list at zero index we are adding one and three so this is a type of a metadata which can help us to know that okay from zero there is an hedge to one and from zero there is an edge to three and similarly if I take this vertex 2 there is an edge to one and there is an edge to three so the link list index two has 1 and three so friend this is how we actually represent a graph into an array of Link list in my upcoming tutorial we will actually code this implementation into eclipse and see it's working working I hope you like this video thanks have a nice day so friends in our previous tutorial we actually discussed about the implementation of an undirected graph through adjacency list so in this tutorial we will code that implementation into Eclipse so here I have created one class by name graph having a main method so here in the graph class we'll first create an array of Link list we'll import the link list from java.util we'll also create an integer variable and we'll name it as V so this integer variable will be having a value of number of vertices in the graph so it represents number of vertices and similarly we'll create one more integer variable and we'll name it as e so this integer variable will be having a value of number of edges in graph we'll also create one Constructor and to this Constructor will'll pass the number of vertices the graph can have so we'll give this integer a name name as notes so here what we can do is as we represents the number of vertices in a graph so we'll simply assign the value of notes to it and as this graph is getting initialized so the value of e will be zero because currently there are no edges and finally we'll create an instance of array of Link list so this do a a equals New Link list and it'll pass the value of nodes to it so after creating an instance of array of Link list currently each and every index of this array will point to null because the link list is not been initialized so we'll provide a for Loop and we will iterate over each and every vertex and we'll create a separate link list for each and every index of the array so adj of V so friend in this for Loop we are trting over each and every vertex and as we have created this array of Link list therefore we need to initialize a link list for each and every index moving ahead we'll create a method as add edge so this method takes in a two value let's say we give the name to us u and v so by calling this Ed edge method what we are doing is we are creating an edge between u and v friends in our previous tutorial we saw that in in order to create an edge between u and v we have to provide the value of V into the link list of U and similarly we have to provide a value of U into a link list of V so here what we do is into the link list of U we add the value V and similarly into the link list of V we add value U and finally we increment the value of e by 1 because it signifies that an edge is been placed between u and v therefore we are incrementing the E by one so friends in the main method we'll first initialize the graph with the number of noes so so friends in our previous tutorial we saw an undirected graph which had four nodes so we'll initialize this graph with four vertices so we provide the value as four and then we'll add an edge from zero to 1 and then from 1 to 2 then from 2 to 3 and finally from 3 to 0o so friends here we have created one graph of four notes and we have added four edges so friend in order to test it working I'll will create one method as two string so so friend this method will return back as a string representation of this graph so in the first step I will be creating an string Builder so to this string Builder first I will append vertices and edges and then we'll provide a for Loop and we'll simply iterate or each and every vertex so you have to string Builder we'll append V so friends here in the for Loop we are getting each and every value of vtex so friends as we are looping over each and every vertex we have the vertex value we'll provide one more for Loop which will bring back the link list associated with that vertex and we iterate over it and print its content so here we'll provide one more for Loop so in order to iterate our a link list associated with a particular vertex what we do is we simply pass the value of that vertex and we'll get the link list associated with it so here if I take an example then we have added an edge from 0 to 1 and there is one Edge from 3 to 0 therefore when we call the link list associated with vertex Zer we'll get the two values one is the value one and one is the value three because those two values are there in the link list so in this for Loop we'll simply append the value present in the link list for that particular vertex and finally we'll append one line break and we simply return return the string representation of the string Builder so friends in our main method we'll now sis out the value of G and we'll run this code so friend here you can see the graph has four vertices and four edges because we have initialized the graph with four Vex therefore the value of V is four which is the number of Vex and as we have added four edges we are getting the value of the number of edges as four and here in the two string representation of it what we are doing is we are iterating over each and every vertex that is from zero 1 2 and 3 and here you can see that there is an edge from 0 to 1 and 0 to 3 therefore from the vertex 0 there is an edge to one and there is an edge to three and similarly from vertex 3 there is an edge to two and there is an edge to zero there is an edge between 2 and three and 3 and zero so into the link list of this third index there are values 2 and zero which represent that there is an hedge between 3 and two and 3 and Z so friend this is how we actually represent a graph through an areay of Link list I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss the breadfast search of an undirected graph so friends breadfast search is nothing but a traversal or a searching technique which we apply to the graphs to visit each and every node of the graph so here breadfast search is also known as level order traversal so let's suppose we are given a graph of say five notes where 0 1 2 3 are connected by an edge and four is connected to two by an edge so there therefore for what do we mean by level order so suppose if you're starting from zero then this is at level one so this will be visited first and then here you can see that from zero 3 and one are connected so these both notes are at level two so after 0 1 and 3 will be visited because they are at level two and then you can see that from three there is an edge to two and from one there is an edge to two so therefore the node two is at level three so after visiting 1 and three two will be visited because it is at level three and then here you can see node 4 is connected to two now this is at level four so therefore four will be visited after two so 0 is at level 1 1 and three are at level two two is at level three and four is at level four so using bread for such Technique we can Traverse the graph level by level so friends here is the algorithm for it so friend in this algorithm we usually use Q data structure so this data structure is nothing but fif data structure which means first in first out so the element inserted into this data structure first will be first to be removed from the que so we are using Q because it will help us in traversing the notes of a graph level by level so friends we apply the same algorithm while we are TR revering the tree but there is a slight catch in the graph because in the graphs it may contain a cycle which you can see here so therefore we need to keep the track of the notes which are being visited so we usually keep the track of the notes into a Boolean array so friend let's see the working of this algorithm step by step so we'll start with the value zero so in this method we'll pass the source node is zero so in First Step what we do is we create a Boolean array whose size is equal to the number of vertices in the graph so this vertices is nothing but the instance variable which we discussed in our previous tutorial so here you can see in this graph there are five notes therefore we'll create a Boolean array by name visited having a size of five so it would look something like this and as it is a Boolean array so initially all the values inside this array is marked as false and we have marked it false because initially we haven't visited any node of the graph moving ahead we'll then create a q data structure now this Q data structure will help us in traversing the notes of a graph level by level so it would look something like this so here in our previous tutorial we also discussed how Q data structure works so you can watch my those tutorial to get more in depth of how Q works so it's simply a fif for data structure where element inserted first will be first to be removed moving ahead now friend as we are starting from zero so we will Mark the visited index as true that we have visited this node in the array we'll make it true and here we'll mark it that we have visited this node so friends after we visit the node we simply put that node into the Q so as you have visited zero we'll put the zero into the Q so it would look something like this moving ahead so friend as we want to Traverse each and every node level by level then we'll apply a while loop and we'll check whether Q is empty or Not So currently you can see Q is not empty because there is one value inside the Q so the condition in while block comes out to be true so now the first step we simply pull this element out of the Q which is zero and we'll assign it to the integer variable U so it would look something like this and it will be assigned to you moving ahead we'll simply print this element on the console that it is visited so zero is printed on the console so here in breadfast search after visiting any particular node we then go towards its adjacent nodes so here you can see the node adjacent to Z are 1 and 3 and in our previous tutorial we saw the representation of a graph through adjacency list so now we'll apply a for for Loop which will Traverse the adjacent nodes of zero so here if we look the adjacency list of graph then the node adjacent to U would look something like this that in the adjacency list 0 is connected to 1 and 0 is connected to three so here 0 is connected to 1 and 0 is connected to three so now we'll Traverse each and every adjacent nodes of zero so we'll start with one so here V becomes one and the first I will check that whether one is already visited or not so here in the array we see that value of index one is false therefore it's not visited so in the F log first we mark this node as visited by providing a value of true to index one of this bullan array so it would look something like this and here will mark it as visited and after marking the node as visited we'll simply put it into the que so we'll put one into the Q so it would look something like this moving ahead now V becomes three we check whether three is visited or not so here in the Boolean array three is not visited so we will first Mark three as visited by making the value is true that we have visited this node and then we'll simply put three into the Q moving ahead now as we have visited all the adjacent nodes of zero therefore this for Loop will terminate and we will come back to our while loop and we'll check whether Q is empty or not so here you can see Q is not empty so we'll pull from the que so one will be pulled out so it would look something like this and U will have value as one we'll print one on the console that we have visited it so friends now we will actually Traverse the Adent notes of one which is nothing but 0o and two because they are connected to one and if we look the adjacency list of one then it would look something like this that one is connected to zero and one is connected to 2 so now in the follow Loop we'll iterate over these two elements so we'll start with zero so V becomes Z we will check whether 0 is visited or not so here you can see Z is already visited therefore we'll simply skip this if block and then now V becomes two we check whether two is visited or not so here you can see two is not visited so we will first Mark the value at index 2 as true that we have visited this node and also we are marking it as we have visited this node moving ahead and then we'll simply put the two into the Q so it would look something like this moving ahead now friends here you can see we have visited each and every adjacent notes of one so therefore the for Loop terminates and then we'll come back to our while loop we check whether Q is empty or not so Q is not empty we'll pull the first element from the Q which is three so it would look something like this and we'll assign its value to U so U becomes three moving ahead we simply print three on the console that we have visited and friends then we'll provide a for Loop which will iterate over the adjacent notes of three so here you can see the adjacent notes of three are 0o and two so if we see the adjacency list of three then it would look something like this that three is connected to 0 and 3 is connected to two so now we will visit the adjacent notes of three and we'll start with zero so V becomes zero we check whether Z is visited or not so here you can see that zero is visited so we simply skip this if block now V becomes two and we check whether two is visited or not so here you can see two is already visited therefore we simply skip the F block so friends there are no more Adent nodes to three so therefore this for Loop will terminate we'll come back to our while block we check whether Q is empty or not so Q is not empty we pull the first element from the Q which is two so it would look something like this and we'll assign it to integer variable U so U becomes two and then we'll simply print the value of U on the console that we have visited it so friends now we will actually Traverse the the adjacent notes of two so here you can see the notes adjacent to two are three 1 and 4 because they all are connected by two so if you look the adjacency list of value two then it would look something like this that two is connected to three 2 is connected to 1 and two is connected to 4 so therefore now we'll Traverse each and every adjacent notes of two so we'll start with three so V becomes three moving ahead we will check whether three is already visited or not so here you can see in the visited areay at index 3 the value is already true and it's already visited therefore we simply skip this if block now V becomes one we know that we already visited one therefore we'll skip this if flock now V becomes four and here we will check whether we have visited four or not so we haven't visited four because the value at index 4 in the visited array is false so in the first step what we'll do we'll mark this value as true that we are visiting it moving ahead and then we'll simply offer four into the queue so it would look something like this so friends now there are no more adjacent nodes left to be Traverse so this for Loop will terminate we'll again check whether Q is empty or not so Q is not empty we'll pull the first element out of the Q which is four so it would look something like this and we'll simply assign this value to U so U becomes 4 we will print this value on the console and then we'll simply Traverse the adjacent nodes to four so here in the diagram you can see the adj and noes to four is only two so if we see the adjacency list of index 4 so it would look something like this that there is only one note which is adjacent to four so V becomes 2 we'll check whether two is visited or not so here you can see two is already visited because the value at index two of the visited array is true so we simply es skip this if block and here we already visited all the nodes adjacent to four so therefore this for Loop will terminate we'll check whether Q is empty or Not So currently you see Q is empty therefore condition in V block comes out to be false so friends here you can see that we have visited each and every node of this graph using bread first search algorithm and you can see in the output that we have visited all the notes level by level so we started with level one which is zero so we visited it then we went to level two where there were one and three so we visited those two notes then we went to level three where the only node was two so we visited two and then we went to level four where the only node was four so we visited four so friend this was the demonstration of the algorithm now let's go to eclipse and see the working of this code in our previous tutorial we actually saw the demonstration of breadfast search algorithm in Java so in this tutorial we will actually code that algorithm and see it's working so friends in my previous tutorial I created one class by name graph and we represented graph using an adjacency list so friend in order to understand and more about graph you can watch my previous tutorials so in this tutorial we will actually code the bread search technique so here I will be providing one method by name BFS and as we know that this method will take a source value which would be nothing but a starting point from where we will actually start our bread first search so in the first step what we do is we actually create a Boolean array which will actually keep the track of the visited notes I'll give the name as visited and friends here you can see that to this graph we actually storing the number of vertices into this instance variable V so the size of this Boolean array would be V moving ahead and then we'll simply create a queue so we'll import it from java.util package friends moving ahead we will Mark The Source node as visited by assigning a value true to the visited array at index s and then we'll simply offer s into the Q which we actually discussed in our previous tutorial then we'll simply provide a while loop and in inside this Val we place a condition that whether Q is empty or not so this Val execute if Q is not empty so in the first step what we do we simply pull an element from the Q and after pulling the element from Q we simply print it on the console so friends whatever the element we have pulled from the queue then we simply Traverse its adjacent notes which we actually discussed in our previous tutorial so we'll provide a for Loop which will Travers the Adent notes to U so let's say we give it as V and in order to get the Adent notes to U we simply bring the adjacency list at index U so friend in order to understand this more you can watch my previous tutorial that what is adjacency list and how we can fet the link list associated with and any particular index moving ahead we will check that whether we is visited or not so if it is not visited then we'll simply Market has visited by assigning the value as true and then we'll simply offer it to the queue so friends in our previous tutorial also we discussed that this Boolean array is kept to keep the track of the visited notes we are using this Q which will help us in traversing of this graph level by level so what here we do is we actually visit a particular node at level and after visiting it we go to its next level so friend this is the algorithm for the breadfast search now let's test it's working so here you can see we already created a graph of four notes so here we will apply this breadfast search to the graph which we saw in the slide so that slide at five notes so I will provide a value of five here and here you can see that there is an edge from 0 to 1 1 1 to 2 2 to 3 and 3 to 0 so we'll provide one more Edge from two to 4 which we actually saw in the slide and then we'll finally call the bread first search method and let's say we are giving the source node as zero so if I run this code now so friends here you can see it printed 0 1 3 2 4 and we also know that as we have started from zero so this was at level one and from zero 1 and three were connected which we actually saw in the previous tutorial so they printed after that two was connected to 1 and three so then two was printed and finally four was connected to two so four got printed so here you can see that we have TR each and every node level by level I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss depth for search of an undirected graph so friends in our previous tutal we actually discussed bread for such traversal of a graph so in this tutorial we'll discuss the iterative way to perform depth for such traversal of a graph so friends here you can see that we are given an undirected graph so by underated graph we mean that that edges they don't have any direction so if you are on any particular note let's say zero then we can go to one and if you are on one then we can go to zero so so the edges don't have any direction therefore this is an undirected graph so here you can see the algorithm to perform dep for search of an undirected graph so let's see the demonstration of this algorithm step by step so friends whenever we perform dep first search on an undirected graph we usually pass in the source node that from where we need to start the depth first search so let's say we start our depth first search from Z so the value of s will become zero so friends whenever we Traverse any undirected graph we usually keep the track of its node through a Boolean array which actually tells us that which node is visited and which node is not because here you can see the graph may contain a cycle and we don't want to visit any particular node more than once therefore we keep the track of each and every note into this Boolean array so whenever we initialize this array we actually pass the size as the number of vertices so here you can see the number of vertices are five so this Boolean array will look something like this that here each index represent a node and at the start each and every value in this Boolean array is false because we haven't visited any of the node till now moving ahead so friends in order to perform depth for search in an undirected graph we usually take the help of Stack so the stack data structure is nothing but Leo data structure which means last in first out so the element inserted last into this stack will be the first one to be removed for more detailed information about the Stag you can watch my previous tutorials so here in this step we'll simply create a stack of integers So currently stag is empty moving ahead so here first we push the source node into the stack so zero will be on the stack moving ahead so friends whenever we want to perform depth first search of an undirected graph we are providing a while loop and inside this value we are providing a condition that whether stag is empty or not so when the stag is not empty this while loop executes So currently you can see stag is having one element therefore stag is not empty so the condition in while block comes out to be true so in the first step what we do we simply pop the element from the stack and we'll assign it to a integer variable U so it would look something like this that zero will be popped out and it will be assigned to integer variable U so U is having value as zero moving ahead so then we actually check that whether we have actually visited zero or not so here in the visited array at zero to index we see the value So currently you can see the value is false therefore we haven't visited this node so the condition in IFL comes out to be true and in the if log we simply Mark the value of index0 is true that we are now about to visit this node and we'll simply print it on the console so zero is printed on the console moving ahead so friends in depth forar what we do is whenever we visit any particular note then we look for its adjacent notes so here the adjacent notes of Z are 1 and three and in our previous tutorial we also discussed about the adjacency list so the adjacency list of zero would be a link list having the values as 1 and three so it would look something like this the agency list of zero will have values as 1 and three because these two notes are to zero for more information about the agent list you can watch my previous tutorials on graph so here we are providing a for Loop which will iterate over each and every element of this adjacency list so we'll start from one the value of V becomes one and in the for we'll check whether we have visited V or not so value of V is 1 and the value at index one is false therefore we haven't visited this node so the condition in if block comes out to be true so in the evlog we simply push one on the stack moving ahead after visiting one we go to three so now V becomes three we check whether we have visited three or not so here in the visited array at index 3 the value is false therefore we haven't visited this node so the condition in IFL comes out to be true and we'll simply push three on the stack moving ahead so friends now we have traversed each and every element of this adjacency list so this for Loop will terminate and the call will reach back to this while loop so in the while loop we again check whether stack is empty or not so here you can see stack has two elements therefore it's not empty so the condition in while block comes out to be true so in the first step we simply pop an element from the stack and we'll assign it to U so U will hold the value as three moving ahead we then check whether we have visited the value three or not so here you can see in the visited array at index 3 the value is false therefore the condition in if block comes out to be true so in the F block first we Mark the value of index 3 as true that we have visited this node and and then we'll simply print it on the console which signifies that we have visited this node so friends after we visited three we look for its adjacent nodes which is 0 and two so the adjacency list of three will look like that it has values 0 and two which are adjacent to three and we'll provide a for Loop and we'll iterate over each and every element edes to 3 so we'll start with 0o so V becomes Z we'll check whether we have visited zero or not so here you can see the value at index0 is true therefore we have visited this node so the condition in if log comes out to be false now V becomes two we check whether we have visited two or not so here you can see the value at index 2 is false therefore we haven't visited this node so the condition in if block comes out to be true and we'll simply push two on the stack moving ahead so friends we have visited each and every adjacent notes to three so this for Loop will terminate and the call will reach back to this V Loop we again check whether stag is empty or not so here you can see stag is not empty because it contains two elements so the condition in V block comes out to be true in the first step we'll simply pop an element from the stack and we'll assign it to U so here U will become two we check whether we have visited two or not so here you can see the value at index 2 is false therefore we haven't visited this node so the condition in IFL comes out to be true and in the if loog first will Mark the value at index 2 to be true that we have visited this node now and then we'll simply print two on the console moving ahead so friends after visiting this node we actually look for it adjacent nodes which is three 1 and four so the adjacency list of node two will look something like this that it has three values 3 1 and 4 because these three nodes are connected to two and we will iterate over each and every element of this link list so we'll start start with three so here V becomes three we check whether we have visited three or not so here you can see the value of index 3 is true therefore we have visited the node three so the condition in if blog comes out to be false and now V will become one we check whether we have visited one or not so here you can see the value of index one is false therefore we haven't visited one so the condition in if block comes out to be true and we'll simply push one on the stack and now V will become four we will check whether we have visited four or not so here you can see the value at index 4 is false therefore we haven't visited this node so the condition in if block comes out to be true and we'll simply push four on the stack so friends here we have visited each and every element adjacent to two therefore this for Loop will terminate and the call will reach back to this while loop we check whether stag is empty or not so here you can see stag is not empty because it contains three elements so the condition in V block comes out to be true we pop the element from the stack and we'll assign it to U so the topmost element on the stack is four so four will be popped out and the value will be assigned to U so you will have four we check whether you have visited four or not so here you can see that value at index 4 is false therefore we haven't visited four so the condition in if loog comes out to be true and in the first we'll mark the value at index 4 to be true that we have visited this node and we'll simply print it on the console so friends after visiting node 4 we'll look for it adjust notes so here you can see the adjacency list of four will look something like this that the link list will have only one element which is two because only two is connected to four and here we are providing for Loop so that we can iterate each and every element adjacent to four so we'll start with two so your V will become two and we check whether we have visited two or not so here you can see the value at index 2 is true therefore we have already visited this node so the condition in if loog comes out to be false and also friends here we have visited each and every element adjacent to four therefore the for Loop will terminate and call will reach back to while loop we again check whether stag is empty or not so here you can see stack has two elements therefore it's not empty so the first step will simply pop the element from the stack and we'll assign it to you so the last element inserted in the stack is one therefore one will be popped out so U will now have value as one one moving ahead we check whether we have visited one or not so here you can see the value of index one is false therefore we haven't visited one so the condition in if blog comes out to be true so in the F blog we simply Mark the value at index one to be true that we have visited this node now and we'll simply print it on the console and then we'll provide a for Loop so that we can Traverse our adjacent nodes to one so friends after visiting the node one we'll look for its adjacent nodes which is nothing but 0 and two so the adjacency list of one will look something like this that node adjacent to one is 0 and two so we'll provide a for Loop and we will iterate each and every element adjacent to one so we'll start with zero so V becomes zero we'll check whether we have visited zero or not so here you can see the value at index 0 is true therefore we have already visited zero so the condition in if block comes out to be false now V becomes two and we'll check whether we have visited two or not so here you can see the value at index 2 is true so the condition if BL comes out to be false and also friends we have visited each and every node adjacent to one so this for Loop will terminate and the call will reach back to this while loop we again check whether stack is empty or not so here you can see stack has one element therefore it's not empty so in the first step we'll simply pop an element from the stack and we'll assign it to U so one will be popped out and U will have value as one then we'll simply check whether we have visited one or not so here you can see the value at index one is true therefore we have already visited the node one so the condition in IFL comes out to be false we again check whether stag is empty or not so here here you can see his tag is empty so the condition in V block comes out to be false and while block terminates so friends here you can see using this depth for search algorithm we have visited each and every node of the graph so friend in this tutorial we actually saw the demonstration of this algorithm now let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually discussed the depth for such algorithm of an undirected graph so in this lecture we'll actually code the algorithm and we'll test it's working so friends in our previous lectures we actually created one class by name graph and you have implemented the graph using the adjacency list we also discussed the bread for search algorithm so in this tutor we'll actually discuss the depth for search algorithm so here we will be creating one method as public void DFS and we also know that the dep for search will start from a source node so s will represent the source node so friends in our previous lecture we actually saw the demonstration of the depth for search step by step so friend in the first step we'll simply create a Boolean array we'll give it a name as visited and we'll initialize this Boolean array with the size equal to the vertices of the graph so friends here we have created this Boolean array which will keep the track of the notes which we already visited because while traversing a graph there may come a situation where graph contains a cycle so in order to visit a particular note only once we usually create this Boolean array which will keep the track of the notes which are visited and then we'll create a stack so we'll import the stack from java.util package so friends we are using this stack which will help us in performing dep for search and its significance we already discussed in our previous lectures so after creating the stack we'll simply push The Source vertex on the stack and then we'll provide a while loop so in this value will provide a condition that whether stack is empty or not so this V Loop will keep executing with a condition that whether stack is empty or not so the stack is not empty this V Loop will keep on executing so inside this V loop as we discussed in our previous lecture that we pop the element from the stack and we'll assign it to you and then we simply check that whether we have visited you or not so if you have hav visited you so the condition in IFL comes out to be true so first we'll mark the value at index U to be true that we have visited this node and we simply print U on the console so friends after visiting you we simply provide a for Loop Loop which will iterate over each and every element adjacent to youu so friends here after visiting any particular note we look for its adjacent notes and we can get the adjacent notes through the adjacency list and we'll simply iterate each and every element of this adjacency list one by one so in the for Loop we simply check that whether the adjacent node to you which is V has been visited or not so if the node is not visited we simply push it on the stack and this we do for each and every element adjacent to the already visited node so friend this is the code to perform for search over an undirected graph now let's test it working in the main method so here you can see we have created a graph with five notes and we have added the edges between the notes say from 0 to 1 1 to 2 2 to 3 3 to 0 and 2 to 4 so this is the same graph which we discussed in our previous lecture so here in the main method we simply call the DFS method and we'll pass the value of the source node as zero that we have to start our Dev for search from the node zero so if I run the code now so friends here you can see it printed each and every node of the graph in the following order first it printed zero then three then two then four and then one so this is the same outut which we discussed in our previous lecture while demonstrating this algorithm step by step so friend this is how we actually perform a dep first search over an undirected graph I hope you like this video thanks have a nice day hello everyone so in this video we will be looking into the recursive depth for search algorithm to Traverse an undirected graph so in our previous video we actually saw the depth for search using the iterative approach so in this video we will see that how recursive algorithm works so here you can see that this is the algorithm which is recursive depth for search here you can see this DFS is calling itself here making it recursive in nature so let's see the demonstration of this algorithm step by step but before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update in our previous video where we discussed about the iterative approach we used the stack data structure to Traverse the graph and in our previous algorithm where we saw bread for search and depth for search itated there we were given with a source vertex and from there we started our DFS but usually the graph is given in form of like this so here you can see 0 1 2 3 4 they are connected together and there is one more node which is five so this vertex is not connected with rest of the elements so basically a graph is provided like that that there could could be components which are basically disconnected so we need to visit this graph and its each vertex so here we actually use this for Loop which Traverse each and every vertex and help us visiting the vertex using dep for search so let's see the demonstration of this algorithm step by step so here as the algorithm is recursive we will keep the track of the DFS method which is getting called on call stack and here you can see when we are calling DFS on any particular vertex V after visiting it we try to Traverse it adjacent nodes one by one so those adjacent nodes we denoted by W and if they are not visited we call the DFS again we pass the W value to it because we want to not Traverse the adjacent vertex to V so when this DFS will be called this W will become our new V so we need to keep that in mind while traversing our call stack so at the start we simply call DFS so one method is on the call stack now friend as this graph can be connected and can form a cycle so when we perform DFS this visited array which is Boolean help us in that which which notes are already visited or which which vertex are already visited so this capital V we already discussed in our previous videos that that this represent the number of vertexes So currently we have six vertex from 0 to 5 so we created a Boolean array of six elements we start from V equal to 0 so V is zero we first check whether V is already visited or Not So currently we see at index0 VF false so therefore it's not visited so we call DFS and as we are leaving this DFS at line number five we update line number here so now there will be one more method on the call stack with vs zero and the visited array you can see here so when we call DFS on any vertex the first thing we do is we Mark that vtex as true that we have visited it so we mark it as true and here you can see we made it yellow and by visiting the node we mean processing the node so here we are simply printing it on the console so 0 will be printed now we look for the adjacent nodes to vertex 0 so this adjacency list we discussed in our previous videos so this adjacency list is a instance variable which holds all the vertex and their corresponding edges so when we do adeny of zero it has two elements 1 and three because these two elements are adjacent to Zer and they are connected so it looks like this so after traversing zero we try to Traverse is adjacent nodes so we can start from any Noe so here we pick three so here you can see W becomes three we check that whether three is visited or not so here you can see three is not visited so we call recursively for search on three so this three which is W when we will call DFS again it will become our new Vortex to visit and here you can see we are leaving this DFS on line number 15 so we need to update line number here because once this DFS will finish we should know that from where we need to start this DFS so we update line number 15 here and there will be one more method on the call stack with our new V S3 so you can think of it something like this we are going like this moving ahead V becomes three we Mark three as visited like this and then we print it on the console and then we look for the adjacent elements to three so if we see the adjacent elements to three we will get zero and two so the adjacency list of three will give us 0 and two now we need to visit 0 and two because those are adjacent to three so we can start with any node so we pick 0 so w becomes zero we check whether Z is already visited or not so here you can see 0 is already visited marked as yellow so this condition comes out to be false so now we go with vertex 2 so w will become two now we check whether two is visited or not so here you can see two is not visited it is marked as is false so this condition comes out to be true and now we again call DFS with WS2 we are leaving at line number 15 so first we'll update line number here there will be one more method on the call stack where V will become two because now we need to Traverse two so we first Mark two as visited like this then we print it on the console two and then we try to Traverse its adjacent vertices so here you can see adjacent to two is three 1 and 4 so the adjacency list will give us 3 4 1 so we can start with any node so we start with three so w will become three here we check whether three is visited or not so here you can see three is already visited so this condition comes out to be false we then take four W becomes four we check whether four is visited or not so four is not visited so then we do the DFS on four so we call DFS with WS 4 we first update the line number here because we are leaving this DFS now so there is one more method on the call stack with our new Vortex to visit is four so V becomes four we first Mark index 4 as true because we are about to visit it we print it on the console so four gets printed and now we check for the adjacent elements to four so here you can see the elements connected to four is only two so its adjacency list will have have only two so we try to visit two now so w becomes two we check whether two is visited or not so here you can see two is visited so this condition comes out to be false and here you can see the adjacent elements of Vertex 4 is all visited so now this for Loop will terminate and this DFS will also get terminated and our call will reach to that DFS which actually called this DFS because we are done with the all the edges and elements of vtex 4 so this method will be removed from the call St and the execution point will reach here and we know that we had left this DFS at line number 15 so we start our execution from line number 15 and when we left this DFS the value of V was 2 and the value of w was 4 so it means we were traversing the adjacent elements of two and V just visited four so if we see the adjacency list of two we visited three already then we went to four so we have done with the four also so now our time is to visit 1 so w will become one in the next iteration one we check whether one is visited or not so one is not visited so this condition comes out to be true and we call DFS again with WS 1 so we update the line number 15 here there will be one more method on the call stack with vs 1 we Mark vertex one is visited we print one on the console so this is also visited and now we actually check the adjacent elements of one so here you can see it as 0 and two 0 and two so we start with 0er W becomes Z 0o so here you can see Z is already visited so this condition comes out to be false then we go to vertex 2 W becomes two and two is also visited so this condition comes out to be false so here you can see all the elements adjacent to vertex 1 are visited so this for Loop will terminate and this DFS method will be removed from the call strike and and execution point will reach here so we start this DFS from line number 15 and we were actually traversing Vortex 2 and the recent adjacent element we visited was 1 so w becomes 1 and V becomes two so if we see the adjacency list of two we are done with 3 4 and 1 so in the next iteration this for Loop will terminate because there are no more edges and elements to Vortex 2 so now this DFS will end and call will reach to its previous DFS we will start from line number 15 and we had left this DFS when value of V was three and the recent adjacent an element to three which we tried to visit what two so V is 3 W is 2 so if we see the adjacency list of three here you can see Zero we already visited and we went to two and two also we visited so now this DFS will end for Vortex 3 execution Point reached here we start from line number 15 and when we left this DFS we were actually visiting the adjacent elements of Vex 0 and the recent we visited was three so V is zero and W is three and if you see the adjacency list of zero so here you can see the recent element we visited was three so now we go with the vertex one so w becomes 1 1 we check whether one is visited or not so here you can see this visited array is helping us to not to visit the vertex again because one is already visited it is marked as true so this condition comes out to be false so now we are done with the adjacency list of zero so this DFS will end and this method will be removed from from the call St and we go back to the starting DFS method where we left at line number five so we start from line number five and we are done with visiting zero vtex so here you can see this for Loop will now help us in visiting five because when we started with zero all these nodes were directly or indirectly connected with zero so we visited everyone using the DFS so this file is not connected to any of these vertices so using this for Loop we will visit f as well so we'll increment v v becomes one so vertex one is visited so we do nothing V becomes two so two is visited we do nothing V becomes three three is also visited so we do nothing four is also visited and now V becomes five so here five is not visited so we call DFS on vertex 5 we update the line number and here we call this DFS with five so here it should be five because we are leaving this DFS when vertex V was 5 so now we call DFS on vtex 5 we Mark vtex as visited this is visited now we print it on the console and then we try to visit the Vex 5 adjacent elements so here you can see there are no adjacent elements to Vex 5 so this for Loop will terminate and this DFS method will be removed from the call stack and we go back to the previous DFS at line number five where V was five and then we increment V it becomes six so now this for Loop will terminate and everything will be removed from the call stack so here you can see in this order we visited each and every vertex of the graph and here using this for Loop we even visited vertex which were disconnected so friend this was all about the recursive dep first search I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss that what are connected components in an undirected graph so friends here you can see that we are given a graph having six notes from 0 to 5 now here if you see that we have three connected components so one is having nodes zero 1 and three which is this connected component another connected component is two and four and the third connected component is a component having only one node which is five so usually with a graph we are given a graph in the form of connected components so one such query comes is that we need to evaluate that in a graph how many connected components are there so in this graph we have three connected components and also once such query comes is we are given with two vertices let's say 0 and two and we need to find whether 0 and two are connected or not so here you can see 0 is in the first connected component and two is in the second connected component 2 is connected with four 0 is connected with 1 and three so 0 and two are not connected so such queries are given so usually in real world let's say we can think of this connected components as a graph of a small region where this three nodes forms a road this two forms another road and there could be a query that whether this road is connected with this road or not and similarly for other applications we can think as Network connections we just need to query whether this connection and this connection are connected or not so such queries can be handled via connected components so in this video we are going to see the algorithm that how we can figure out the numbers of connected component and how we can figure out whether any node is connected to another node or not so here is the algorithm and here we are using the same graph which we discussed in our previous slide so let's see the demonstration of this algorithm step by step so friends before we start in case if you want to master data structure in algorithm you can subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that to find the number of components and to find whether any of the vertexes are connected or not we need to process each and every node so here what we do is we apply the depth for search now this algorithm is recursive in nature here you can see dep for search is again calling here itself so it's a recursive algorithm so therefore we will maintain the calls to the DFS in the call Track and we need to keep the track of the vertices we are visiting so at the start we call DFS now when this method starts execution there will be one method on the call stack by name DFS and now this method will start its execution so we are storing the state R of v w and count for this DFS and this we will do for each and every recursive calls here because when we are calling this DFS from this DFS this method will store the state into the call stack and then it will again call DFS so once this DFS will end the method will return to this DFS and we will assign back the values of the variables from where this DFS left moving ahead so friends here you can see that as we are calling this DFS on an undirected graph there could be a possibility that this graph contains a cycle like this so what happens is we create a Boolean array visited now this Boolean array will help us to check whether any of the vertices are already visited or not because let's say if we visit zero then 1 and then three then from three if we go to zero this Boolean array will help us knowing that Zer is already visited so in order to keep the track of visited node we create a Boolean array and here in our previous videos we know that the capital V is nothing but number of vertices So currently we have six vertices from 0 to 5 so this Boolean array will have six vertices from 0 to 5 index and each index corresponds to a node in a graph so at the start all the values of the visited array will be false because no node is visited as of now now we will create yet another array which we will call component ID we will see its significance later but here you can see this component ID will store the ID of any particular component in the form of integer so you can think that as we have three components here so this component ID for 3 0 1 will store let's say an ID of zero for example for two and four it will store one and for five it will store two now this will state that we have three components 0 1 and 2 node 3 belongs to zero component 0 belongs to 0 component and 1 belongs to 0 component so that will be evaluated with this component ID and similarly two will belong to component one four will belong to component 1 and five belongs to component 2 so there could be so many notes in a graph so this component ID will denote a group of notes which will be represented by an ID so we will see its significance later so this array would look like this that at the start for all the vertices the value will be zero or what we can do is we can also initialize this array as as a wrapper of integer so every value will be null stating that the notes are belonging to no component at the start moving ahead then we will create a count variable now our task is to First count number of connected components and our second task is to return return true or false for a query that whether X and Y are connected or not so we are using this algorithm to figure out these two problems so we are creating a count variable which is suggesting that how many connected components are there in this graph so at the start in this DFS method count will be zero because we are yet to start the processing of this graph also friends here you can see in this method we are creating these three things visited array component ID array and count so usually for these two queries we take these three variables at the class level so that we can use them directly in any of our methods but here for time being I have created this three variables in the method itself so that I can demonstrate the algorithm that how it works so these three things you can create outside of the method at the class level we can make these variables as instance variables so for time being you can think that these are part of the method itself and for the actual DFS algorithm we are actually passing them directly into the method or else if they are at instance level we don't need to pass them like this now we will start the processing of graph from vertex 0 and it will go till it is less than the number of vertices which is six we need to go from 0 to 5 so at the start V is zero so we update zero here now the first thing we check is whether V is already visited or not so here you can see as we are starting the processing of the graph V is not visited here value at zero index is false so therefore this condition comes out to be true which means we can apply the depth for search on vertex zero now so here now this DFS will be removed from the call strike and this DFS will be called so first we update line number here because we are leaving this DFS now so we are leaving at line number seven so that when this DFS method will finish we come back to this DFS and we start the execution from line number seven itself and we assign this values back to V so now there will be one more method on the call stack and the execution point will reach to that DFS with v as Z count as Z because we are passing count z and v 0 we will see what this W is here and visited array and component ID array you can refer here now when we will call DFS on any particular node what we do is we first process that node and how we can process that node is we can perform any typical algorithm on that particular node and we first Mark that node as visited that we are done visiting this particular node so in the visited array at zero index we simply assign a value true stating that we have visited node zero like this we have visited this node and here what we can do is we can either process some algorithm on top of this node we can print this node and we can do anything on this node based on the algorithm we are trying to process and now what we do is this count variable which we have passed into the DFS here this count variable will help us in finding the ID of the component so as we discussed that these three nodes belong to component ID zero this two belongs to one and this belongs to two so this ID can be anything so here what we are doing is we are taking the count only as our ID so in the component ID array at vertex 0 we update count as zero like this now after visiting a particular node what we do is we recursively visit its adjacent nodes so in our previous video we have discussed that what this adjacency list is this this is actually a list we are passing a Vertex zero because value of V is zero and we are asking to return return its adjacent notes so it would look something like this I'll remove this so here this list states that 0 is connected to 3 and 1 and it is denoted in the form of an adjacency list you can watch my previous videos to understand more about this so here what we doing is we are iterating the nodes one by one so 0 is connected to three and 1 so we can process these nodes in any order so this for Loop will process one one node so at the start value of w will be three let's say we are taking three to visit like this now we need to visit Three so what we do is first we check whether we have already visited three or not so here at index 3 we have a false value it means we haven't visited three so now our task is to recursively call DFS with W will become our new V in the next DFS call and we are applying this DFS now for Vortex 3 because we haven't visited this Vortex so before calling this DFS we know that we are leaving this DFS at line number 18 so we'll update line number first here like this and then this DFS will be called so there will be one more method on the call stack like this an execution point will execute this DFS here W was three when we called this DFS it becomes our new V so you can think it is going like this so now we are applying this DFS on Vortex 3 we have passed count as zero as we are directly Pro propagating the count to this DFS so V becomes three now we know that we haven't visited 3 so we will first visit three by marking the index 3 as true like this that we have visited three now and in the component ID array at index 3 we will assign the value Z because value of count is zero like this now this zero is actually telling us that this zero and three are actually connected because their IDs are same after visiting three we will visit its adjacent notes so we will iterate the adjacency list of three and it has only 1 Note 0 because 3 is connected only to zero so at the start W will be zero like this and now as we are process processing the adjacent nodes of three we first check whether Zer is already visited or not so here you can see at index 0 we have value true it means we have already visited zero so this condition comes out to be false and here you can see for vertex 3 there are no more nodes adjacent to three left to be traversed so this for Loop will terminate and after this for Loop gets terminated this DFS method will also get terminated and this DFS will be removed from the call stack and execution point will reach to this DFS and here we know that we had left the previous DFS at line number 18 so we start from line number 18 at that moment V was at zero so V will come back to zero W was at 3 and if we see the adjacent list of zero we have processed one of the adjacent notes of zero which is three now in the next iteration we will pick one and we will apply DFS on one because we need to visit one and then visit is adjacent notes recursively so w becomes one here we check first that whether one is already visited or not so at index 1 we have a value false it means one is not visited so we will call DFS again and we are leaving this DFS at line number 18 so we'll update the line number here 18 there will be one more method on the call stack as we have called this DFS with WS 1 this W will become our new V here for this DFS so it will go like this and count will go with a the value zero only the first step we do is we Mark the vertex 1 has visited so at index one we mark it as true like this that we have visited one now in the component ID array at index one we put the value of ID as zero which suggest that 0 1 and three are connected now after visiting one we will visit its adjacent notes recursively so if we call the adjacency list of one you will see that it is connected only to zero so we have only one Vortex so w will start from zero we'll first check whether zero is already visited or not so here can see Z is already visited in the visited array at zero index we have true so this condition comes out to be false and there are no more vertex adjacent to one left to be traversed so this for Loop will terminate and this DFS method will also get terminated and removed from the call stack so execution point will reach here we had left the previous DFS at line number 18 so we'll start from line number 18 at that moment V was zero and w was 1 and V was Zero it means we were visiting the adjacent notes of v We visited three and we have visited one recursively so now there are no more notes in the adjacency list of zero to visit so this for Loop will terminate and this DFS method will also get end and it will be removed from the call St and execution point will reach to this DFS which we left at line number seven so V start from line number seven at that moment V was at zero so here you can see that after performing the DFS on any of the node here we started with zero it recursively visited its neighboring notes so once this DFS will end we know that we have visited one component fully so now what we do is we simply increment count so our count becomes one now this count is suggesting that we are done processing of one connected component and we have found one connected component so count becomes one we'll increment v v becomes one now it means we are going to the vertex V and trying to apply DFS on vertex V so first we check that whether one is already visited or not because there could be a possibility that its previous Vertex or any of its previous vertex must have visited one because one must have been connected to that vertex so here you can see one is already visited so this condition comes out to be false we will increment v v becomes two we check that whether two is visited or not so here at index 2 we have a value forse it means 2 is not visited so we can apply the DFS now on Vex 2 so we are leaving this DFS at line number seven and we are calling this DFS with v or Vortex S2 so there will be one more method on the call stack with v S2 and count as 1 first we Mark two as visited like this so here I'm just representing it with a different color in the component ID at index 2 we put one now here this count was increased so our ID also increased which also help us in figuring out that two belongs to a different component now our task is to visit the adjacent noes of two recursively so two is only connected to four so adjacency list of two will have only node four so we'll start with four first W becomes 4 we first check whether four is visited or not so four is not visited so we call this DFS with W as 4 so this four will become our new V in the next DFS call so first we update line number here because we are leaving this DFS and there will be one more method on the call stack so the W which was in previous DFS becomes our new V and count is propagated directly we first mark four as visited here like this and in the component ID array add Vertex 4 we assign a value one this suggests that two and four are part of one single component because they have same component ID now we'll Traverse the adjacent notes of four so adjacency list of four will have only one vertex which is two so w starts from two we first check whether two is visited or or not so here you can see index two we have value true so two is already visited so this condition comes out to be false and this for Loop will terminate because there are no more notes adjacent to four left to be traversed and this DFS method will end and execution point will reach to previous DFS we start from line number 18 at that moment V was at zero so V comes back to zero W was 4 which suggests that we were visiting the adjacency list of two which was this we know that we recently visited four and there are no more adjacent nodes to two left to be traversed so this for Loop will terminate and this DFS will be removed from the call stack and execution point will reach to previous DFS we start this DFS at line number s at that moment V was at 2 so it suggests that we just finished one more DFS on one of the vertices which was two and it must have marked its connected vertices in the visited array so we'll increase the count now because we are done processing the second connected component so count becomes two will increment V so V becomes three now we need to apply this DFS again on vertex 3 but first we check whether 3 is already visited or not so here you can see three is already visited so this condition comes out to be false we increment v v becomes 4 4 is also visited so this condition comes out to be false we increment v v becomes five so here you can see vtex 5 is not visited so this condition comes out to be true so now we'll app DFS on vertex 5 so we are leaving this DFS at line number seven so we update line number seven here and there will be one more method on the call stack with vs5 and count 2 now the first thing we do is we mark five as visited like this and the component ID array at index 5 we assign a value two because value of count is two now here it suggests that this five belongs to a different component because value of count has changed now we'll visit the adjacent notes of five so here you can see in this connected component we have only one node and five is connected to no other node so therefore this for Loop will terminate and this DFS method will also end execution point will reach to this DFS we start from line number seven and vs5 so after this DFS is done we know that we have just visited one more connected component so we increase the count count becomes three we'll increment v v becomes six and we know that we have only nodes from 0 to 5 so this for Loop will terminate and this DFS will be removed from the call strip so now here you can see if you see in the visited array we have visited all the elements in the component ID array you can see 0 0 and 0 are at indexes 0 1 and 3 which suggest that 0 1 and 3 are connected if you see 2 and four they have a same value 1 1 it means they are connected and here if we see at index 5 we have two it means it's a connected component having only one vertex so friends here you can see that if we take out this three variables as our instance variable and we can provide one method as something like public hint get count of connected components so this we can return the value of count like this so this will solve our first query the second query we can provide a method as public Boolean and we can give the method name is is connected and to this method we pass X and Y so here we can simply return comp ID of X whether it is equal to comp ID of Y so let's say if we pass XY as 0a 2 so this is our X and this is y so the value at index X which is 0o we have zero and value at Vex 2 have one so here you can see we are comparing whether 0 is equal to 1 or not it means this condition comes out to be false and we return false stating that 0 and two are not connected now for for example if we pass three and 1 like this so 3 is X and Y is 1 so comp ID of three we are checking it with comp ID of one so this will give value zero and this will give value zero so both values are equal and this condition is true so we simply return true stating that three and one are connected and they are part of the same component so friends this was all about the connected components in an undirected graph I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem number of islands now let's move ahead and see what this problem is and how to solve this so here we are given an M cross n Matrix like this which is 2D binary grid so binary grid we mean that we have this Matrix having only ones and zeros now in which ones represent a land so you can think wherever we have one it actually represent a land and zeros as water like this now our task is to return the number of islands now what do we mean by Island so as per the definition in the problem you can see an island is surrounded by water so this is the one thing that an island is surrounded by water and second is formed by connecting adjacent LS horizontally or vertically so this is a land this is a land so one thing is there should be a connection horizontally or vertically and second they should be surrounded by water like this and we may assume all four edges of the grid are surrounded by water so beyond this grid here you can think that there is only water it means that it has zeros so here we have zero here we have zero here we have zero so here this three ones form an island because these three are connected horizontally and vertically and they are surrounded by water this single one forms one Island because it is also surrounded by water and this one also is surrounded by water so the answer is three we have three number of islands we don't have to consider this diagonal relationship as per the problem we need to look horizontally or vertically so here you can see that how we can solve this problem is if you look closely then we are given with a graph indirectly here if I plot this one so this is one node and the node adjacent to it is also one so we can think that there is a connection via this Edge horizontally like this and there is a edge vertically because we need to consider vertical Edge also so this forms another connection like this so you can think this island in the form of this graph and if we look closely to it it's look like this one one one like this so you can also think that we are given with this five notes of a graph that they are connected horizontally and vertically and if there is a vacant space here it means that it is surrounded by water so in one of our previous videos we discussed about connected components so this forms one connected component this forms another connected component and this forms another connected component and we also discussed that how we can process a connected component and we also discussed that how we can find the number of connected components so this problem is very much similar to that so in the connected components problem we applied the DFS which is a depth first search so here also we'll apply the same so the only difference is there we had this actual nodes connected by edges and here we are taking this adjacent lens horizontally or vertically in the form of edges so keeping these constraints in mind let's move ahead and see the demonstration of this algorithm step by by step so friends before we start in case if you want to master data structures and algorithm you can subscribe to my channel and click the Bell icon so that you never miss any update now this is the algorithm to find the number of islands we are given with a matrix where we have only ones and zeros and they are provided in the form of a character and here we need to return return the number of in this grid so here we have created integer variable number of islands and at the end we are returning this number of islands so let's see the demonstration of this algorithm step by step we call the number of islands method passing in The Matrix which is our grid now let's say we take the same example where we are given with this Matrix and we know that we have three Island here one is this island another is this and the third one is this now let's see how we can find out the number of islands and we also know one property that LS should be connected vertically or horizontally so this can be treated as a vertex of graph and this can be treated as an edge so this is a horizontal Edge and this is the vertical Edge so so friends here you can see that wherever we'll find land we need to apply depth for search on top of it so that we can figure out that how much deep that connection is via this property now here we are given this m cross n Matrix so this m cross n represents row and column so the number of rows which is m is given by grid. length which is four we have four rows 1 2 3 and four which with an index of 0 1 2 and 3 similarly we have four columns denoted by n so this is First Column second third and fourth column with the index of 0 1 2 and 3 so friends when we apply dep for search here we know that we need to consider horizontal and vertical relation so here let's suppose we are given with this so of graph let's say here we have this one so it must look like this so if we are applying dep first search on top of it we know that once we visit any particular node then we visit its neighboring nodes recursively so usually in the graph we can encounter this Cycles so here let's suppose we have visited this node then we go to this node we visit this and let's say if we are going to this node and we are visiting then here we are visiting but if we go back here this node we have already visited so this is a rough example to just demonstrate that when we return back to this node we know that we have already visited this node but how we can mark that we have visited this node because when we will reach to this node then the algorithm will keep on visiting this node again and again so we have a cycle so in order to keep the track of the visited noes we create a Boolean array or here you can see that we have created a visited Matrix here as the graph is given in the form of a grid and here each index represents a Vortex so therefore we have to create a matrix of M cross n which will actually help us to figure out that which notes are visited and which are not so it looks something like this it's a Boolean Matrix so at the start every note is unvisited being denoted by F which is false as we need to return number of islands so we initialize this integer variable with zero because at the start we haven't found any Island so the number of island is zero so friends when we apply dep first search on a graph we visit each and every node of that graph so here each index value can be considered as a node of a graph so here you can see that we have 16 such vertex and they are given in the form of Matrix m cross n so we need to apply these two for Loops to travel each and every vertex and apply the depth for search on top of it to figure out the number of violence so here I will Traverse the rows and J Will Traverse The Columns M denotes our rows n denotes The Columns so at the start I is zero J is zero so it means that we are on index 0a 0 like this also friend as we need to find the number of islands we can apply the dep for search on the nodes which have values as one because Zer represent water so when we encounter water we need to skip the water and once we found even one of the land then we can apply depth for such on top of it with an only condition that this one should not be visited because there could be a possibility that if we going in this direction then we are coming back then going down and they're going up so there could be a possibility that we encounter the nodes which are already visited so which is being tracked by the visited 2D array so the only condition we need to keep in mind is that in the visited aray at 0a 0 we should have false value it means this node should not be visited and the value of this node should be one if we encounter zero then we will simply skip this element because this denotes a water so here at the start we found one which is a land and this land is not visited so therefore we can apply dep first search on top of this one considering the graph horizontally and vertically so when we will apply DFS on top of this Grid at index 0a 0 it would look something like this that this method will now call DFS method like this so here we have this grid and this visited 2D array we pass the row as Zer comma 0 so on the call stack there will be one method DFS having row is zero and column is zero because we found one and that is not visited so here we are maintaining this call stack because this algorithm is actually recursive as we are applying the DFS we know that it's a recursive algorithm where we actually process any node and then we try to process its adjacent notes recursively so therefore this algorithm is recursive so in order to keep the track of this method calls we are maintaining a call stack this is our base case to stop this recursion we will see this later so now at the start we are processing a value at an index 0a 0 in this grid Matrix because we have found one land denoted by one and which is not visited so so here you can see this is our base case now as we will apply this dep first search horizontally and vertically in all the directions because this land can be connected to another land so let's say we have a land here if Above This Land we have another one here we have another one and here we have another one and Below we have another one so this land if you see it is connected like this like this like this like this so we need to go in four direction to figure out the extent of this island because we are given in the problem that we need to see in the horizontal and in the vertical Direction so here in the normal DFS where we are given with a vtex we visited a node and then we visited its adjacent nodes recursively here the adjacent nodes as we discussed will be given by these four directions which is up left right and down so currently what this base case says that after processing any note if we are going to a level above let's say if we are going to top of this one then we are going outside the boundaries of this Matrix because Beyond 0 comma 0 the index doesn't exist in the Matrix so here this is the base case that we may go out of the Matrix so if row is less than zero or column is less than zero then we simply return from the DFS method so this is our base case the another conditions are if row and column goes beyond this or this then also we need to return and the last two conditions are let's say if we are on this node and if we go to right so here we are finding a water which is being denoted by zero we only keep the track of the lenss which are connected adjacent and as soon as if you find a water we simply return back so here if this Grid at a row and column if the value is zero then we will simply return and one last thing is let's say if we have visited this one we went here for this one also we need to go up so we'll go back to this one but here we know that we just visited this node and came here and then we are going up so if in the visited 2D array at row and column if we find any True Value then also we need to return because we have already processed the node so this six conditions are are very important because they form our base case we should not go beyond the boundaries with this first four conditions we should not go in the water with this condition and we should not go to a land which is already visited so at the start we are within the boundaries of this Matrix because we are at 0 comma 0 this vertex is not visited and the value is 1 which is not 0o so therefore all the conditions comes out to be false so with suggest that we have found one land and now as for the DFS we will visit this land and in the visited 2D array we'll mark it as true like this so friend one property of DFS is after visiting any particular node we visit its adjacent nodes recursively and we know that in order to find the adjacent nodes to one as per the problem they should be be horizontal or vertical so we need to apply this DFS horizontally and vertically so it means we have to go in four directions left up right and down to visit the adjacent nodes of 0 comma 0 recursively so here if you see if we are in particular row let's say 0 zero here we can travel in any direction so what we are doing is we are going first to left then up then right and then down so here when we are going left it means we are going in this direction So currently here you can see that whichever box is yellow that is our current row and column which is 0 comma 0 this if we want to go in the left it means we are going in this direction so when we are going in this direction to the left row actually Remains the Same here you can see value of row is is zero so it Remains the Same as we are going on the left the value of column decreases by one so here we have colum zero here it can be minus one because we are going in this direction similarly if we going up let's say we are here and if you're going up here row is two now it becomes one so here row is actually decreasing but column Remains the Same so when we go up row decreases column remains same when we go right let say if we are here if you're going in this direction so row Remains the Same and column actually increases from 1 to two so we do call + one and if you're going down let's say if you're going down from here to here so row was one now it became two because we have reached here so row is actually increasing and column Remains the Same so this four direction we need to keep in mind if you're going on the left column decreases if you're going up row decreases es if you're going on the right column increases if you're going down row increases so this four direction we need to keep in mind because for any particular land we need to see its horizontal and vertical adjacent nodes to figure out whether it has land or water so we need to call this DFS four times because we need to visit a particular row and column in four directions going left then going up then going right and then going down so first we will go left where row Remains the Same and and column decreases by one so here you can see that we are leaving this DFS at line number8 and we are calling this DFS so first we'll update the line number here 8 that we are leaving this DFS at line number 8 so once this DFS will end we will return back to this DFS but we need to keep the track of the line that from where we left this DFS so this line number 8 will help us knowing that we had left this DFS at this line so we'll start our execution at this line and whatever the value of row and column will be we'll assign those values back to the row and column so now here you can see this method will be called where row will remain same and column will decrease by one so there will be one more method on the call stack like this here row Remains the Same and column decreased by 1 so it became minus1 it means we are going to the left so here we went outside the boundaries of this Matrix where column became lesser than zero so it means we have encountered a base case so we simply need to return back to 0 comma 0 so this DFS will end because we are not returning back so this method will be removed from the call stack exit execution point will reach here we'll start from line number eight and we have visited the left side and we came back to 0 comma 0 so we are coming back to 0a 0 and now we know that we are done with the left we need to go up so when we go up row decreases and column Remains the Same so we are leaving this DFS now at line number N9 so we'll update 9 here so there will be one more method on the call stack where row will decrease from 0 to minus1 and column Remains the Same so here you can see now we went to outside the boundaries of this Matrix in in Upper Direction so now row has become less than zero so therefore we need to return from this DFS so we will come back to 0a 0 we will start from line number nine here and we will come back to 0a 0 and now we go go towards its right so when we go towards right column increases so here it will increase from 0 to 1 because we are going to the right direction and row Remains the Same so we execute this DFS and we leave this DFS at line number 10 there will be one more method on the call stack where row Remains the Same and column increases by one because we are going towards right so now here you can see we are going to 0 comma 1 so we reached to this index which is 0a 1 so now we are within the boundaries of this Matrix so first four condition comes out to be false this condition in the visited 2D array we have false so this comes out to be false and we know that at this index 0a 1 we don't have zero we have 1 so therefore this condition also comes out to be false so here you can see all the conditions came out to be false because we are within the boundaries this value is not zero and it is not visited so it denotes that we have found an adjacent land which is being denoted by one and it is not visited so first thing we do is we mark this as visited like this and as we know that how DFS works now for this vertex we will visit his adjacent nodes recursively so now for Value 0a 1 we will apply the DFS into four directions so for this note first we'll go to left we'll update line number eight here we will have one more method on the call stack and as we are going on the left column decreases so column was one it decreased to zero row Remains the Same so it means we have reached back to this land here you can see this node is within the boundaries of this grid but if you look in the visited 2D array at row row 0 comma 0 we have already visited this node because we are actually applying the DFS from this node only we reached to this node and then we are coming back to this node so we have already visited this node so though this condition is false that we are encountering a land here but we have visited this land already so we'll simply return from this DFS and this DFS will be removed from the call stri execution point will reach here and to whichever DFS viewer we simply start from line number eight here we know that we were at 0 comma 1 so we were at 0 comma 1 so we return back to this node like this and for this node we just went to its left and came back so now we'll go up so first we update line number here because we are leaving this DFS so now there will be one more method on the call stack we are going up so row will decrease so from 0 it will become minus one like this it means from 0a 1 now we have went to outside the boundaries of this Matrix so it means row is less than zero so we need to return back because this condition comes out to be true it means we are returning back to 0a 1 now so this method will be removed from the call stack we will reach to this method we simply start our execution from line number nine here and at that moment row was 0 and column was 1 so we come back to this 0a 1 like this so with this line we went up and then came back so now we'll go towards right so first we update the line number here which is 10 because we are leaving this DFS we are going towards right now so there will be one more method on the call stack as we are going on the right column will increase so from one it becomes two row Remains the the same so we are going towards right it means we are going to 0a 2 here and here you can see that we have found a water so we need to Simply return from this node because we have found water and this is actually stopping this land to go beyond that so we have encountered a water so we'll simply return back this method will be removed from the call strike execution point will reach here we'll start our execution from line number 10 because we had left at line number 10 so we come back to 0a 1 because when we left this DFS we were at 0a 1 so we came back to 0a 1 so we visited left up right so now we'll go down here first we update line number here which is 11 then we will call this DFS again there will be one more method on the call stack if if we are going down row will increase so from zero become one column Remains the Same here so we'll simply return because we have found the water here which is zero so we simply return back this method will be removed from the call stack execution point will reach here at line number 11 at that moment we were at 0a 1 because now we are returning to 0a 1 back like this so here you can see that for this node we went to its left up right and down and after that we are done with this node so after 11 this DFS will end it means this DFS will end so this method will be removed from the call stack and we go back to its previous DFS that we had left at line number 10 so we start from line number 10 and the value was 0a 0 so we are actually returning back to 0a 0 like this because we went to its right when we visited 0a 1 here you can see that we executed DFS we went to right and now we are coming back so we have came back to 0 comma 0 so for this node now we need to go down so we'll update the line number here 11 there will be one more method on the call stack we are going down so row increase es so it became 1 from zero and column Remains the Same it means we are going down we came here we are within the boundaries of this Matrix so first four condition comes out to be false This Land Is Not visited because value is false here and we have actually came to a land so it means all the conditions comes out to be false it means we are on a valid land which is adjacent to our previous land so first we mark this land as true so in the visited array at 1 comma 0 we put a value true like this so we are putting this value true because in case if we return back to this node we can come to know that we have already visited this node now friend there could be a possibility that here we have one or here we have one so as we have reached to a land now we need to apply the DFS to its adjacent nodes as well because let's say if here we have one and then we have one then one one one so this land would have expanded till the last row in last column so we need to apply this DFS now for this node in the four directions left up right and down to figure out whether this land is also surrounded by any other land or not so now first we go to the left so it means we are going in this direction now so we update line number here eight there will be one more method on the call stack where column will decrease it becomes minus one and row Remains the Same so it means we have went outside the boundaries of this Matrix where column became minus one which is less than zero so this condition comes out to be true and as it is a r in all the conditions so if any condition comes out to be true we simply return so we simply return back to 1A 0 here so this method will be removed from the call stack we reach here at 1 comma 0 and we start our execution from line number 8 we just went to the left of 1 comma 0 so we are returning back to this node like this so now we actually go up so first we update line number here which is nine and then we are leaving this DFS so there will be one more method on the call stack we are going up so row decreases so from one it became zero so it means we have reached here so friends here you can see that from this node we actually went here so for this node this one is also adjacent so when we reached here we know that we have already visited this node so how we can figure this point out is we can simply look in the visited array at 0a 0 we find a value true so we are in the boundaries of this Matrix so first four conditions comes out to be false but here you can see this condition visited row column this comes out to be true so it means this land is already visited we need to come back so we simply return from this DFS execution point will reach here we'll start from line number nine and at that moment we were at 1A 0 so so we come back to 1A 0 because we are returning from 0a 0 back to 1A 0 here and for this note we just went to up and came back so now we go towards right we update line number 10 here there will be one more method on the call stack so we are going now towards right here where value of column will increase so from zero it became one we reached here so in this DFS we are now at 1 comma 1 so we reached here now here we have encountered a water so this condition comes out to be true so we simply return return because as we are encountering water we need to return back this method will be removed from the call stack we come back to previous DFS we start from line number 10 so we come back to 1 1A 0 like this and now we go down we just visited the right now we go down so we first update line number here which is 11 that we are leaving this DFS at line number 11 and now there will be one more method on the call stack we are going down so row will increase so from one it became two and column will remain same so with this DFS now we reach to 2 comma 0 here and as we have encountered a water here so this condition comes out to be true so we simply return back so this method will be removed from the call stack execution point will reach here we start from 11 and at that moment we were at 1 comma 0 so we come back to 1 comma 0 here and for this node we visit Ed its left up right and down and after that this DFS will end so for this node we have visited it all the directions so this will be removed from the call stack we reach back to this DFS we start from line number 11 and at that moment we were at 0a 0 so we come back to 0a 0 here so here you can see that we started our DFS with this index 0 comma 0 and after traversing recursively all its adjacent note we are returning back to 0a 0 which means that we have visited left up right and down so the last Direction We visited was down here and we came back so after this line This DFS will end which signifies that we have visited all the lenss connected horizontally and vertically so we'll return from this DFS so this DFS will be removed from the call stack and we will simply go back to the method which called this DFS at the start here and this is our condition as of now that we have visited this one this one and this one and we have found one connected component which is our Island so we'll increase the number of islands value because we have just found one Island so it becomes one moving ahead so now we are done with this note 0a 0 so we'll increment J J becomes 1 we go to 0a 1 here because there could be a possibility that from here only another land starts or another Island starts so here first we check that whether the value is one or not so here you can see the value is one but we also check that whether we already visited this land or not because in our previous DFS we started here then we visited this land and then we visited this land so we know that we have already visited this land because value is true here so therefore this condition comes out to be false because we are going only to those lands which are not visited here we have just visited this land in our previous DFS so this condition will prevent going into another DFS call so the condition in if loock comes out to be false now we'll increment J J becomes two so we are on 0a 2 here you can see that we have landed on water so it means we need to skip this element because we need to identify an island so an island can only be formed by a land which is one so if we are landing on water it that it means that we need to skip this node and proceed ahead so this condition comes out to be false because value is zero here so friends here you can see see that now we will go somewhat fast because whenever we encounter zero we'll simply move ahead because these conditions will come out to be false so we'll increment J J becomes three we'll simply skip because we have landed on water so now we'll increment J so J will go beyond the boundaries of this Matrix so this condition comes out to be false so this for Loop will terminate and the execution point will reach to the upper for Loop because now we need to process the second row so first we increment I I becomes one so now we are processing this row we are done processing this row so we start from J equal to 0 so it means now we are on 1 comma 0 we know that we have found one land denoted by one so this condition is true but we also know that we have already visited this land so so this condition comes out to be false we'll increment J J becomes one so now we are processing this value at 1 comma 1 so friends here you can see this zero this zero 0 0 0 this five will be skipped because we are landing on water and as we are traversing this Matrix we will now encounter five Waters so we will go over this somewhat quickly so this is the basic traversal of Matrix we have found water so this condition comes out to be false J becomes two this condition comes out to be false J becomes three this condition comes out to be false so now we are done processing the row one so we go to row two we'll increment I I becomes two we'll start with J equal to 0 so we are at 2 comma 0 now this condition comes out to be false J becomes one this condition comes out to be false because we are landing on water so we need to skip it J becomes two so friend now here you can see that we are on a particular land because this condition comes out to be true and if we go to the visited area I comma J which is 2A 2 here we have a false value it means we haven't visited this land so both the condition comes out to be true so it means as we have found a new land we'll apply DFS on top of it to actually f figure out it adjacent length horizontally and vertically so this DFS will be called with 2 comma 2 so on the call stack there will be DFS with row as two and column s two like this so now we'll apply the same algorithm which we applied to this node we are in the boundaries of the Matrix visited is false and the value at this row and column is one so all the condition comes out to be false so first we mark this land as visited by assigning a value true to the visited 2D array at 2A 2 now we simply go to Left of 2A 2 so when we go left row remains same and column decreases so we are leaving this DFS so first we update line number here which is8 now on the call stack there will be one more method by name DF FS where row Remains the Same and column decreases so we are at 2 comma 1 now it means we are going towards the left of 2A 2 which is 2A 1 here we know that we have landed on water so we simply return so this DFS will end execution point will reach here so this DFS we had left at line number 8 so we start from line number8 we have encountered the water so we simply return so we come back to 2 comma 2 because at this moment row and column were at 2A 2 so we come back to 2 comma 2 now we go up so first we update the line number here which is N9 there will be one more method on the call stack if you are going up row decreases column remains same so row became one from two it means we have went here 1 comma 2 here you can see that we have landed on water again so we simply return so we come back to 2 comma 2 now this method will be removed from the call stack we'll start from line number nine we come back to 2 comma 2 and now we are going towards right so first we update line number 10 here there will be one more method of on the call stack if we are going towards right row remains same and column increases so from two it became three and we are going to 2 comma 3 now here here you can see that we have again found a water so we simply return to 2 comma 2 we start from line number 10 we return back to 2A 2 and now we simply go down so first we update line number 11 here because we are leaving this DFS at line number 11 there will be one more method on the call stack we are going down so row will increase so from two it became three and column Remains the Same we are at 3A 2 and here you can see we have found a water so we'll simply return back to 2 comma 2 this method will be removed from the call strike we return to this DFS at line number 11 so we return back to 2 comma 2 and here you can see that we have visited all the adjacent notes of this land so this DFS will end now because there are no more lines to execute so now we'll go back to the method which actually called this DFS at 2 comma 2 so this is the condition so here you can see after we finish visiting all the lands adjacent to this land horizontally and vertically we know that we have found one more Island so we'll increase the value of number of islands which becomes two now we'll increment J J becomes three so here you can see this is a water water water water so for the next four iteration we'll simply skip this values so we'll go over this quickly this condition comes out to be false now we are done with processing the row two so this for Loop will terminate we'll increment I I becomes three because now we are processing the last row we'll start from J equal to0 this condition comes out to be false J becomes 1 this condition comes out to be false J becomes two this condition comes out to be false and at the end j becomes three that we have found a land which is actually not visited because value is false it means that now we can apply DFS on top of this land so will call DFS we pass the value of I and J which is 3A 3 there will be one method DFS with row is three and column is three like this we are within the boundaries of the Matrix and we haven't visited this land so all the condition will come out to be false so we will first mark this land as visited by assigning a value true in the visited array at row three and column 3 and now we'll perform the same steps we go left up right and bottom so we'll go over this quickly because we know that we are performing the same steps what we did here and here so we need to keep this thing in mind when we are going to the different directions so first we are going left so we update line number here there will be method on the call stack we are going left so column decreases so from 3A 3 it became 3A 2 we have reached here now this is a water so we'll simply return back to 3A 3 we start from line number 8 we come back to 3A 3 and now we actually go up we update line number here and there will be one more method on the call stack as we are going up so row will decrease so it became 2A 3 now we reached here this is a water so we return back 2 3A 3 we start the execution on line number nine we come back to 3 comma 3 because value of row and column is 3A 3 in this DFS now we go towards right we update line number 10 here because we are leaving this DFS and there will be one more method on the call stack we are going towards right so column will increase so here we can see that we have gone outside the boundaries of this Matrix so value of column is actually equal to grid of 0. length which is equal to 4 it means we are outside the boundaries of this Matrix so we'll simply return we return back to 3A 3 we start the execution at line number 10 like this and now we simply go down so we update the line number here 11 as we are going down row will increase and we have went outside the boundaries of this Matrix so here now value of row is equal to grid do length which is four so we'll simply return we start the execution from line number 11 and we return back to 3A 3 and after that there are no lines to execute so this DFS will also will be removed from the call stack and we go back to a method which called this DFS at row and column 3 comma 3 so this is the condition so we know that we have visited one more Island so we'll increase the value of number of islands so it becomes three we'll increment J so J will go beyond the boundaries of this Matrix so this for Loop will terminate and as we have visited the last row we'll increment I so I will also go beyond the boundaries of this Matrix it means we have visited a complete Matrix and at the end after visiting all these islands we'll simply return the value three because there are three islands this this and this here you can see we have visited this this and this so friend this was all about that how we can solve the number of islands problem I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon icon so that you never miss any update thanks have a nice day hello everyone so in this video we will discuss about hashing data structure and we will see a basic introduction to hashing so friends before we start in case if you are new to my channel then please subscribe to my channel so that you never miss any update so what do we mean by hashing so before discussing that we will see that why we actually need a concept called hashing so usually when we need to perform any search operation we have few options such as linear search where what we do is let's suppose we are given with this array of 10 elements and let's suppose we want to search for a particular element for example let's say 10 so in linear search what we do is the value which we want to search which is 10 We compare it with each and every element of this array and when we reach here we find that 10 is there in this array and we simply say the value 10 is found in this array Also let's suppose if we want to search for a value let's say 20 so what we need to do here is we need to compare 20 with each and every element of this array and after comparing with the last element if you don't find 20 in this array then we simply return return that 20 is not found so here the problem is in case if the key which we want to search is not present in this list or array then the time complexity basically goes to O of n because we need to compare the key with each and every element and then only we can come to know that whether the key is present in this array or not so this is one problem with the linear search the other form of search we have is binary search now in binary search what we have is let's say we are given with this array of 10 elements in binary search the array we have is already sorted so here you can see here the elements are sorted in ascending order so when the elements are sorted in ascending order we basically use this property to make this search quicker so for example let's say if we want to search for a element 8 so here we don't compare the key which we want to search with each and every element of this array as we know that the array is already sorted we take the lower index which is zero we take the higher index which is N9 and using these two indexes we try to find the mid index so here we simply do 9 + 0 ided 2 which give us 4.5 and if we take the integer value the mid value will come to 4 so what we do is whatever the value is at index 4 which is 10 we simply check that whether 8 is less than 10 or greater than 10 we know that 8 is less than 10 so it must be lying somewhere to the left of mid index because here we know that the elements of array are already sorted so what we do here is we simply discard the right sub array completely because we know that searching elements after 10 will never give us 8 8 will only come before 10 so we simply discard the right sub array so after discarding the right sub array our array becomes from 0 to 4 where we take 0 as the lower index and four is the higher index we do 4 + 0 divided by 2 we get two as mid index so whatever the value is at Mid index which is five when we compare five with eight we know that 8 is greater than 5 and as the array elements are sorted we simply discard the left sub array because we know that it must be lying to the right of five so now after we discard the left part our array Becomes of three elements from 2 to 4 and then we again find the mid index we do four + 2 which is 6 and if we divide it by 2 we get three so whatever the value is at third index which is mid we see it is8 we come to know that we have found our key and here you can see that compared to linear search binary search works pretty much faster when the are elements are sorted so friends with binary search with each iteration we simply discard half of the array because we know that the element which we want to search can be found at three places one is at the mid index or it can be on the left sub array or on the right sub array so if it is on the left sub array we simply discard the right sub array and if it is on the right sub array we simply discard the left sub array so here you can see on each iteration we are discarding half of the array so the time complexity of binary search comes out to be o of login which is pretty much faster than o of n but here the problem Still Remains which is is there any data structure or is there any search technique which give us a Time complexity of O of one because searching an element in linear search takes o of n which is not feasible for the search operation and for the binary sech takes o of login but here we have this constraint that element should be sorted which is usually never the case we have always elements in unsorted form and if you want to s sort them we need to apply sorting algorithms whose complexity can reach to n log n so after we sort the elements then our search becomes faster and we get o of login so how can we achieve a Time complexity of O of 1 so if you see one solution is if we take error data structure now why array because array can be used to provide o of one searches using indexes so let's suppose if we are given with these elements 61 3 5 9 7 and let's say if we want to search in these elements and we want that the search should be of O of one time so what we can do is among this elements we will see which is the highest element which is nine so what we can simply do is we can create an array whose last index is 9 which means we create an array of 10 elements where the last index is nine and what we do here is we take six and we store six at six index one at first index three at index 3 five at index 5 9 at index 9 7 at index 7 so we simply store all these elements into their respective indexes in an array and let's suppose if we are given let's search for a value three so what we can do is we simply go to third index of array by accessing the array with index 3 and we see whether three is there or not so this operation takes time complexity of O of one because we can access array elements directly so here at third index we see that there is a value three so our answer is found and let's say if you want to search for for zero so what we do is we go to zeroth index and we see there is no value so our answer is not found so friends here you can see that ARS can give us a Time complexity of O of one when performing the searches using their indexes so the time complexity of this scenario will be o of one which is pretty much fast so let's suppose we take one more example let's say we are in a classroom and we have this 30 students so what we can simply do is we can assign a role number to each and every student and we can create a data structure which is array of size 30 where last index is 29 and we can assign the indexes to each and every student and let's suppose we are storing a student object on each and every index so here when the students are sitting in a classroom the teacher can directly go to a particular seat let's say five and let's say the teacher has a device where she can directly type five and gets the information for the student that the student name is John these are his marks in particular subject and all of the information for the student John and similarly If She searches for 29 she can get the information for Tina so here also we can use error data structure and we can get the time complexity of O of one so to this type of storage we simply call Direct addressing moving ahead now whatever the example we saw there array was a perfect data structure for searching in over one times now where the problem will still arises let's say if we want to store AAR card number which is of 12 digits or you can you can also take an example of storing the social security number in an array so here if you see that AAR card number is of 12 digits and it gives an identity of a particular citizen of India based on his AAR number so the problem is if we take an array to store the AAR card number then if we want to store this big number into an array which is nothing but direct addressing with its index then there would be a huge array to store all the AAR card numbers so this is one problem that we need to create such a huge array where the AAR card number matches the index of that array and the second problem is let's say if the AAR card number is designed with 12 digits and we have created a huge array to store the AAR card number and let's suppose we have only distributed 10 to 12 AAR card to the people and if we try to store those AAR card numbers into the array then after storing we will see that most of the memory of the array elements will remain unutilized and wasted so this is the problem with array where we can't use direct addressing because we need to store such a huge number so to basically address these problems hashing was introduced now what is hashing so here you can see that hashing is a technique which is used for storing retrieving and removing the information as quick as possible and how do we perform the hashing is here it is a process of converting a arbitrary size key into a fixed size value so here what we are simply saying is let's suppose we have our keys which are huge let's say the AAR card number or social security number so what we can do is we can't directly store the key into the respective indexes of the array because that problem we discussed in our previous slide so what we do is we take that particular huge key and we try to convert that key into a fixed size value and how we perform this conversion is this conversion is done by a special function which we call Hash function so we will discuss hash function in our upcoming videos but for time being we can think that let's say if we have array of thousand elements and we want to store a 12-digit AAR card number so what we do is we take the AAR card number which is of an arbitrary size or a huge size we pass that number to our hash function and this hash function will give us a fixed size value let's say if you're taking the size of the array where we want to store the AAR card number is of, then it will give us a fixed size value between 0 to th000 and we can simply use that fixed value and store that particular AAR card number so this conversion of a large key into a fixed small size is done via hash function so we will discuss this hash function in detail in our upcoming videos so for timing you can simply think that hashing is a technique which is used for storing retrieving and removing the information as quick as possible and the operation which hashing supports such as storing retrieving and removing an information have average runtime complexity of O of1 So friends in this video we saw that why we actually require the hashing technique or why we require a hashing data structure because we need average runtime complexity of O of one when we want to store retrieve or remove any particular piece of information so in our next video we will see that what are hash functions and how it helps in converting a huge size key into a fixed size value so friends in case if you find this information useful then please like this video and if you new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so friends in our previous video we discussed about what is hashing so in this video we will see that what are hash functions so friends before discussing about hash function in case if you're new to my channel then please subscribe to my channel so that you never miss any update so in our previous video we saw a basic definition of what is Hash function so a hash hash function simply takes an arbitrary size key and provides fixed size value also called as index so here using an hash function we can take a key of any size and once we pass that key to Hash function it returns us back a fixed size value which we also called as index now this fixed size value is basically small and can be taken up as index and using that index we can store the key which we want and also by using this hash function we can even retrieve that key so we'll see the importance of hash function more in our upcoming videos so for this video you can simply think of hash function is let's suppose we are given key of any size what we do is we simply pass this key to our hash function and whatever key we passed hash function return us a index which is of fixed size Now using this index value what we actually do is we simply store this key into a smaller size data structure and we can perform storing retrieving and removing of this key very fast we will see those implementation details later in upcoming videos so for timing you can simply think that two over hash function we pass in a key and it returns back as a smaller fixed size value index we will see its usage in Greater detail in our upcoming videos so friends the hash function can be of any type you can basically write your own hash function where what you do is you simply take a key and it should return you back a smaller fixed size value so that you can use that fixed size value and store that huge key into a data structure so that the retrieval storing and removing of that particular key becomes faster and how does hash function help us in achieving a Time complexity of O of one we will see later in upcoming videos so one such typical hash function which is mostly used in hashing data structure is modular hash function so what does hash function does is the modular HH function simply takes a key and a size now what it returns is remainder by dividing Key by size so usually the remainder which hash function return us back is used as an index to store the key in an array of the provided size so here you can assume that key has a large value which cannot be taken up as an index of an array which we discussed in our previous video that it creates the problem so what hash function will help us in doing is let's say we take a smaller size array so when we pass the key and the size hash function will return the remainder by dividing Key by that size and whatever the remainder is return returned that remainder is taken up as an index to store the key in an array of provided size so here you can see instead of using an array for direct addressing which we discussed in our previous video here what we do is we simply take an array of smaller size and let's suppose the key has a very large value now how we can store that key into the array of small sizes we simply take the key we divide the key by the size and whatever the remainder we get that will be taken up as an index to store this particular key so let's see how modular hash function help us in storing large Keys into a smaller size array so here we usually take the hash function as h of key which is the hash function which takes in a key and usually returns us back in index and this hash function can be any implementation you provide but here we are simply discussing the modular hash function so here we take the key we do modulus by size which is key mod size now this modulus operator always returns us back the remainder when we divide the key by size so here let's these are our keys which we want to store now here you can see the keys are 5 1 10 26 and 99 so we can't take an array of length 100 to store only five elements for the direct addressing so what we do is we simply take a smaller size array let's say of 10 elements now size of this array is 10 now how we store these Keys into this arrays we take the key we pass into the the hash function so here 5 modulus 10 which is five is the key modulus size which is 10 so if we divide 5 by 10 we get remainder as five because five is not divisible by 10 so the remainder we get is five so here we simply take this key go to the fifth index here this is the index which it returns so we go to the fifth index and we store five now we take one so 1 when we divide 1 by 10 we get remainder as one so we take this key go to index one and store one now we take key as 10 so when we divide 10 by 10 we get remainder zero because 10 is divisible by 10 so here you can see that here 10 cannot fit into this array if we take it as a direct index index so this hash function is helping us to get a smaller index so when we do 10 mod 10 we get zero so here what we do is we simply go to the zero index and we store 10 here similarly if we take a value 26 if we do 26 mod 10 it means if when we divide 26 by 10 we get the remainder as six because the 20 gets divisible by 10 and we get the remainder value is six so here we go to sixth index and we store 26 there and similarly when we take 99 when we do 99 mod 10 or when we divide 99 by 10 we get remainder as 9 so here we go to N9 index and we store the value 99 so friends here you can see that here instead of doing the direct addressing of the key with array index we are using a simple hash function and whatever is the value of key we don't care we simply divide it by the size and whatever the remainder comes out we simply take that as an index and we store those values at that particular index so friends here we used the modular hash function to store this key elements into an array of fixed size so similarly we can search a particular key based on our hash function so if we take this example let's say if we want to search that whether 26 is present or not so when we were storing this value in this array we used modular hash function so similarly when we want to search what we do is we take the value which we want to search we pass to our hash function it returns us back an index we simply go to that index and we simply see that whether that key is present or not so here in this case 26 goes to the hash function and the hash function return as the remainder as six so we go to the sixth index we see there is a value We compare this value with the key which we want to search and we see that 26 is present so now here you can see the hash function is helping us store the keys which are very large in size and here you can see that for storing 99 we didn't take an array of 100 size elements we simply took an array of 10 elements and we stored these values in the array so friends here hash function can be implemented in many different ways so one of the most popular hash function which we saw here was modular hash function now friends one more problem arises here is as we are mapping large Keys into a smaller fixed size array there could be a possibility that let's say if we want to store one more value as 109 so when we do 109 mod 10 we get remainder is 9 and when we go to 9th index for storing 109 we already see that there is a value 99 so now there is a problem that what do we do with initially stored 99 value because in Array we can store only one value at a time so we will see these problems in Greater detail in our up coming videos the idea which you are seeing here is using a smaller array and storing the larger size keys this data structure if we Implement in such a way using a hash function such data structure are basically called as hash table so in our upcoming video we will see what is Hash table so friends I hope you find this information useful and in case if you find this information useful then please like this video and if you're new to my channel then please subscribe to my channel so that you never miss any update hello everyone so in this section we will discuss about a basic introduction to Hash table in our previous video we discussed about what is hashing and what are hash functions so in this video we will look into a data structure which is Hash table and we will see the concepts which we discussed in our previous videos like hashing and hash function and we'll see how they are used to implement a hash table so before we start in case if you're new to my channel then please subscribe to my channel so that you never miss any update in one of our previous video we discussed that AR can be used to store retrieve and remove an information with the time complexity of O of one based on indexes but we also saw that AR had and limit limitation while implementing the direct addressing strategy via indexes so we introduced the concept of hashing now based on those concept when we Implement a hash table we basically take a generalized form of an array so internally the data structure for implementing hash table is pretty much an array but it is used with the concepts of hashing and hash function now what do we do with the hash table is the data is stored in the form of key value pair so in our previous video we discussed that how a key is passed to a hash function and an index is return So based on the index we store this key value pair so basically in a hash table we simply put the data in form of key value pairer where we take the key we pass it to the hash function and hash function returns us an index so this index is nothing but an index of an array where we simply store our key value pair so this key can be a huge key but our hash function takes that key and returns us back a fixed and a small value which is nothing but an index of our array now what we do is we take that index and we store the key value pair in the array and the primary operations which are supported by hash table are first is the put which takes in a key and a value now what does this operation does is it adds the key value pair against a unique key so here our key is unique and if we try to add a different value with the same key then that value gets updated and the older value will be removed so here the key is unique because this key usually goes into this hash function and based on the hash function calculation our index is returned and on that Index this key value pair is stored similarly after storing when we do get then the value is returned for that provided key so here this key goes into the hash function our index is returned and based on this index whatever the value is stored in the array that value is returned for that provided key and the third operation is remove where we pass the key so what it does is it removes the key value pair from the hash table so these are the three primary operations supported by hash table and here if you see all these three operations use a hash function and we will discuss all these three operation in Greater detail in our upcoming lectures these all three operations internally use the hash function which takes in a key returns as an index and based on the index put get and remove operations are performed so all these three operations are pretty much fast the average running time of all this operation is O of one and if you see in our Java collection framework we have a hashmap class which is pretty much same as the hash table class so if we want to deal with key value pair then we simply use hashmap class and if you want to deal with only Keys then we use hash set so here if you want to store store any data in form of key value pair then we simply take the help of hashmap class in Java which is nothing but an hash table but if you only want to deal with the keys and not with the value then we simply use the hashset class and the idea behind both the classes to store the keys Remains the Same which we discussed here so friend let's see a simple hash table where we have provided with the hash function as key mod size and size is nothing but the length of this array so this array is the internal data structure to implement a hash table so we simply call it a hash table only now let's say if we want to store these key value pairs in this simple hash table so what we do is let's say key is five and the value is John so when we try to store this key value pair in a simple hash table what we do is we take the key we pass it to Hash function and this hash function returns as an index so we simply go to that index and store this key value pair so for example 5 Mod 10 so when we divide 5 by 10 we get remainder as five so this is our index which is being returned by the hash function so here we simply go to the fifth index and we simply store key value pair so this array can be taken up as array of key value pairs which can be our own type object which takes key and a value now if you want to store one comma Tom so 1 divided by 10 gives remainder as one so here we go to the first index and we store one comma Tom if we want to store 10 comma James we do 10 more 10 so we get remainder is zero so we go to the zeroth index and store 10 comma James there for this key value pair we get six as the remainder so we go to the six index and we store 26 comma Tina for this key value pair so if we divide 99 by 10 we get remainder as 9 so we go to the 9th index and we store 99 comma Sana there now if you take the last value 105 mod 10 will give a remainder as five so friend this is a simple hash table so now here you can see if we try to go to fifth index here you can see that we already have this value 5 comma John now the problem is what should we do with this key value pair so whenever this kind of situation comes where we are simply storing key value pair in a particular index and we already encounter a key value pair there this concept in hash table is called as Collision because now there is a collision between these two values that what should we do so friends here you can see that this kind of situation usually arrives when we Implement a hash table because here you can see the size of this hash table is only 10 and the keys which we are trying to store St is more than 10 so usually after storing few values a hash table simply Encounters this Collision frequently so this is a simple hash table so in our future video we will see that how this hash table can be implemented to resolve these collisions and also friends there are strategies to resolve this collisions which we'll discuss in our upcoming videos so friends I hope you find this information useful and in case if you find this information useful then please like this video and if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in our previous video we discussed about a simple hash table we saw what hash table does and we also saw that when we use hash function to store the key value pair in a hash table there will come a situation when there will be a collision so in this video we will see that how we can resolve that Collision using a collision resolution technique which we call as separate chaining so in our previous video we saw a simple Ash table where we had this array of key value pair and of size as 10 our hash function was key mod size where we divided Key by size and whatever was the remainder we used that remainder as an index to store these keys with its values in this array so 5 Mod 10 gave value as five so at the fifth index we stored five comma John at the first index we stored 1 comma Tom at the zeroth index we stored 10 comma James because when we do 10 mod 10 or when we divide 10 by 10 we get remainder as zero on the sixth index we stored 26 comma TAA on the ninth index we stored 99 comma saana and when we encountered a value as 105 so our hash function return returned as a value as five because when we divide 105 by 10 we get five as the remainder so when we we went to fifth index we saw that there is already a value stored 5 comma John at fifth index so this resulted in a collision which we discussed in our previous video now in this video we will see that how we can resolve this Collision using a strategy called as separate chaining so friends what we do in separate chaining is in case if we encounter a collision let's say when we try to store 105 on the fifth index we already found that value as 5 comma John so what we do is when this Collision occurs then at the fifth index we simply store both the values in a list so that list is nothing but a simple linked list where whenever we encounter a collision we simply add that element in that list which belongs to that particular index so when we try to store many values which are huge in a small fixed size array then there will be a situation where we encounter frequent collisions so we simply add those elements into the list which belongs to that particular index so when this list grows it looks like a chain so therefore the resolution strategy is separate chaining where with each index we create a separate chain or linked list to store the values which are getting collided so let's see an example so friends in our previous videos when we discussed about the link list we saw that how we can create a singly link list W link list and circular singly link list so if we take the example of singly Link list we saw that there is a head from where basically the singly link list starts and each node basically points to the next node in the list and the node which is at end points to null so here instead of taking the array of key value pair what we do is we take the array of hash nodes so here if you see let's say if you want to store F comma John we first pass the key into the hash function we get the index which is five so instead of directly storing at this this index we create a hash node so this hash node is pretty much similar to the singly link list list node where we had a data and a reference to the next node so here we simply add one more value which is the key so here our hash node has three attributes one is the key other is the value and the third is the reference to the next hash node in this list or chain when some Collision occurs so this terminology you can simply take it as hash node so in our upcoming videos we will discuss in Greater detail what is Hash node now let's say if we want to store one comma Tom so at the first index we store one comma Tom in the form of a hash node at the zero index we'll store 10 comma gyms and and similarly the other values but when we encounter 105 comma Mary so our hash function has return returned our index as five so here when we go to index 5 we see that there is already a hash node available having key as5 value as John now here we have encountered a collision so what we do is as this hash node can be treated and converted into a list or chain what we do is we can use its next reference and we can simply store 105 s key value as marry and its next is pointing to null so here whenever we encounter Collision we keep on adding those elements in this chain which we also say that it's a form of a link list so by separate chaining technique we can resolve these collisions and we can store the values in the form of a link list when any Collision occurs so we'll see the importance of this hash node and this link list in our upcoming videos when we will Implement a hash table using the separate chaining technique so friends I hope you have find this information useful and in case if this information is useful to you then please like this video and if you new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in this video we will discuss that how we can represent a hash node in a hash table so now previous video we discussed about one of the Collision resolution technique which was termed as separate chaining and when we discussed about the separate chaining we saw that how we can remove the collisions VI hash node and create chains where one hash node is pointing to other hash nodes so let's see the structure and representation of a hash node in a hash table but before we start in case if you're new to my channel then please subscribe to my channel so that you never miss any update so here a hash note class in hash table consist of three data members now the first one is the key so the key is basically a unique value which help us in storing the data and here this case simply represent a generic type in Java the second data member is value which is the actual data which is being stored in a hash table in a location which is being computed by the key and the hash function so here V simply signifies the generic type it can be any type so K and V V can be any type and the third data member is Hash node next so it simply refers to the next hash node in a chain of hash nodes so chain of hash node is nothing but a list of hash nodes which help us in resolving the collisions where one hash node simply refer to the other hash node and they form a chain so here these are the three data members and if we see the symbolic representation of it then hash note consists of three things the key which is unique and which help us in storing the value via hash function and the hash node simply points to the next hash node in a list when there is a collision so here hash node is very much similar to the list node which we discussed in our singly link list videos the only difference is in the list node there was value and a reference to the next node but here in hash node we also store the key so we will see why this key value pairs are stored and how the primary operation in a hash table are implemented and if you see a representation of it it looks something like this that it has a key value and a reference to the next hash node in the list of hash nodes so friend this is how we actually represent a hash node in a hash table so so usually when we Implement a hash table then the hash node is nothing but a private class inside a hash table which help us in implementing the operations which are being performed by hash table so those operations we will discuss in detail in our upcoming videos I hope you must have liked this video and in case if you're new to my channel then please subscribe to my channel thanks have a nice day hello hello everyone so in our previous video we actually discussed about that how we can represent a hash node in a hash table so in this video we will see that how we can Implement a hash table via separate chaining Collision resolution technique so here in order to implement a hash table I will be creating few videos which will be in series so you can consider it as a part one of how to implement a hash table but before we start in case if you're new to my channel then please subscribe to my channel so that you never miss any update so friends in order to implement a hash table we will first look into some of the terminology which we will be using frequently in upcoming videos to understand different parts of hashtable so here as you already discussed that hashtable table is nothing but a generalized form of an array now let's say if we take the example of this array whose length is 10 and having index value from 0 to 9 so when implementing a hash table via separate chaining Collision resolution Technique we discussed that we actually use the hash node so here in order to store key value pair we simply take this as an array of hash nodes so to this array we simply call it as buckets and we denote it something like this that each container at a particular index is termed as bucket and this array basically stores hash notes which has key value pair and a reference to the next hash node and here we will also create a variable which would be number of buckets so this number of buckets is nothing but the length of buckets array which is also called as capacity of hash table so for example if we want to store a key value pair let's say our keys of integer type having value as 10 and a value of string type which takes in a value as James and if we want to store at zero index what we do is the zero index bucket simply points to a hash node storing key value and has a reference to next node So currently if there is only one element then the next node will point to null similarly let's say at index one if we want to store a key value so it would look something like this so here you can see that way we are storing this key value pair is via hash function which we already discussed in our previous video and which we will be discussing in our upcoming videos also that here you can see the key is 10 and here let's say if we take the hash function as key mod the number of buckets which is also the length of this array then we get 10 modulus 10 which will give us a remainder zero and whatever we get from the hash function it is nothing but our index so at the zeroth index you can see that we have stored a key value pair like this and similarly at fifth index we are storing a key five with a value as John so here five when divided by 10 gives remainder as five only so at fifth index we are storing a key as five and we usually term it as hash note which we have already discussed now let's say if we want to store a key of 105 so when we divide 105 by 10 we get remainder as 5 which would be the value returned by our hash function so if we go at index 5 we will see that there is already a value so there is a collision so in order to resolve this Collision we are taking help of hash notes because here you can see that the third data member is nothing but a reference to the next hash node so here we can use the next reference to store this key value pair which also corresponds to fifth index so here when we store this key value pair in form of a link list the first element is simply treated as head and this link list is also termed as chains because we are discussing separate chaining Collision resolution technique and which is being implemented via chains so here when a collision is encountered the key value pairs are stored in a form of chain and this chain can be the way you want to implement you can simply add the newly inserted node at the end or at the beginning or you can insert in a sorted form like based on the key that five comes before 105 comes later and then 205 305 something like that so you can insert multiple key value pair which is also called as hash node in a way which you want and similarly we can store other values like this also friends here you can see that length of this array is 10 which is also a value stored by number of buckets and which is also called as capacity of our hash table but here you can see that this hash table currently has 1 2 3 4 5 and six hash notes so the size of the hash table is six because it has hold six key value Pairs and the capacity is of 10 so this is the difference between the capacity and size so when we talk about size you can think of it the number number of key value pairs inside a hash table and when we talk about capacity number of buckets or length of buckets we are simply talking about the array length so friend these are the few terminologies which are being associated with hash table so here when we Implement a hash table you can see that we have three members here one is the buckets array which is of type hash node the second second value is number of buckets which is also the capacity of our hash table and the third variable is size which is the number of key value pairs being stored in a hash table so here you can see that hash table has a Constructor which takes in a capacity so when we create an object of hash table we need to provide that what's the capacity of our hash table it means we are providing that how many buckets the hash table will have and here you can see that internally our hash table is using hash node class so which we already discussed that it has a key and a value and a reference to the next hash node so here you can see that we are taking key as integer and value as string so this can be any generic type so for the understanding and demonstration I will be using the key as integer and the value of string so basically most of the things remain same when we take any generic type type of key and value so here after taking key as integer and value as string and the third member is a reference to the next HH node which help us in storing the key value pair in a chain when the Collision occurs so here what we do is at the start we simply call and create an instance of hash table and let's say we pass capacity of 10 to our hash table so it looks something like this is that capacity value is 10 and in the hash table Constructor what we do is we assign the capacity to number of buckets so it becomes 10 and then we create an array of hash node and we provide the capacity so it looks something like this that internal data St structure is array of type hash node it is being termed as buckets and each compartment here you can see is a bucket which holds the hash notes in a form of a chain so here when we create this array at the start every index or bucket points to null because there are no hash notes currently into this array of hash notes so at the start size remains zero because we currently don't have any key value pairs inside this hash table so size is zero so friends in this video we saw a initial implementation of a hash table via separate chaining Collision resolution technique in our upcoming videos we will see that this hash table has many operations where we put a key value pair we remove a key value pair and we can get a value based on a key and there are many other operations which we will be looking into our upcoming videos so this this is just a basic and initial implementation of a hash table so now let's go to our intelligent ID and we'll simply code this part into the ID I hope you have find this information useful and in case if you find this information useful then please like this video and if you're new to my channel then please subscribe to my channel so that you never miss any update thanks have a nice day hello everyone so in our previous video we discussed about a initial implementation of hash table we saw the structure of hash table and we also saw that how it uses hash nodes internally now in this video we'll simply code for the internal structure of hash table and in upcoming videos we will see the different operations performed by hash table and then we'll test its working in the main method so here I have created one class as hash table now as we discussed hash table will consist of few instance variables one is array of hash node which we term as buckets and as it is using the hash note class internally here we will create a inner class hash node and as we already discussed that this hash note class will have three members one would be our key so this can be generic type the second member would be value and this can also be any generic type so here for the demo purpose I'm using the key as integer and value as string and the third member would be the reference to the next hash node and it will have a Constructor which will take two things key and a value we will assign the key to this do key and value to this do value so here the hash table consist of an array of hash node which we called as buckets it also has a integer variable number of buckets which is also capacity and it also has a integer type size which is nothing but number of key value pairs in hash table or number of hash notes in a hash table so basically in a hash table the number of hash notes represents the size of the hash table and here we will provide a Constructor to our hash table class so when we will create a instance of hash table it will simply call The parameterized Constructor providing a default capacity so here we will create one more Constructor which will take a capacity so here we can provide a customized capacity by calling this Constructor and if we call this Constructor it will create a hash table with a default capacity of 10 so here what we'll do is to number of buckets we will assign the capacity and now number of buckets is holding the capacity so what we'll do we will create the array of hash node whose length would be the value stored in the number of buckets so here when we'll create the instance of hash table let's say with a capacity we provide so the number of buckets will hold that capacity and the array of hash node will be of size which represents the number of buckets and you usually at the start when there are no hash notes in a hash table the size will be zero so this is what happens when we first initialize or create the instance of hash table now here you can see that this is the initial implementation of hash table so in a hash table there are many operations so one of the operation is that we want to know the size of the hash table that how many key value pairs are there so we provide a method as size and here we simply return the size one more method we provide is Boolean we check whether the hash table is empty or not so we provide the method as is empty and here if size is equal to zero then we return true stating that H table is empty and if size is not equal to zero we are returning false so friends in our upcoming video we will look into the primary operations of a hash table which is put which basically put a key value pair in a hash table so the parameters are key and value so this method basically takes in a key value pair and it simply puts that key value pair in our hash table so we will discuss about this method in Greater detail in our upcoming videos so this is one of the primary operations the other operation is get so this method simply takes in a key and Returns the corresponding value associated with it so for time being I'm simply returning null to compile this method so here whatever the key value pairs are stored in hash table so if you want to get any value associated with a key we simply Pass Key here and we get its corresponding value and one more method is remove where we pass the key and that key value pair will be removed and the value associated with that key will be returned so when we call get the key value pairer remains in the hash table we only get the value out of the hash table but when we do remove that key value pair is completely removed from the hash table and its corresponding value is returned so here these are the three main operations which are being performed by hash table and all these three methods have a Time complexity of O of 1 which is the average time complexity of a hash table so friend this was basic and initial implementation of a hash table in our upcoming videos we will see all these primary operations in great detail so friends in case if you find this information useful then please like this video and if you new to my channel then please subscribe to my channel so that you never miss any update thanks 7 ISJ hello everyone so in our previous video we saw a basic implementation of a hash table we saw that hash table internally has an array of hash notes and we also saw the representation of an hash node which contains key value and a reference to the next hash node so after creating a basic structure of hash table in this video we will see the that how we can put a key value pairer in a hash table and the strategy which we will be using for Collision resolution would be separate chaining so friends before we start in case if you're new to my channel then please subscribe to my channel so that you never miss any update so here you can see that in our previous video we saw a basic structure of hash table where we can create a hash table by providing in a capacity which also signifies the number of buckets in a hash table so when we will call this line here you can see the hash table internally uses an array of hash node which we call as buckets and at the start each hash node at a particular index points to null so friends when we try to put a key value pair into the hash table there are various scenarios which comes into picture so the one scenario is when we take the key and we pass it to our hash function then that hash function return us a index so what we do is we simply go to that index and see that whether the hash node is pointing to null value or to any other node so in case if it is pointing to null then we simply insert key value pair in the form of a hash node and we simply assign that hash node to that particular index and in case if there are multiple hash noes already present then what we do is we first check that whether that Keys is already present in the sequence of hash notes or not and if the key is already present then we simply update the value we don't insert a new key value pair and one more use case is let's say if there are multiple notes but the key value pair is not present so what we do is we simply create the hash node from the key value pair which we want to insert and we simply insert that hash note at the beginning of the list which is being formed by the hash note at a particular index So currently you see all the hash note at a particular index is pointing to null it means that each list which will be getting formed at a particular index starting node is null because there are no key value pair currently in this hash table and at the start we have this number of buckets value is 10 because we are providing the capacity to be 10 and currently as there are no elements so the size is zero now let's say if you want to put a integer key and a string value so here key is 105 and value is John so at the start here you can see that key is very long and we need to accommodate this key somewhere in this small buckets array so that when we put this key value pair and when we want to find that key value pair it should be pretty much fast so what we do is we simply pass this key to our hash function so here we will take the example of modular hash function which will take the key and we'll simply divide the key by buckets. length or number of buckets and whatever is the remainder that would be our index which will be written by this method so we are using this method as our hash function which is nothing but the modular hash function so if we divide 105 by 10 we get the remainder is 5 so that five will be return return from this method and will be our bucket index now what we do is we simply access the hash node at this bucket index so we go to the fifth index and we access this hash node So currently you can see it is pointing to null so which simply means that there are no hash note at this index and as this is pointing to null it will signify that head is pointing to null because at this index we are storing a hash node so this hash node has next reference which can store other hash nodes and if there are many hash nodes then the first hash node is always our head so this is also what we already discussed when we discussed about the singly link list where we normally had a list not node with a value and a reference to the next node so here the only difference with hash node is it has key value pair and a reference to the next hash node so here you can see currently head is pointing to null which means at this index there is no hash node so what we can do is we can increment the size because we can directly put this key value pair here at this point so first we create the hash node with key as one 105 value is John and when we create a new hash node the next always points to null so friends now what we do is whenever we insert this key value pair or hash node into this buckets array we can use different strategies one would be that we can insert this note at the beginning of the list or we can insert this note at the end of the list or we can store this node based on some sorting logic such as the ascending order of the keys so there are various strategies by which we can insert this node so here we will be simply inserting this node at the beginning of the list so friends in our previous videos we have seen that how we can insert a node at the beginning of the list or a singly link list so here the concept remains exactly the same now here you can see as head is pointing to null so at the first step what we do is as we want to insert this node at the beginning of the list and there could be a possibility that there are already notes here as currently there is no notes but there could be a possibility that head is pointing to a chain of nodes so at the first step what we do is we simply assign node next value to head because we want to insert this node at the beginning of the list so if node next is pointing to head then only this node will be at the beginning of the list but currently head is pointing to null so node next is already pointing to null and then what we'll do is this hash node which is pointing to the Head will break this link and will try to point it to our hash node which we want to insert so it would look something like this this null value goes away and this node will be inserted now let's say we want to insert a key as 21 and a value as stor so the bucket index would be 1 because 21 mod 10 will give remainder is 1 so we simply access the hash node at index one we see it is pointing to null so it is the same case like what we saw here so we simply increment the size by one and then we put the key value pair in the form of hash node so now here you can see that our hash table has two key value pairs therefore the size is two now let's say we want to insert a key value pair is 31 comma s so here now this case is when there will be a collision so how this separate chaining strategy comes into picture we will see now if we do 31 mod 10 we get remainder is one so our bucket index is one so we simply go and access the hash noted index one so we see that there is already a hash node at this index so now here is a collision so the way we insert this key value pair now is we create the separate chains in a form of list so that's why we have created this hash node which has a next reference so that chain of nodes can be added with ease so at the first step what we do is to whichever hash note this index is pointing that would be your head so this is the first step now what we do is as we don't know that how many notes are there and there could be a possibility that this key might exist already in this hash table so what we do is we start from the head we compare its key with the key which we want to insert and if that key already present then we simply update its value we don't add a key value pair in this hash table we simply update the value so that case we will see later but now here you can see head. key is 21 and the key which we want to insert is 31 so therefore they are not equal so what we do is we move head to its next node because so let's say if there are five notes then we need to compare all the five notes key with a key which we want to insert because we don't want to insert a key which is already there so we simply move head to its next node by assigning head do next to head so now here you can see head is pointing to null it means that this key is not present and we can safely insert this key value pairer at this index at the beginning of the list and as we are adding this key value pair we'll increment the size by one and then we'll bring head to its first position again now we'll create our hash node with this key value pair so key is 31 value is saana and it's next is pointing to null so here now we are inserting this node at the beginning of the list so what we saw already here so the first step what we do is as we want to insert this node at the beginning of the list we simply assign the value of head to node next so that node next currently pointing to null should point to head so it looks something like this that now node next is pointing to head and as node next is pointing to head now we can safely break this link and we can assign this reference to our newly created node so it would look something like this this link will go away and now there will be a reference to this hash note from this index so it would look something like this so here there is a reference from this index to this node which we want to insert and from this node there is a reference to the list of nodes which were already there so currently there is only one node but there could be a chain so when we rearrange this it would look something like this that node is inserted at the beginning of the list and this node simply shifted by one position so friends now here you can see let's say if you want to insert a key value pair where key is already present so here we have this three notes we are trying to insert key value pair where key is 21 and values marry so when we will divide 21 by 10 we get remainder as one so our bucket index become one so we simply access the hash node at this index and the first hash node is our head and if there is a hash node already present so now our first task is to verify that whether this key is already present in this hash table or not so the way we do it is we do head. key which is 31 here we compare it with our key so here you can see they are not equal so what we do is we Traverse head to its next node why this this reference so now we again compare head dot key so here you can see it's 21 and our key which we want to insert is also 21 so therefore they are equal so what we do is by this check we came to know that key is already present so we don't have to insert a new key and increase the size what we do is we simply update the value when we actually put a key value pair so here instead of Tom now the value will become marry so friend this was all about this video in our next video we will see the code for adding this key value pair in a hash table via animation I hope you must have like this video and in case if you are new to my channel then please subscribe to my channel thanks have a nice day hello everyone so in our previous video we we saw a demonstration via an animation that how we can put a key value pair in a hash table using the separate chaining Collision resolution technique so in this video we will see the code for that and we will see its demonstration step by step with an animation so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so when we create the instance of hash table this is what we discussed that at the start what happens that all the hash notes on each index points to null so which means that on each index we have a list of nodes and the starting node is basically our head which is being pointing to null and here you can see when we start as we are providing the capacity of 10 it means we are creating the array of hash node with a length is 10 which is nothing but our number of buckets and size is zero so let's say if you want to put a key and a value as 105 and John so we call the put method we take key as 105 and value as John so in our previous video we discussed the idea that how we can insert this key value pair there are many use cases which we will be seeing later so each use case at the start what we do is we take the key and we pass it to our hash function which gives us an index and we take that index and we try to insert the key value pair in the form of hash node into this buckets array so here you can see the get bucket index method is nothing but our hash function so here we are using the modular hash function where we are taking the key we are dividing it by number of buckets and whatever is the remainder we are returning it from this method which would be nothing but our bucket index so when we pass 105 is key and if we divide 105 by 10 then we get five as the remainder so the bucket index is five now what we do is we try to access the hash node at this bucket index so which is five so here you can see it points to a hash node having value as null so here you can see it is referring to a null value so it means at this index there are no hash nodes so we can directly insert this key value pair and as the starting node is pointing to null we are creating a hash node by name head which points to the first node at this index which would be null so head is pointing to null so friends here you can see that on each index there can be multiple hash notes which are connected via the next reference which hash node has and when we discuss singly link list we saw that the starting node is head so here we are simply referring head as the starting node of the singly link list which will be formed by the chain of hash noes so here why we need this head is because in this file loop at this particular index there could be a possibility that let's say there are many nodes so in this file Loop we are checking that whether the key is already present or not so here you can see as head is pointing to null it means that this key value pair is not present so we exit from the while loop and as key value pair is not present we can simply add this key value pair in the form of hash node so first we increment the size so now size become one and now here you can see that let's suppose at this index there could would have been multiple notes connected bya next reference so in this V Loop there is a possibility that head might travel to some of the notes to check whether the keys is present or not so after this V Loop we bring back head to the first node by again assigning the hash node at bucket index so head will again point to null and now as we want to insert the node so first we create the hash with key value pair which we want to insert so it would look something like this key is 105 value is John and this next is pointing to null and it is being referred by node now as we want to insert this node at the beginning of the list which is starting from head what we do is we simply assign the value of head to node next because we want to insert this node just before the head which would be the beginning of the list so node next should point to head so we are simply assigning value head to nodes next So currently node next is already pointing to null and now as we want to insert this hash node in this buckets array so at this index whatever the reference would be we simply assign it to the node so at the bucket index we are simply assigning the value of node so it would look something like this as node is pointing to to this node now this has node will point to the node which we want to insert so here we can see that we have inserted one hash node and from now onwards there would be multiple hash nodes on this index in case some Collision will occur so let's put one more key value pair where key is 21 and value is stor so size is already one key is 21 value is Storm we first calculate the bucket index from our hash function so when we'll call get bucket index we pass in the key so 21 when divided by 10 will give remainder as 1 so the bucket index will become 1 so now what we do is we simply try to access the hash node at this bucket index so when we call buckets and we pass bucket index as one we are accessing this value so here you can see that the hash node which it refers is null so it means that there are no notes in this list here so head will point to null now we will simply check whether 21 is present in list of notes at this index or not So currently head is pointing to null this condition in while loop will come out to be false and we know that this key value pair is not present so we'll simply increase the size by one because now we are simply adding key value pair into this buckets array so size becomes two and we already discussed that head might travel in this V Loop to some of the notes to Simply compare whether 21 is present or not so we simply bring back head to the starting of the list by again assigning the hash noted bucket index so head will again point to null we'll create the hash node with key as 21 value as Tom and next pointing to null and as we want to insert this node at the beginning of the list first we assign the value of head to nodes next so head is pointing to null so here node next will point to null and then we will simply add node into this bucket array by assigning the value of node at the bucket index so it would look something like this that now it will point to the node which we want to insert so friends here you can see that we have added two noes now now let's say we want want to add one more key value pair where key is 31 and value is saana so this is the case where we will actually see the collision and we will see the importance of this next reference so key is 31 and value is saana we calculate the bucket index 31 ided 10 will give remainder as one so bucket index will become one we will access the hash node at this bucket index which is at index one and to whichever node it is pointing our head will point to that node because that would be our starting of this list so head will point to this node so now we'll see that whether 31 is present in this list of nodes or not which is at this index So currently you see head is not equal to null so there could be a possibility that this key and value might exist already in the buckets array so in the while loop we check whether head do key which is 21 is equal to 31 or not which is the key which you want to insert so this condition comes out to be false because 21 is not equal to 31 it means this key value pair is not present for this node so what we do is we simply Traverse head to its next note because there could be possibility that this list can contain let's say n number of nodes so we have to compare the keys for this n number of notes by traversing head 1 one position with each iteration so we simply assign head. next value to head so head do next is pointing to null so now head will point to null we check whether head is equal to null or not so head is equal to null so this condition comes out to be false which signifies that this key value pair is not present in this buckets array so we can safely insert a key value pair so this condition comes out to be false and while loop will terminate so rest of the steps Remains the Same as we are now inserting this key value pair we will increment size by one so size will become three and here can see that head has already traversed into this list of nodes so we again bring back head to the starting point of the list by again assigning the hash node at bucket index which is our first hash node so it would look something like this head comes back to the first position and why we are bringing head to the first position is because we are trying to insert this key value pair in the form of hash node at the beginning of theist list so we usually need the head for that which is nothing but our first hash note of the list so here we are simply creating the node with key value pair so key is 31 value is saana and it next is pointing to null which is being referred by node and now as you want to insert this node at the beginning of the list which means let's say there are n number of notes already here and if we insert this note our node should come before head which is having key is 21 so the node having key is 31 should insert before before the node having key is 21 which is nothing but our head so what we do is we can't directly break this link and assign it to our node because if we break this link this chain will go away so first we need to hold this chain so how we can hold this chain is we assign the value of head to nodes next because we want to insert this node before the head so node next should point to head so after this assignment it would look something like this that node next is pointing to a node to which head is pointing and then we can simply break this link and assign it to our newly created node so it would look something like this this link will go away and there will be a link from this index to the hash node which you want to insert so if we rearrange this structure it would look something like this that the node which you want to insert is at the beginning of this list which is just before the our old head so friends now let's see one last use case where the key is already present so here you can see if you put key is21 and let a value is marry so here if the key is already present we don't put the key value pair in the buckets array we simply update the value and that we do with the help of this V Loop so let's see how Keys 21 values marry the bucket index will come out to be 1 because 21 divided 10 will give remainder as one so bucket index is one so we simp simply access the hash note at this bucket index which would be nothing but our head so head will point to this node we check whether head is equal to null or not so here you can see currently head is not equal to null so in the while loop we simply check whether key 21 is already present or not so that is done via this if condition we simply check head dokey is equals our key or not so 21 is not equal to 21 so this condition comes out to be false and we simply Traverse head to it next node by assigning head. next to head so why this reference head has traveled to its next node because we want to compare each and every key present at this index with our key because there could be a possibility that 21 is already present in this list so after this assignment we again check whether head is equal to null or not so we encounter one more hash node so head is not equal to null but now here you can see head dot key is 21 it is equal to our key 21 so this condition comes out to be true which means that key is already present in our buckets array so we don't increment size here what we do is we simply assign the the value as marry to head dot value so head dot value is stor which will be updated by marry so here we are simply updating the value with the recent Value Old value is discarded and the size of the hash table Remains the Same because key is already present and after updating the value we simply return from this method so friends here you can see that we saw various use cases that how we can insert a key value pair in the form of hash node in a hash table we saw that how we can add a key value pair we also saw that how we can update a key value pair we also saw that what happens when there is a collision and we also saw the importance of our hash function that it can take a large key and provide us with a small index so that we can add this key value structure into this buckets array so friends I hope you must have find this information useful and in case if you have find this information useful then please like this video and if you are new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so now previous video we saw that how we can put a key value pair in a hash table we also saw different use cases which comes into picture when we actually put a key value pair in a hash table so one use case is if the key is not present we simply put the key value pair and increase the size and the Second Use case is if the key is present then we don't put the key value pair we simply go to that key and simply update the value for that key so if the key is present then we simply update the value we don't add the key value pairer in our hash table because key is already there so here before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that our hash table internally has an array of hash notes which we call as buckets it also has the capacity which is nothing but buckets. length and it also has size which is nothing but the number of key value pairs in a hash table or we can say the number of hash notes which this array holds we also saw that how internally hash table uses hash node class so here it has key value pair and a reference to next node so for our implementation we can take any key value pair but here I have taken key as integer and value as string we also saw about the size method which Returns the number of hash node in our buckets array and if size is equal to zero his empty method will return true now we'll see the implementation of the put method which takes in a key and a value and we'll see that how we can put this key value pair in our H table so at the start we simply provide simple edge cases where we simply check that if key is equal to null or values equal to null then here either we can return from this method or we can throw an exception let's say I throw illegal argument exception saying key or value is let's say null so friends here you can provide your own H cas so this is one of the simple edge cases I'm providing now here in order to put this key value pair in our has table the first thing we do is we try to evaluate bucket where we can put this key and value so for that we will be using modular hash function so here we first evaluate bucket index so we will call our hash function whose name is get bucket index and we pass our key to it because this key can be a very huge key and in order to accommodate a huge key in simple or small size array we need a hash function which takes in the key and returns us a smaller index value so that we can use that index and put this key value pair so here I'll be creating one private method as get bucket index which will return us back the index value for this key so it will take key and here I'm using the modular hash function so we'll simply return key mod divided by number of buckets and whatever is the remainder that will be returned from this method here we all can also use buckets. length instead of number of buckets so after getting the bucket index we will try to access the hash node which is at that bucket index so we do buckets we provide the index to it and whatever the hash note it will return it will be the head of the list which this index is holding so that would be our hash node and it will be head so after getting the head what we do is we can't ly put this key value pair in our hash table we first try to search each and every element present at this bucket index which is the list whose first node is referred by this head so what we do is we simply provide a while loop and we provide the condition as head should not be equal to null so if head is not equal to null then first thing we do is we try to search for our key because in case if our key is present then we don't put this key value pair in the hash table we simply update the value corresponding to this key so if head is not equal to null we provide if condition we check head. key equals the key which we have passed to this method and if it is true what we do is we simply update the value associated with this head node with our value so here you can see that we are using this head to Simply Traverse the list at this index and we are comparing the head key with the key which we have passed so this case handles if the keys is already present in our HH table so after we update the heads value with the new value we simply return from this method because we don't want to add this key value pair again so if this condition is false what we do is we Traverse head to its next node by assigning head. next value to head and this is important because let's say we have found a list of hash nodes which is being referred by head so we need to compare this key with each and every node which is being referred by this head so therefore we have provided this while loop and as soon as we have found found our key we are updating its value and returning from the method without adding this key value pair and if we are not finding it then we are simply traversing it to its next node so there would be a condition when head will reach to the end of the list so at that moment this V Loop will terminate and at that moment if V Loop terminates it means that we never found our key so we can now directly add this key so what we do in the first step is as we are adding this key value pair in the hash table we will increase the size by one and also friends here you can see that we can add this key value pair in the form of hash node and that hash node we can insert the way we want so here we will be inserting this hash node at the beginning of the list so in order to get the beginning of the list what we do is there could be a possibility that in this V Loop the head must have traversed so what we do is we simply do this step again and we make head reach to the first position by again assigning a hash note at this bucket index so after this step now head is pointing to the first node of the list and we want to insert this hash node before head so the first step we do is we create the hash node let's say we give name is node and here we provide the key and the value so here it looks something like this key value and it next is pointing to null so now how we can insert the note at the beginning of the list is we simply assign head to node. next here you can see head is pointing to the first node of the list and we want to insert this node just before that so it means it's next should point to head so this is the first step and the last step is Hash node at this bucket index is currently pointing to head so we need to break that link so here what we do is we do buckets bucket index and we assign the value of node to it so friends here you can see the hash note at this bucket index was initially pointing to head and as we inserted our node just before the head now hash noed bucket index is pointing to node which we want to insert and node next is pointing to the head in order to keep the rest of the nodes intact so this is how we can put a key value pair in a hash table now let's see it's working in the main method so here we'll create a main method first we will create the hash table let's say we provide the capacity as 10 which means number of buckets will be 10 and now what we do is we simply put few values let's say we put 105 comma let's say Tom we put 21 sa and now what we do is let's say we do table dot we print the size so if I run the code now so here you can see it printed two now what we do here is we again call table. putut and here we are again providing a key which is already there and this time we are providing the value as Harry so if I run the code now the size should remain the same same so here you can see it came out to be two and here if I debug this so here you can see if you open buckets array that 105 was added at index 5 based on our hash function where we divided 105 by 10 and remainder was 5 so if I open this you will will see the value as St and key as 105 and next pointing to null because we only inserted one value if I open the index one here we will see that we have only one value as next is pointing to null but here you can see the updated value is Harry initially it was saana now it became Harry and here we simply updated the old value with the new value and let's suppose if we add something like 31 denish and if I rerun it so here you can see 31 ided 10 will give index 1 so if I open index one you can see the 31 is inserted at the beginning of the list and now here you can see initially it was 21 so now 31 got inserted before that and its next is now pointing to 21 so this is how we actually put a key value pair in our H table I hope you must have find this information useful in case if you find this information useful then please like this video and if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update hello everyone so never previous video we saw that how we can put a key value pair in a hash table using the separate chaining Collision resolution technique and in this video we will see that how we can get a value by key in a hash table so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so friends let's suppose we are given with this hash table having buckets array where number of buckets is 10 which is the length of this hash node array and the size is three because we have inserted three key value pairs in the form of hash node and where we have detected a collision there we have inserted the notes in the form of chains here index one is nothing but our bucket index which correspond to this list whose index is one which is being generated by the hash function by providing a certain key so friends here you can see the advantage of searching a value corresponding to a key in this hash table is it is very much fast so for example let's say if we want to search for key 105 so here you can see that the number of buckets in the buckets array is only 10 and we are storing a huge value in this buckets array so after storing these values in in the form of chains there one question arises that how we can get that value because storing is easy but how we can get a value corresponding to a key and that to very much fast so here as we discussed the way we put the key value pair into the hash table using the hash function the same way we use the hash function and deduce the index and try to search for a key so here you can see that size is three so inside this bucket are there can be thousands of elements in the form of key value pairs so how hash function help us in searching our particular key value pair fast is let's suppose if we call table. getet and pass in a key as 105 so via this method we are asking that please get us the value corresponding to this key so here what happens is key is 105 so at the start what we do is we pass this key to our hash function and hash function provide us with an index and we try to search only in that particular index so this type of searching makes our data structure very much efficient in searching so here our hash function is we pass the key so here we can take any hash function which we like but here I'm taking this modular hash function where we are simply taking the key we are dividing it by buckets do length or number of buckets and whatever is the remainder that we are simply returning which will be treated as our index so if we divide 105 by 10 we get remainder as 5 so our bucket index is five so it means that this key can only present in the chain of notes corresponding to index 5 so we simply access the hash note at index 5 and to whichever node it is pointing that would be our head because there can be multiple hash nodes in this list so the first node is usually our head so we simply Point head to it and now our task is to search for our key so here we do head. key which is 105 we try to compare it with our key and if they are equal then we simply return its value which is John so friends here you can see there are so many elements but with just simple hash function we quickly search for our key so this is the simple case where our first node became the key which we want to search so after this let's say we search for 21 so key is 21 if we divide 21 by 10 we get remainder as 1 so our bucket index will come one so so we directly go to index one and we will try to access its first node so head will point to the first node via this link and here what we do is we simply compare head do key which is 31 with 21 so they are not equal it means for this node the key is not present but there are other nodes in this chain so what we do is we simply Traverse head to its next node via this reference so head comes to this position and now we again do head. key we compare 21 with our key and we see that we have found our key so what we do is we simply return the value as stor now let's suppose if we want to search for a key which is not present in this hash table for example if we call table dog and we pass the key as 88 so here we see 88 is not present so key is 88 when we will divide 88 by 10 we get remainder as 8 so the bucket index becomes 8 we go to the eth index and try to access the hash node which it refers so here you can see the head will point to null which simply signifies that this key is not present in this hash table so we simply return null from this hash table so friend these are the simple use cases where we can get a value by key in a hash table in our upcoming video we will see the code to get a value corresponding to a key from the HH table and we will see the demonstration of the code VI an animation I hope you have find this information useful and in case if you find this information useful then please like this video and if you new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw an animation that how we can get a value by key in a hash table so now let's look into the code with an animation but before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here the example which we discussed in our previous video we will use the same example and we will see that how it works via this code so let's say if we calling get method and passing in the key so here key becomes 105 and here you can see currently our bucket has three notes in the form of key value pairs so the size is three so at the first step if you want to get a value corresponding to a key the first thing we do is we try to find the bucket where that key might belong so how we can do that is we simply call our hash function we pass the key to it and it will return us back the index so when we will call get bucket index passing in the key it will return us back the index by simply taking in the key dividing it by the buckets. length or number of buckets and whatever is the remainder it will return return us back that index so here we can use any hash function and here I have used this modular hash function which is taking the mod of key and buckets. length and returning us back the remainder so when 105 will be divided by 10 we get remainder is five so the bucket index is five for this key it means that at index 5 this key will be present or it might not present moving ahead now as we have figured out the index so we try to access the hash note at this index so we do buckets and we pass in the index so this will return us a hash note which would be nothing but the head of our list of notes which can be there on this index so head will point to this hash node because this is the first hash note in a list of hash noes now how we can search for our keys we provide a while loop and why we are providing this while loop is because here you can see there is only one hash node but there could be a possibility that there are n number of hash noes so we need to compare each and every hash noes key with the key which we want to search so we are simply checking whether head is equal to null or not so if head is not equal to null it means that there are notes present at this index so we provide a if condition and we simply check whether head dot key which is 105 whether it is equal to the key which we want to search so here you can see this condition comes out to be true because 105 is equal to the key which we are searching so the if condition comes out to be true and we simply return head do value because we have find our key and we want to return its corresponding value so we simply return head do value so John will be returned now let's say if we want to search for a key which is somewhere in between of this list at a particular index so here we are calling get method with key is 21 so at the first step what we are doing is we are calling the hash function get bucket index we are passing in the key so this method will return return us an index where we can search for this key so when 21 will be divided by 10 we get remainder as one so the bucket index will be one so now we'll simply access the hash node at this bucket index and that will be our head so at index one we have this hash node so head will refer to it we provide a while loop because here we are having a list from which we want to search our key so we simply check whether head is equal to null or not so here you can see head is not equal to null so this condition comes out to be true we provide if condition that if head do key equals key which means that we have found our key So currently head do key is 31 We compare it with 21 so this F condition comes out to be false because 31 is not equal to 21 so we simply move head to its next node by assigning head. next value to head so head is pointing to this node it's next is pointing to this node so via this reference we will simply Traverse head to its next node we again check whether head is equal to null or not so head is not equal to null we check head. key which is 21 whether it is equal to the key which we are searching so yes head. key which is 21 is equal to 21 which we are searching so this condition comes out to be true and we will simply return return the value corresponding to this key which is Tom now friend let's say if we want to search for a key which is not present in this hash table so we call get method we pass in the key as 88 so key is 88 we calculate the bucket index we divide 88 by 10 and we get the remainder is eight so the bucket index will be 8 so we access the hash node via the bucket index which is this node which would be our head now so head is pointing to null and then we are providing this V Loop because there could be a possibility that it contains the chain of nodes so here you can see the condition here is head should be not equal to null but here head is equal to null it means that key which we are searching is not present in this hash table so at the end we are simply returning the null value which signifies that 88 is not present in this hash table so friends I hope you find this information useful and in case if you find this information useful then please like this video and if you new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw an animation that how we can get a value VI it key from my hash table so in this video we will actually code the algorithm and we'll test it working in the main method so before we start if you new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in our previous videos we saw a initial implementation of hash table and we saw that how we can put a key value pair in hash table which internally uses the hash function which is nothing but get bucket index and here the hash function which we are using is modular hash function which is using this modulus operator now in this video we will see that how we can get a value by providing its key so when we saw the implementation of put we provided this Edge case that key or value if they are null then we simply throw illegal argument exception saying key or value is null and as we are not putting any null key or null value when we will do get we simply provide this check again and here we'll simply check if the key is null then we throw illegal argument exception saying key is null so this is the simple H case which we are providing and now how we can get a value associated with this key which we are passing to this method because in hash table internally it is using buckets array of type hash node so how we can find our key and return its corresponding value we basically use the hash function which takes a key and return us back an index and corresponding to that index we try to search our key so here you can see we first evaluate the bucket index where this key might lie because there could be a possibility that this key is not present in our has table so what we do here is whatever the key we are passing we call get bucket index method we pass the key to it so this is our hash function so it will return us back the index where this key might lie so after getting the bucket index what we do is we try to access the first node of the list which corresponds to this index so here we simply access buckets we pass the bucket index it will return us back the hash node which would be the starting note of the list of HH node so we are assigning it to head now after getting the head our task is to find the key so for that we are providing this while loop and here we are providing the condition is head should not be equal to null so friends here you can see this is exactly what we did in put and also we provided while loop where we were simply searching for that key and if key was found we were simply updating its value so here I will simply call copy this and we'll paste it here so the only change we do here is if we find our key then what we do is we simply return head. value because we wanted the value associated with this key so we searched for the key and we checked that whether any Keys is matching to our key or not so in the if block we provided the condition if had do key is equal to our key then simply return its value and if it is not then simply move head to its next node by assigning head do next to head so friends here when we are accessing the hash node at this bucket index there could be a possibility that this hash node will point to other hash node and there can also be possibility those hash noes point to other hash noes so we are accessing the head we are comparing the key if key is matching then we are returning the value and if key is not matching we are simply going to its next node and doing the same steps again so friends if the key is present its corresponding value is returned and if it is not then we are simply returning null here now let's test it's working in the main method here in our previous video we added few Keys along with its values so if I run the code now you will see there would be three keys so it printed the size of the HH table is three because the key values pairs are three 105 21 and 31 here this 21 was already present so when we call put the saana was replaced with Harry so it simply updated the value it never inserted a new key value now here what we do is let's say if we do table doget and say return me the value associated with key 31 and we print it so if I run the code now it should print denish so which is corresponding to ke31 so now if we do table. getet and pass the key is 21 if I run the code it should print Harry because Harry is the updated value for key 21 and last let's say if we print a key which is not present let's say 90 if I run the code now so it should print null so it is returning null so friends in this video we saw that how we can get a value associated with its corresponding key I hope you have find this information useful and in case if you find this information useful then please like this video if you're new to my channel then please subscribe my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw that how we can get a value from a hash table VI it key now in this video we will see that how we can remove a key from a hash table so basically we will see the demonstration of remove method which takes in a key and it removes that key from the hash table and also returns its corresponding value back to us so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so let's suppose if you are given with this hash table having three hash noes where size is equal to three now let's suppose if we want to remove a particular key so what we do is we are given with a key we first try to find the index associated with that key via our hash function then we go to that index and we try to search for that particular key in case if we find that key then we simply remove that note from the corresponding list of that index and if we don't find the key key we simply return null so here you can see that there are various cases which needs to be handled while removing a key the first case is what if the key is not present so we simply return null the second case is let's suppose the key is in the middle somewhere so when we find that key we can't directly delete this node because if we delete this node directly then there are other nodes associated with this node which will also get deleted so what we do is let's suppose if we want to delete this key then when our node will reach to this point we compare the key and we find that we need to delete this node we have to break this link so in order to break this link we need to Som out access this node and this is accessed via a temporary node which is previous to our current node which we want to delete so here after we find the key which you want to remove the previous node will help us in removing this node so what we do is as previous is pointing to this node we have to break this link and make a link from this note to currents next because we don't want to remove the notes after that so we simply assign currents next to previous next so this link will go away and this link will point to currents next which would be the leftover noes after we remove this node so friend this is also one case where the key which you want to remove is in the middle of this list so for that we simply keep the track of its previous node which we will see later so let's suppose if you want to remove a key having value as 105 so at the first step we pass this key to our hash function which takes the key divided by buckets. length which is the number of buckets and return us back the remainder of it because here we have this modulus operator so whatever the remainder is returned that is nothing but our index where we can find that particular key so if we divide 105 by 10 we get remainder as five so the bucket index becomes five we simply access the hash node at bucket index 5 so this will be our head so as head is pointing to the first node at the start we assign a null value to our previous node so this previous will simply track the previous node to our head we will see why it is needed later in this video So currently previous is pointing to null Now using the head we will simply search for our key which we already discussed in our previous videos so we do head. key which is one5 We compare it with our key so here head do key is equal to the key which you want to remove remove it means we have to remove this hash node so what we do is as previous is pointing to null it means we want to remove the first node of the list so currently head next is pointing to null so there could be a possibility that there are n number of nodes after that so it means that we want to remove the first node from the list so what we do is in order to remove this node we have to first break this link so that there is no reference to this node and it can be freed up but we can't directly break this link because there could be notes after that so these notes which can be after the head will also be removed so what we do is so first we decrease the size so size becomes two and now what we do is if we do head do next we will get the remaining hash notes in the form of chain and as head do next is pointing to the notes after that if we assign head do next value to buckets at this index so this note can be freed up and this reference will point to whatever the head dot next is pointing So currently it is pointing to null so what we do is if previous is null which means that we want to remove the first node of the list so here we will assign head. next value to bucket index five so it would look something like this head do next is null so this link will be removed and it will point to null and now we can simply remove this node and we can return head dot value which is John so it would look something like this now let's say if you want to remove key 21 so 21 ided 10 will give remainder as 1 it means the 21 key can be present at index one so we access the hash node of index one so this would be our head at start we assign null value to previous now here first we search for our key so we do head do key which is 31 We compare it with our key which is 21 so here you can see 31 is not equal to 21 so what we do is before moving head to its next node in order to search for the key we first assign the value of head to previous because we need to keep the track of the previous node so that in case if we find a key then we can use its previous and break the link so that the key which we have searched can be removed easily so here as head is pointing to this node now previous will point to this node and we will simply Traverse head to it next node via this link now we again compare head do key which is 21 with our key so here you can see that we have found our key so our task is to now remove this node but there could be a possibility that after this node there are many other nodes so what we do is as we want to remove this node first we decrease the size so size will become one and we simply check whether previous is pointing to null or not so here you can see previous is not pointing to null it means that our key is lying somewhere in the between of this list because if previous would have point to null then we would have sure that head is pointing to the first node of the list but as previous is pointing to this node so what we do is we simply assign head next value to previous next so why we do that because we need to first break this link so when this link will be broken then this node will have no reference so this can be garbage collected but there is one problem head. next will refer to other noes as well so those nodes will also be removed if we break this link directly so what we do is head. next will point to the notes after that so we simply assign head. next value to previous next so instead of previous next pointing to head it will now point to Heads next so this note can be freed up so it would look something like this this link will go away and as head. next is pointing to null so it will point to null so now this hash node can be removed easily we'll return the value Tom and then we'll simply remove it now friend let's say we are given with this two notes and we want to remove 31 so what we do is we do 31 divided 10 which gives remainder one so bucket index is one we simply access the hash node at index one we give it a value as head because this is the first node of the list we will assign previous a value of null and then we compare 31 which is head. key with our key so that we can search for that particular key which we want to remove so here you can see head do key is equal to the key which you want to remove it means we want to remove this key so so first we simply decrease the size so it will become one because we are removing this key now and after that we need to break this link so that this note can be freed up but if you remove this link directly then all the notes in this list will be removed we only want to remove this node and keep all the notes after that intact so what we do is how can we access all the notes after that is we simply do head. next and if we do head. next we reach to this node so here we break this link and we assign a value of head dot next to it so now this link will go away and it will point to this node and the nodes after that so here we are simply assigning head. next value to buckets array at index one so it would look something like this this link will go away and it will point to this node and once the method will end this node can be safely removed and we can simply pass the value associated with this key so after it gets removed it would look something like this so here there could have been multiple nodes after that so we have kept that list intact and we have removed the node from the middle so this is also one of the use case now let's suppose if we are given with this hash t table with two notes and we want to remove a key which is not there in this hash table so key is 88 if we divide 88 by 10 we get bucket index is 8 we access the hash node at index 8 so here it is pointing to null which means that key is not present in this hash table so we simply return null so friend these are the cases which are involved when we remove a key from our hash table I hope you find this information useful and in case if you find this information useful then please like this video and if you new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw that how we can remove a key from hash table VI an animation so in this video we will see the algorithm why an animation and we'll see that how it works step by step so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that this is the algorithm to remove a key from the hash table so let's see the demonstration of it step by step we will take the same use cases which we discussed in our previous video so when we will call table. remove and pass the key as 105 the remove method will be called with a key 105 now at the first step what we do is we search for that key and how we can search for that key is first we get the bucket corresponding to this key so we call our hash function get bucket index we pass in the key and it returns us back an index by dividing Key by buckets. length or number of buckets and return us back the remainder because it has this modulus operator so here if we divide 105 by 10 we get remainder as five so this method will return us the bucket index as five now what we do is we have got the bucket index and we know that key 105 will lie at this bucket index so we simply access the hash note at this index which is five here so the first hash note is nothing but our head and there could be n number of hash notes so head will point to the first hash node now in order to keep the track of the previous hash node we simply assign it with the null and why we keep the track of the previous hash node we will see later so we are providing this V Loop which is pretty much same what we saw in our previous videos that we are trying to search the key first So currently head is not pointing to null so this condition comes out to be true we check whether head. key which is 105 is it equal to the key which you want to remove so here you can see this if condition comes out to be true so what we do is as soon as we find the key which we want to remove we simply break from this V Loop because we have found our key and now it's time to remove that key so when we break from this V Loop it will come here and here we encounter one use case that head could point to null so which we will see later so currently head is pointing to a hash node which is not null so this condition comes out to be false so now here you can see as we want to remove this node we will first decrease the size by one so size will become two and after that we encounter a a Els block which is very much important because here if previous is not equal to null so this is the if condition if previous is equal to null it means we are trying to remove the first note of the list let's say if we take this example and if head is pointing to this so previous will point to null so it means we are trying to remove the first node of this list and if previous is not equal to null it means the key which we have found is somewhere in the between of this list so that use case we'll see later so currently you can see previous is pointing to null so our if condition comes out to be false and the else part will be executed and here we want to remove this node from the list so what we do is is and we know that this is the first node which is being referred by buckets array at bucket index so in order to free this node we need to remove this link we will assign head. next value to buckets array at bucket index so the hash node referred by bucket index which is this instead of pointing to this node it will simply point to head. next because we want to remove this node and this node can also have other nodes so we can't directly break this link We simply assign head. next value to this index So currently for this use case you can see head. next is pointing to null so here we simply break this link and we assign head. next which is null so it will point to null and here you can see after this method gets end first we return the value associated with it which is John and once this method will end this node will be garbage collected so it would look something like this now let's suppose if you want to remove a key 21 so first we'll find its corresponding bucket so 21 divided 10 will give remainder as 1 so the bucket index is 1 so we simply access the hash noted bucket index one which is this node and there could be a list so we assign head to this node because this is the first node of the list we create a hash note previous and at the start we assign a null value to it and now as we want to remove the key 21 so we search in this list using this file Loop So currently head is not equal to null if head. key equals the key which we want want to remove then this if condition will come out to be true so here head do key is 31 it's not equal to 21 so the condition in if block comes out to be false so this is the key we are comparing it with 21 and as this condition is false we will reach here so usually we search for the key in complete list so for this node the key didn't match so before going going to its next node by assigning head do next to head what we do is we simply keep the track of this node because let's say if you find this key here then we can use the previous node and we can simply remove this link here so that this node can be freed up so before moving head to its next Noe we assign the value of head to previous so it would look something like this and now we simply move head to it next position by assigning head do next to head so head do next is pointing to this node so via this link head will now point to this node head is not equal to null if head. key equals the key which we want to remove so head do key is 21 and 21 is equal to 21 so this condition comes out to be true and here we know that we have found our key which we want to remove so so we simply break from this while loop we first simply check whether head is equal to null or not if head is equal to null then we simply return null So currently head is not equal to null it means we need to remove this key so we first decrease the size by one size becomes one and now here you can see previous is not equal to null previous is pointing to this node therefore this condition comes out to be true so why we provide this check is if previous is equal to null it means we are trying to remove the first node of the list and if previous is not equal to null it means the key which we have found is somewhere in the middle of the list because previous is providing that information to us so in the F part what we do is we need to remove this link and we can't directly remove this link because head. next May point to the other not so what we do is we simply assign head. next value to previous next so it would look something like this that now previous do next is pointing to null and why we did that because let's suppose if there are n number of notes after that and we want to only remove this key we don't want to touch other notes so to whatever value head. NEX is pointing previous do next should point to that node but here it is null so previous do next is is pointing to null we will return the value Tom and this node will be removed from the hash table now friend let's suppose if you want to remove a key is 31 so we calculate the bucket index 31 divided 10 will give remainder as one so one will get return from our hash function so bucket index becomes one we access the hash node at this bucket index and to whichever node it is referring that will assign to head so head will point to this node at the start we do previous equals null and then we search for our key so we check whether head is equal to null or not so head is not equal to null so the while loop will start then we provide if condition to search for that key so if head. key equals the key which we want to remove head do key is 31 and the key which you want to remove is also 31 so this condition comes out to be true it means we have found our key we break and then we check whether head is equal to null or not so head is not equal to null it is pointing to a key which we want to remove and before removing the key we decrease the size by one so size becomes one and now here you can see previous is pointing to null so the else part will be executed and in the lse part you can see that why we are doing head do next in use case one head do next was pointing to null but here you can see there is possibility that head. next is pointing to other nodes so we can't directly break this link so to buckets array at bucket index we assign the value head. next so now this link will be removed and as we are assigning head dot next to it this will point to this node because head. next is this node so it would look something like this that we are assigning head. next value which is this node two buckets array at bucket index so now here you can see this note can be freed up easily by returning the value saana and if you rearrange it it would look something like this so here we removed a node and we saw the importance of doing head. next because we can't directly break the link this link we need to assign it head. next so that it should refer to the remaining notes of the key which you want to remove so friends one last use case is this use case where we want to remove a key which is not there in this hash table so we'll calculate bucket index 88 divided by 10 will give remainder as 8 so bucket index is 8 we access the hash node at this index so here it is pointing to null which means head will point to null we create previous and we assign a null value to it here head is pointing to null so it means this condition comes out to be false and here as head is equal to null it means that size Remains the Same and key is not present so we simply return null so in this video we saw that how we can remove a key from a hash table and we saw the demonstration of the algorithm step by step I hope you have find this information useful and in case if you find this information useful then please like this video if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw that how we can remove a key from a hash table and we saw the working of the code through an animation now in this video we'll actually code the remove method which takes in a key and return us back the value associated with the key which we are trying to remove so here in our previous videos we saw how we can put key value pair how we can get a value corresponding to a key so now we'll see that how we can remove the key so friend at the start I'll simply copy this part so here if we are passing key as null then we are simply throwing an exception saying key is null so this is the illegal argument exception which states that key is null so this is the simple H case and now in order to remove a key what we do is we pass this key to our hash function and this hash function will return return us a index where we can search for this key and once we find that key we simply remove it so it will return us back the bucket index after getting the bucket index we access the hash node at that bucket index and as that index is pointing to a hash node which is the starting point of the list corresponding to this bucket index we give a name to it as head so friends here you can see that these two steps are are being used in get method also and in put method also now what we do is in order to remove a key let's say this index if I simply copy this part and here at this index let's say we have this list of hash notes something like k21 value of storm now let's say it has three notes something like this where key 31 has value Harry and key for 41s value let's say saana now head is pointing to this node because this is the first hash node of the list now our task is to remove this key so let's say if we want to remove the key as 31 and head is pointing to this so first we will search our key by traversing head to each and every node and if you find the key let's say if we find the key 31 so somehow we need to access this hash node because this link needs to be removed in order to free this node and if you free this node directly then all the nodes after this node will also be removed so what we need to do is as head as Travers to this node so first we simply keep the track of its previous nodes so wherever head will go we will keep a reference to its previous node which is very important while removing a key from the hash table so if head is here and key matches so previous will be here so to previous next we have to break this link so to previous next we need to assign head next because we need to keep these notes intact we will assign head. next value to previous next head. next is this node and the notes after that it will be assigned to previous next so this this link will go away from this node to this node and then we can simply remove this hash node so for that what we do is at the start we create a previous hash node we assign it a value as null because as head is pointing to this node at start we are doing previous as null so now what we do is we search for the key so for that we provide the while loop and here we will use the same while loop which we did in the get so here we are providing the condition as head should not be equal to null and if head is equal to null it means we have traversed this complete list and we didn't find our key and if head is not equal to null what we do is we compare head do key with the key which we want to remove and after we find our key what we do is we simply break from this V Loop because after this V Loop head will point to the key which we want to remove let's say here 31 so head will point to this key because this condition matches so let's say if we take this example and if we want to remove a key as 31 so in this file Loop head will first check it with 21 this condition comes out to be false then we go to its next node head will come here it is not equal to null then we'll compare head. key which is 31 with the key which we have passed to this method so as soon as we find our key head is pointing to this node and here what we do is before moving the head to its next position what we do is how can we keep the track of this previous no is we first assign head to previous so previous and head will point to this node and then we simply Traverse head to its next node so previous is a step behind the head and why we are keeping previous just behind the head is because let's say we have searched for the key which we want to remove so we break from this V Loop and as soon as we break from this V Loop previous is here and head is here so after this while loop what we do is we first check that if head is equal to null or not so if head is equal to null it means we didn't find any key in this list because this while loop would have terminated when head would have pointed to null which is the last node next so if had would have reached here it means we haven't found our key so we we are simply returning the null value and if head is not equal to null then the first thing we do is we decrement the size by one because now we are about to remove the key so here now two condition arises one is at the start previous is pointing to null and head is pointing to let's say 21 and what if if you want to remove 21 only so in that case we are simply removing the first note of this list and how we can come to know that is the first node only is via the previous because if previous is null and after this if block we can come to know that head is not equal to null so it means head must be pointing to this node only and which means we have to remove this key so here we provide the if condition and we check that previous is equal to null or not so if previous is equal to null and if our code has reached here it means head is also not equal to null which signifies this head is pointing to the first node so in the else part what we do is we have to remove the first node and it is being referred by this the hash node at bucket index is the first node so here what we do is we simply reassign this value to something like we do head dot next so it means that our buckets array at this bucket index was pointing to a hash node to which our head was also pointing and now we need to remove this node so head is pointing to this node if we assign head dot next to this then this node will be removed easily and now our buckets and array at bucket index will point to this node because 21 would be removed so this is the small change which we do if previous is pointing to null and if previous is not pointing to null now let's say if we want to remove 31 so head will point to this and previous will point to this so now instead of doing this stuff what we do is we do previous do next and we assign head do next to it so here you can see head do next Remains the Same as previous is not equal to null it means we can't use this stuff because this is only used in case if we want to remove the first node of the list but if we want to remove let's say a node in the middle then previous will help us in removing that so head was pointing to this and we want to remove this and previous was pointing to this so to previous next we assigned head next this value so now this hash node next will point to this hash node and this hash node can be removed easily so this step does that so after this reassignment head is still pointing to this so at the end what we do is we simply return return head do value and once this method will get terminated this head is our local variable so it will be garbage collected so friends what we did in the remove method we took the key we evaluated the bucket index where this key might lie the starting hash note we denoted it with head we created previous and at the start we provided a null value to it and now in the while loop we try to compare each and every key with the key which we want to remove remove because if we don't compare then we'll not able to get which node we want to delete so as soon as we found the key which we want to delete we break from this file Loop and we perform the assignments here but let's suppose if the key is not found for the first iteration then what we do is we have to move head to its next node but if we move ahead to it next node we can't delete this node we need to keep the track of its previous node as well so before moving head to it next node we are assigning the value of head to previous and then we are moving head to its next node so that when we will find any key in the middle we have reference to a node before that so that we can reassign its next pointer here you can see we are reassigning it so if the key which we want to remove is at first node then we simply assign head. next value to buckets array at this bucket index and if it is somewhere in the middle or end then we have this previous reference we simply assign head. next to previous next and finally we return head. value and once we return head do value this method gets terminated and the node gets freed up so now let's test it's working in the main method so here you can see let's suppose we have this three keys 105 2131 and if I run the code now you will see size will come as three because there are three hash notes or key value pair now what we do is let's say we remove 21 and we print its value on the console so here you can see it printed Harry because Harry was associated with key 21 now let's say if you want to remove 31 so now if I run the code you can see it printed denesh and if I print the size of of it so here we have removed two notes so it should print one so it has printed one so here you can see only 105 remains in the hash table because we have removed 21 and 31 so here if I simply copy this part so here before removing these two values we add hash table something like this this is three the 21 Harry and let's see if I remove this for timing so this was our hash table at index one because we are removing 21 and 31 so if we evaluate the bucket index 21 divided 10 will give remainder is 1 so this is for the index one we first added 21 using put and then we added 31 so 31 came before 21 because we are inserting the hash not at the beginning of the list so this was the situation so when we removed 21 head started with this note then it reached here and previous reached here so 21 matched with our key and at the end what we did previous next was assigned with Heads next which is null and then we removed 31 so this node was removed and when we printed the size it printed one only this key value pair exist and we removed these two key value pairs so friends I hope you find this information useful and in case if you find this information useful then please like this video if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem contains duplicate so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in this problem we are given an integer array and our task is to return true if any value appears at least twice or return false if every element is distinct so let's understand the problem with an example now let's suppose we are given with this integer array having elements as 1 2 3 1 now our task is to return true if any value appears at least twice so here you can see that one appears at two places therefore we return true and return false if every element is distinct so here you can see in the second example the array is 1 2 3 4 so all the elements are distinct therefore we have to return false so here our task is to check whether the array contains duplicates or not now let's move ahead and see how we can solve this problem via various techniques so let's suppose we are given with this array 7 3 1 4 1 and we know that one appears at least twice therefore we know that it contains duplicates so the first way to solve this problem is a very Brute Force approach where we take each element and compare it with the rest of the elements in the array and we figure out whether the element is duplicate or not so when we try to solve this problem we take a pointer I and let's say the value is seven we take another pointer J and we compare the values at I and J index so at the start 7 is compared with three they are not equal so J moves to the second index 7 is not equal to 1 so J moves to third index 7 is not equal to 4 so J moves to the fourth index 7 is not equal to 1 so therefore we figure out that s is unique among these elements so after that I moves to three and J points to index after I because 7 is already being compared with three in the previous iteration so three is compared with one they are not equal so J moves to third index three is compared with four they are not equal so J moves to the fourth index 3 is not equal to 1 so therefore we come to know that three is also unique in this array so we increment I now I comes to the second index so J starts from the third index one is compared with four so they are not equal so J moves to the fourth index now here 1 is equal to 1 so therefore we come to know that there are duplicates in this array and one is appearing at least twice so therefore we return directly true from the method so if we see via this approach we need two for Loops one for I and one for J so using these two for Loops we can can figure out whether the array contains duplicates or not so the time complexity of this method is O of n Square because this approach contains nested Loops so this is not very efficient solution now can we reduce the time complexity from o of n² to less than that so one thing we can do is we can actually sort this array so when we sort this array in ascending order the elements will rearrange something like this 1 1 3 4 and 7 and now after sorting we can use one for Loop to check whether the neighboring elements are equal or not so if they are equal we just return true and after the loop ends if we didn't find any duplicates then we can return false so whilea this approach when we are sorting the array the time complexity comes out to be n login so this is a better approach and time complexity now is there any other way where we can reduce this time complexity so we'll look into that so in order to reduce the time complexity what we can do is we can use an additional data structure so let's say if we are using a headset the property of headset is it only contains unique elements now what we can do is we can iterate over this array we can take one one element and we check whether the headset contains that element or not if it doesn't contain then we simply add it to the headset and if headset contains that value then we are sure that it contains duplicates so for example the first value is seven we check whether headset contains seven or not so it doesn't contain so we put seven into the headset then we check for three whether the headset contains three or not so it doesn't contain so we put three into the headset then we take one so one is not in the asset so we put one into the asset then we take four four is not in the haset so we put four into the headset at last we get one so when we check whether one is there in the headset or not we come to know that one is already there so therefore we directly return true that we have found a duplicate now let's say instead of one there would have been six so we would have checked whether six is there in the headset or not so it was not there so we put six into the headset and after that there are no elements in this array to be traversed so at the end we would directly return false that there are no duplicate elements in this array Now by doing this the time complexities we are iterating this array once so time complexity becomes o of n but space complexity increases because we are using an additional data structure so the space complexity is O of n but this is the much better approach because the time complexity is reduced now let's move ahead and see the animation of this algorithm step by step so this is the code where the method name is contains duplicate we pass in the array so at first when we we call contains duplicate method we pass in the array now let's say if we are given with this array having values as 1 3 5 4 1 so at the first step what we do is we create a head set so this is our set now as we discussed we just iterate each and every value once so we provide a for Loop where I starts from zero index like this and I goes till nums do length so here the array contains five elements 1 2 3 4 5 so nums do length is five so it goes from zero index to 4th index So currently 0 is less than five so this for Loop executes now has set has a method contains when we call this method it actually returns true or false if the element is present in the head set returns true and if the element is not present it returns false so nums of I is nothing but the value at zero index so we check whether set contains one or not so here you can see set doesn't contain one so set do contains will return false because this element is not present so we add this element into the set so one is added into the set now we increment I so I becomes 1 1 is less than 5 we check whether value three is present in the set or not so set do contains return return false because three is not present so we simply add three into the set we increment I so I becomes 2 and 2 is less than 5 so this for Loop will will execute now nums of I is nothing but value present at second index which is five so we check whether set contains five or not so set doesn't have five so it returns false so we simply add five into the set like this we increment I I becomes three 3 is less than 5 so this for Loop will execute we check whether value at third index which is four present in the set or not so this actually return false because four is not present into this set so we simply add four into the set we'll increment I I becomes 4 4 is less than 5 so this for Loop executes now here value with aat index is one and when we check whether one is present in the set or not so one is already present in the set so set do contains return return true so it means we have found a duplicate in this array because one we inserted into the set at the beginning and again we found a one so set do contains written true because one is already present in the set so it means that our array contains a duplicate so this if blog is executed so here we directly return true which states that our array contains the duplicate now let's say if our array doesn't contains the duplicates so instead of one we put a six so after placing 1 3 5 4 into the set the last element would have been six and if we do set do contains six so it returns false and if blog doesn't get executed so we simply add six into the set now when we increment I I becomes five and five is not less than five so therefore this for Loop will terminate so at the end we directly return return false stating that our arror doesn't contains duplicate it contains unique elements so friends in this video we discussed the problem of contains duplicate I hope you must have like this video thanks have a nice day hello everyone so in this video we are going to discuss about a very important topic which is intervals so in this video we are going to see a basic introduction to intervals and we will also see what are overlapping intervals now this this is a very important topic for the coding interview there are questions asked on the concept of overlapping intervals so let's move ahead and see what are intervals and what are overlapping intervals so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so first we will see a basic introduction to an interval so usually an interval is actually a range which is represented by two numbers something like 5A 8 6A 10 so an interval is a range where two numbers are involved now that two numbers are termed as start and end so here five will be our start and eight will be our end so these two numbers are basically start and end of the interval which actually represent a range now usually when we talk about interval they are correlated with time now when it is related with time this start and end can be any unit of time it can be millisecond seconds minutes so here let's see the time interval of few task let's say task a has a time interval of 1A 3 B has time interval of 4A 5 C has time interval of 8A 10 D is time interval of 9A 11 so if you take a time exis like this now here it could be seconds milliseconds Nan seconds it can be any so let's say if we want to plot this task on this time axis and we take it as seconds so it suggest that task a has start time of one and it has end time of three so if we plot task a on this time axis it would look something like this that a task starts from one and ends at three so it means if we take it in the form of seconds task a takes 2 seconds to complete from 1 to three if we plot B it starts with four and ends on five so it takes 1 second if we plot C so the start is 8 and end is 10 so it takes 2 seconds to complete and if you plot D so it starts at 9 and ends at 11 so it also take 2 seconds so usually these time intervals represent a range let's say for a task or for a process and mostly the coding interview problems are given with these intervals so here we saw that an interval has two numbers start and end now let's see how we can represent this interval in form of a code so the interval representation looks something like this that there is a class interval now this is a custom class which we will create which has two properties start and end so this start will will represent the starting point of the interval and end will represent the ending point of the interval so any interval takes only two numbers start and end and if you want to create an interval we have provided this Constructor which takes in a start and end and initialize a particular interval with these numbers so this is how we actually represent a interval class so now let's move ahead and see the concept of overlapping intervals so what are overlapping intervals so let's if you have interval something like 1A 5 and another interval is 2A 6 so if you plot this intervals it looks something like this this is one this is five and let's say two is here and let's say this is six so here if you see this is the first interval with 1A 5 and this is the second interval with 2A 6 so now if you closely look they are actually overlapping in this region from interval 2 to 5 so this actually suggest that these two intervals are actually overlapping with each other in this region 2A 5 so for an overlapping intervals we actually require two intervals at minimum let's say if we denote it by A and B so there will be some relationship between these two intervals so the first relationship would be that A and B do not overlap so it means a starts and ends here and B starts and ends here so here if we take an example let's say 1A 3 and 4A 5 so this is one interval and this is another interval but they don't overlap if you have interval something like 1 comma 3 and 3A 4 then that will overlap because the end time of first interval is equal to start time of another interval But Here There is a gap between these two so they don't overlap the another thing would be a and b overlap but B ends after a so it would look something like this that a starts here and ends here and B starts here and ends here so here B is ending after a and this is our overlapping interval so if we take an example let's say 1A 4 and 3A 6 so here you can see these two intervals actually represent this condition that a interval starts from one and ends at 4 and B starts at three so it means this is 1 this is 4 this is three and this is six here B is ending after a so we can visualize these two intervals like this the third would be a completely overlaps B so it would look something like this that a is actually overlapping B completely so if you take an example it could be like 1A 6 for A and B could B 2A 4 so here 1 6 2 and 4 so it says that a is completely overlapping B so this could be one such case so the fourth case is a and b overlap a ends after B so this is pretty much same as this but here it looks something like this here B was ending after a but here a ends after B so these two are pretty much same only the names of the intervals have changed B completely overlaps a so this is pretty much same as a completely overlaps B so it would look something like this here A was completely overlap in B and now here B is completely overlapping a so here we just need to change the order of A and B so if this was a and this was B so here a would be 2A 4 and B would be 1A 6 rest everything Remains the Same and the sixth case is b and a do not overlap so this is pretty much same as a and b do not overlap so it looks something like this so friend these are the six cases where we can demonstrate the overlapping intervals so for a situation where this overlapping intervals come we at least need minimum of two intervals and there could be many intervals like a b c d which can overlap with each other but we actually require minimum of two so friend in this video we covered what are intervals and what are overlapping intervals in our future videos we will see few problems related to overlapping intervals I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we discussed about what are intervals and what are overlapping intervals so now in this video we will look into a problem of merge intervals so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so if you look at the problem you are given with a list of intervals you need to merge all the overlapping intervals and return a list of non-overlapping intervals so let's see it by an example let's say we are given with a list of intervals like 2A 6 1A 3 8A 10 and this intervals can be in any random order so we need to merge only those intervals which are overlapping to each other and at the end we have to return a list of all the nonoverlapping intervals so the output would be 1A 6 and 8A 10 now how this output came we'll see in a diagram so let's say we have this time AIS and we have this intervals 2A 6 1A 3 and 8A 10 we will plot these intervals on this time axis so first we will take 2A 6 so the start is at 2 and end is at 6 so this interval takes four unit of time now let's say if time AIS is in seconds so this will take 4 seconds if you plot 1A 3 it would look something like this 1 is the start and three is the end and after that we will plot 8 comma 10 so it looks like this so this is 2 seconds interval and this is also 2 seconds interval so here if you see this 1A 3 and 2A 6 are overlapping to each other so this is the area where they are overlapping so it means we have to merge all the overlapping intervals so if we merge these two intervals together we will get a bigger interval whose start will be one and end will be six so here as these two are overlapping intervals when we will merge this two you can simply take this first interval and put it on the top of the second interval and that will be our merged interval so it looks like this the start will remain the same because this interval came first and the end will actually depend that which interval has the maximum capture duration so here in this case the first interval is completed at third second and the second interval is completing at the 6th second so we will take the max of three and six and it merges to 1A 6 so this is the merged interval because these two intervals are overlapping to each other but here if you see 8 comma 10 as we have only three inputs 8 comma 10 is not overlapping with any of these intervals and we have to return a list of nonoverlapping intervals so 8 comma 10 will remain as it is like this so therefore our answer is 1A 6 and 8A 10 if this 8A 10 would have been 6A 10 or 5a 10 then our answer would have been one complete merged interval of 1 comma 10 so let's move ahead and see how we can solve such problems so for the overlapping interval in our previous video we saw the different use cases that when two intervals are overlapped with each other what happens so one such condition is a and b do not overlap so it looks something like this that there is a gap between these two intervals so we can't merge them now if a and b overlap but B ends after a so it would look something like this now here one thing we are assuming is a will always come before B so this diagram will make sense that b ends after a and if a A and B overlap it would look something like this a completely overlaps B so it would look something like this but still a is coming before b b completely overlaps a in a case that both have same start time so B is completely overlapping a but a should come either before b or it can start at the same time so therefore we are taking this assumption and we will come to know later why it's important so this is one such case where B will completely overlap a but as a should either start at the same time as b or before B this would be one such use case now we will see all these cases and why they are important so with the first case When A and B overlaps and B ends after a so this is the case so when we will merge these two intervals A and B and let's say result we denoted by a c now as we are merging these two intervals A and B here you can see the the range of C which is start and end would be a start and B end so here you can think of any two intervals but one thing is sure both of the intervals either will start at the same time or one of the interval would be coming first so whichever interval is coming first its start will become C start and the value of C end will depend on the maximum expansion of any of this interval so here you can see as B ends after a B's end value will become C's end and after merge it will look something like this so let's say if a starts from one and ends at three and B starts from Two and ends at five so here you can see this is the overlapping part so when we will merge these two intervals let's say we put a on the top of B so it will become something like it starts from one like this and ends at five so this is the merging we'll see another use case let's say a completely overlaps B so in this case if we merge these two intervals let's say we put a on top of B so it would look something like this that c start becomes a start because this is the start of the interval and as a completely overlaps b c's end will become A's end like this so this is one such use case if we look at the third use case where a start is actually equal to B start and B ends after a so in this case if we merge both these intervals it would look something like this that if you put a on top of B the C start will be either a do start or B do start it will be same but the end will be B's end because this is the start and this would be the maximum value till both the interval goes so in all these three use cases one thing to keep in mind is we are assuming a will either start before b or at the same time of B so C start will be equal to a start this is sure and C end there will be a condition that we will take Max of A and B end and whichever is the maximum value that will be assigned to C's end so in this case here you can see a end is three and B end is five so C end becomes five here you can see a completely overlaps B so a end is greater than B's end so therefore C end becomes a end and similarly here as B is completely overlapping a so B end is having a greater value than a ends so whichever is the maximum that gets assigned to CN and that will be our merged interval now one thing we discussed that a should start before b or at the same time but if we look and do the problem we are given the intervals in random order let's say 10A 19 3A 4 1 comma 2 and let's set 2 comma 3 now we have to merge all overlapping intervals so one thing we need to keep in mind is we have to first sort all this intervals based on their start time once we get the start time this condition will come into picture that one of the interval is starting before the other and once we sort it based on the start time all the intervals start time will be in ascending order so we can directly compare one with the other and see if they are overlapping with each other or not so in order to solve this problem the first thing we need to do is we need to sort the intervals based on the start time so this condition will come into picture that a do start will be less than or equal to B do start so here a do start in this case is less than b do start in this case also it is less than b do start but in this case a do start is equal to B do start so this condition is important so when we will sort these intervals the merging becomes easier here if you see let's say if you want to merge this two elements we know that a do start is before or equal to B do start so C do start will directly becomes a do start because a is coming before B but C do end which we discussed here its value will depend on whichever interval is going to Greater time span so it would be Max of a do end and B do end so here in this case a do end was smaller than b do end so C became B do end in this case if we merge these two elements then B do n was lesser than a do n so when we merge it become a. n and similarly here B do n is greater than a do n so therefore on merging CN becomes B do n because we have to take the maximum of a do end and B do end so these two conditions are very important and once we do the merging of let's say two intervals we can keep proceeding ahead with all the overlapping intervals and we can check which are overlapping intervals and we can merge them so friend let's see the demonstration of this algorithm step by step so we have this merge method which actually merge the overlapping intervals and we are given with a list of interval and our task is to merge the overlapping intervals and return done a list of all non-overlapping intervals because once we merge all the overlapping intervals they all become non-overlapping so first we will call the merge method we pass in the list of intervals so it would look something like this that this is the list of interval 7A 9 2A 6 1A 3 and they are in random order so the first thing we have to check that whether interval size whether it is less than two or not so if it is is less than two it means list has either zero elements or one element it means there is only one interval or zero interval so we don't have to merge anything we have to Simply return the same list back so this is one H case so currently intervals. size is three therefore it is not less than two now in order to compare whether all these intervals are overlapping to each other what we need to do is we have to sort all these intervals based on their start time so that we can come to know that whether there is any overlap or not so the list has a sort method which takes in a comparator and comparator has a comparing int method which actually returns a comparator now in this method this is a static method so in this method we are simply telling that take each interval and sort it based on the start time so this comparing int method will take this intervals list we'll sort it based on the start time so the intervals will become something like this 1A 3 2A 6 7A 9 so start time so 1 is less than 2 2 is less than 7 so it has sorted based on the start time moving ahead now as we need to return a list of all non-overlapping intervals we will create a result list like this so currently it's empty now as we have sorted the intervals based on the start time we will compare the adjacent intervals so that we can check whether they are overlapping or not so in order to compare all these intervals the first thing we do is we simply take the first interval as it is so this is the time AIS and the first interval is 1A 3 so if we plot it here it looks something like this now our task is to compare this 1A 3 with 2 comma 6 and check whether anything is overlapping or not so for that we will create two variable start and end we will see it significance later so to the start variable we will assign first do start because we are starting with this interval so start becomes one because first dot start is one and to end variable we will assign first. end so first do end is three so we are simply taking this two intervals start and end as 1 comma 3 and now as we have to compare it with other intervals we will take all these intervals in a for Loop and we will start with one because Zer is already taken so this is zero this is one and this is second index so we will start I from one so it would look something like this that we are now picking up 2A 6 and I is less than intervals do size 1 is less than three so this condition comes out to be true now you can think start and end represents first and in the for Loop currently we are on two comma 6 so this becomes our current interval and this can be treated as previous intervals so from this list we will get that interval by calling intervals. getet we'll pass the value as 1 so we will get 2A 6 so this will be assigned to the current like this and if you plot it here you can see 2 comma 6 now our task is to Simply check whether 2A 6 is actually overlapping with any of the previous intervals or not so we will check whether current do start is less than equal to the end so we are not doing first do end because there could be many intervals before this current interval and start and end will represent just the previous interval which are being merged or non overlapping we will see his importance later so we are simply comparing current do start whether it is less than equal to end so here you can see value of end is three current do start is two so this is the start for current it is less than end so it means that there are overlapping intervals and if you see why this example 1A 3 is actually overlapping with 2 comma 6 so this condition comes out to be true which means we have to merge this two intervals now so once you merge this two intervals let's say the result interval is C so we also saw that c do start was equal to a do start which always remains a do start because a is either starting before b or at the same time as B so here our start will remain one only it won't get changed but C do end will become the max of a do end and B do end so here this is the condition for that that we are simp simply taking the maximum value of current do end which is the current interval and value of end which is the value of its previous intervals which is three so if we do 3 comma 6 Max we get six so here you can see our start will remain the same but end will change to six now because we are merging this two overlapping intervals so end will become six moving ahead so here you can see one reason of picking start and end in a different variable is as we have merged this two intervals start became one and end became six and there could be a possibility that once we move ahead in the array there could be another intervals like this so here in this case all this interval will get merged together so therefore only the end will get expand till the intervals are overlapping and start will remain the same so therefore we have created this two variables which are doing those things these two variables are keeping the state of the previous intervals which are merged or which are yet to merge so now we'll increment I I will become two 2 is less than 3 so this condition comes out to be true now this is our current interval 7 comma 9 so when we will do intervals do get two we'll get 7 comma 9 as our current interval like this so now our task is to merge current with previous already merged intervals so we have to check whether 7 comma 9 is overlapping with any of the previous intervals or not so that value is actually hold by start and end so here if we see current do start is this value and current do end is this value so here you can see current do start is 7 and value of end is 6 so it means current do start is not less than or equal to end because value of end is six and current do start is 7 so here you can see there is a gap between these two intervals therefore they are not overlapping with each other so this condition comes out to be false so the else part will be executed and in the else part as we have already found one Gap in between this two intervals and this interval we can now safely merge this two intervals because when we go ahead these two intervals will not be get affected and we can simply merge them and add it to the result so in the result we are adding new interval start comma end so we are creating a new interval of start and end which is 1A 6 and we are adding it to result so it would look something like like this that it is merged like this and it is added to result list moving ahead so once we have merged this two intervals and there is a gap between the current and this merg interval now our task will be to focus from 7 comma 9 to rest of the elements ahead we have to forget this merging now because we have already merged this two intervals and there are no more intervals which can get merged to these two intervals so therefore we have to forget this part now and as you have started with 1 comma 3 at the start because that was the first interval now we have to start from 7A 9 thinking it is the first interval so therefore now start will become current start we will assign the value of current do start which is 7even to start and end will become current do end which will become nine so this is now our fresh interval and if there are more intervals after 7 comma 9 this 7 comma 9 will be compared with this intervals and this intervals are already merged and they are added to the result list so we don't touch them now moving ahead we will increment I so I will become three and I is not less than 3 therefore this condition comes out to be false and for Loop will terminate because there are no more elements left to be compared with this 7 comma 9 so this follow Lo will terminate and one thing to notice as soon as this follow Lo will terminate whatever the value start and end will hold that will hold an actual interval which also needs to be added to the result so here you can see 7 comma 9 was the single most interval left and there are no more intervals left which can be merged with 7 comma 9 so this 7 comma 9 also needs to be added to the result list so at the end we have to add the 7 comma 9 also to our result list because this is a non-overlapping interval so we do result do at new interval and we pass the value of start and end which is 7A 9 so it would look something like this that this is also one such non-overlapping interval and our task was to merge all the overlapping intervals and only return the non-overlapping intervals so 1A 3 and 2A 6 got merged to 1A 6 and 7A 9 didn't get merged with any of the interval so it came out as 7 comma 9 so these two are our answers 1A 6 and 7A 9 so at the end we will simply return return the list of interval which is our result list so friend this was all about the problem how to merge and overlapping intervals and return back all the non-overlapping intervals I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we actually saw the problem of merge intervals so in this video we will actually see one more problem insert interval so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so in this problem we are given with a list of non-overlapping intervals which are sorted by their start time we are also given with a interval which we need to insert into the list at a valid position in such a way that if that interval overlaps with any of the intervals which are given in the list then we have to merge all those intervals and return back a list of mutually exclusive intervals which means we need to return back a list of intervals which are different and non-overlapping so let's see an example let's say we are given with this list of intervals 1A 3 5A 7 8 comma 10 now they are non- overlapping and sorted by their start time and let's say we are given with this new interval 4 comma 9 our task is to insert this 4 comma 9 into this list in such a that if this new interval overlaps with any of the interval given in this list we have to merge it with new interval and return back a list of mutually exclusive intervals so the output is 1A 3 and 4A 10 now how this output came let's see via diagram so this is our time axis and if you plot all these intervals on this time AIS it would look something like this 1A 3 5A 7 8A 10 we have to insert 4A 9 so it will go from 4 to 9 so here you can see this 4 comma 9 doesn't overlap with 1 comma 3 so 1A 3 doesn't get affected by insertion of 4A 9 because they are not overlapping so 1A 3 will be part of our answer because it's mutually exclusive so this is the first part now here you can see when we will insert 4 comma 9 it will affect 5A 7 and also 8A 10 so s 4A 9 is completely overlapping ing 5A 7 if we put 5A 7 on top of 4A 9 that means merging of these two intervals will not get affected because 4A 9 is already overlapping completely 5A 7 but in this case 4A 9 is ending at 9 and 8 comma 10 is ending at 10 so if we put 8 comma 10 on top of 4 comma 9 the region will get expanded till 10 and as 4 is less than 8 so start part will remain the same but end will change because 4A 9 is overlapping with 8A 10 and when we merge this two intervals we take the end time of both the intervals and we see which is the maximum so here 10 is the maximum so the merge interval will be something like this it would be 4A 10 so the next output is 4A 10 now let's move ahead and see some of the concepts behind this insertion and merging let's say we are given with this two intervals we need to insert a so A and B are non- overlapping so it means we can simply insert a without touching b so we simply insert a now let's say A and B are overlapping so when we will merge this two interval their area will be from here to here so this is the start of a and this is the end of B so if we take this interval as C then we have to keep a formula as C start time will become the minimum of a do start and B do start and the end time will become the max of a do end and B do end so this condition comes into picture if they are overlapping so here you can see let's say if you give it a value as 1 4 3 6 so we know that when we will merge these two intervals the minimum of three and 1 so c will become one and maximum of 4 and six will be six we know that the area of this merging will be 1A 6 because we have to accommodate both the intervals so this formula comes handy minimum of a do start and B do start a do start is 1 B do start is three so minimum is 1 and C is end end will become Max of a do end and B do end a do end is 4 B do end is 6 so C's end will becomes six so this interval will expand from 1 to 6 so C becomes a do start which is this and B do end which is this similarly here a completely overlaps B so if we apply this formula the C will become a do start because a do start is coming before B do start and C do n will become a do n because it is coming after b.n we have to take the max value and if this is the scenario then by applying this formula C start will become B start and C's end will become A's end so this would be the area of the C interval and if B completely overlaps a and if we want to insert a so by applying this formula C start will become B start and C end will become B's end so this is how we actually insert and merge the intervals together now let's see why an example if we have this four intervals which are non- overlapping sorted by their start time and we have to insert a new interval 4 comma 9 so if we plot all these intervals on the time axis it would look something like this 1A 3 5A 7 8 comma 10 11a 12 our task is to insert 4A 9 so here as we want to insert this new interval from 4 to 9 there will be three region around this 4 comma 9 which will get affected when we will insert this new interval so one region is just before four which is this another region is this between 4 to 9 and the third region is just after 9 so here we are taking the region 1 as just before 4 not even equal to 4 and here just after 9 not even equal to 9 because if any of the interval touches this boundary like this then they also need to be merged because they are overlapping with each other and so we need to keep this condition in mind that in region one we have to Simply check for less than intervals in region three it should be greater than the end time and in this region if they overlap we have to directly merge them so how we can solve this type of problem is we have to take these three regions first we have to take all the intervals which are part of region one and all the intervals which are part of region one will satisfy this condition that their end time let's say this part is less than the new interval start time it means they are not overlapping there is a gap so this less than condition is helpful if they become equal then they actually overlap and we have to merge them so first we cater for less than condition and we figure out what are all the intervals which are not touching 4 comma 9 so those intervals we directly take into our result list because they are not touching 4 comma 9 and they are not overlapping 4 comma 9 so let's say if there are n number of intervals before four so we have to check each interval end time and check whether it is less than the new interval start time if it is less than the new interval start time we know that they belong to this region so after placing all the elements of region one we come to region two now here what we check is let's say if we take this example so here if this interval has to belong in region two what we do is we take its start time and we check whether it is less than or equal to the new intervals end time now here we are checking for this condition less than or equal to so let's say 5 is less than 9 so it means this interval belongs to region two because we have already excluded the region one intervals and if any of the intervals is left if this condition satisfies that 5 is less than 9 or equal to 9 then this region even if it expands Beyond 4 comma 9 it will still overlap with 4A 9 and why we are taking this equal condition is because let's say instead of 8A 10 we have 9A 12 so 9 is the start time and if 9 is equal to new intervals end time so still it is overlapping with this interval and we have to merge them so it still belongs to region two so this is the main condition for region one all the intervals end time should be less than new intervals start time so they will completely belong into this area and they will be non overlapping in this region they will overlap so we have to Simply check the interval start time and we have to check it is less than equal to the new intervals end time if that is the condition they still overlap and we have to merge them so here if you see 4A 9 overlaps 8A 10 because 8 is the start time and it lies before 9 because 8 is less than equal to 9 so therefore when we will insert this interval it will affect 5A 7 and 88a 10 and we know the formula that how to merge the two intervals together which we saw in our previous slide so after we add all this elements into the list whatever elements are remaining these are out of the boundaries of this 4 comma 9 which is the new interval which we want to insert so we can directly add them into the list they won't get affected by the insertion of this new interval so after merging 5A 7 with 4A 9 and 8A 10 with 4A 9 it will become something like this so our overall answer becomes 1A 3 4A 10 and 11a 12 so the algorithm is something like this we have to skip and add intervals that come before the new interval to the result list so all the intervals of region one which are coming just before the new interval we have to Simply add onto the list we have to merge all the intervals that overlap with the new interval so this interval and this interval they are overlapping with this new interval so we have to merge it with this new interval we have to add that merg interval into the result so this is the interval which gets merged we add this into the result and finally we insert the remaining intervals to the result so these are the remaining intervals there can be many intervals like this we have to just insert them to the result because they are non-overlapping and mutually exclusive so this region cover this part this region covers the overlapping part and this region covers all the remaining elements so all these regions will be captured by a simple while loop in the algorithm so let's move ahead and see the algorithm so this is the algorithm so this file Loop is for the region one where we simply skip the elements which just come before the new interval this V Loop is covering the intervals which are get getting overlapped with the new interval and this file Loop is just adding the remaining intervals so let's see the demonstration of this algorithm step by step we'll call the insert method we'll pass the list of intervals and a new interval which we want to insert which is 2A 6 so let's say you have list of interval as 0a 1 3A 5 6A 7 9A 10 and we need to insert 2A 6 so if we plot all this interval on the time axis it would look something like this 0a 1 3A 5 6A 7 9A 10 we need to insert 2A 6 which is from time 2 to 6 moving ahead so here we are just simply checking for the base cases that if list is null or empty we simply return the list so currently list is not empty and it is not equal to null so for the new interval you can think that it's a valid interval as we have to return the list of mutually exclusive intervals we will create a result list which is currently empty now as we need to Traverse each and every element of this intervals list will'll create integer I starting from zero index so first we are picking 0a 1 now in this Val we are checking that that whether 0a 1 when this 2 comma 6 will be inserted into the list of intervals will this get affected or not so first we check whether I is less than intervals do size we are simply checking whether value of I is less than interval do size which is 4 because as we are traversing each interval one by one there would be a time that I will completely Traverse all the elements so we need to break from the while loop at that moment so currently I is less than intervals. size the other condition we check is we get this interval so we do intervals. get I so we get 0a 1 and as we discuss we will check its end time with the new interval start time and we check whether this intervals end time is less than new interval start time because if it is less than new interval start time it means they are not overlapping there is a gap between so intervals. get I is this interval if if we do do end we get one we check whether one is less than new intervals do start so new interval do start is two so 1 is less than two so it means this condition comes out to be true which signifies that 0a 1 doesn't overlaps with 2A 6 and we can simply skip this element and add it to the result list because this won't get affected by insertion of this new interval so 0 comma becomes part of the result now we will increment I I will come to the index one so I is less than intervals. size which is 4 intervals. get I which is 1 which is 3A 5 now we are at 3A 5 we check whether this intervals end is less than new intervals. start so here this interval do end which is five we check whether it is less than new intervals. start which is two so this condition comes out to be false which suggest that all the intervals which were just coming before new interval have already been part of the result and once we reach on this interval this condition comes out to be false which actually states that 3A 5 will either lie in the area of new interval or Beyond but it won't lie here in the region one because this condition came out to be false so ideally this file Loop will terminate which signifies that all the intervals which were coming before new interval have been added to the result list and we can move ahead with the another while loop I is less than intervals. size now here we actually check for the second reason that whether 3A 5 is overlapping with 2A 6 or not and we already discussed how we can do that is intervals. get I which is this interval we simply check its start time which is three we check whether it is less than or equal to new intervals. end so three is less than equal to new intervals. end which is six so which is true so it means these two intervals are overlapping which is being proved by this condition and so the condition in while loop comes out to be true so first we will get this interval 3A 5 we assign it to current like this moving ahead now as we need to merge 2A 6 with 3A 5 so we know the formula that if we merge two intervals let's say A and B and let's say result interval is C so it becomes C start becomes Min of a do start B do start and C's end will become Max of a do end and B do end so here these two are the same conditions and here C is our new interval only we are simply merging 3A 5 into the new interval only so new interval start will become the minimum of current start which is this and new interval start which is two so minimum of 3A 2 will give two so new interval do start will become two which is already two so this won't get changed Now new interval end will become Max of a. end and b. end so current. end and new interval. end we take Max of it so current. end is five and new intervals end is six so if we take Max of it we get six which is assigned to new intervals. end so new intervals end doesn't get change because it is already six so it means we have merged this two intervals and the resulting interval is same 2A 6 because this new interval completely overlapped the current interval moving ahead now we are done with this this interval also so we'll increment I I reaches to 6A 7 so here I is less than intervals do size now here if you do intervals. get I we get 6A 7 so friends here you can see that why this less than equal to is important this 6 comma 7 is starting where this new interval is ending so it means they are still overlapping because because the interval start which is six is actually equal to new intervals end which is also six so therefore they are overlapping and we have to merge this two intervals as well we can't exclude 6A 7 because it is just overlapping with 2A 6 so this condition is important so the overall condition in while loop comes out to be true we do intervals. get I the interval 6 comma 7 will be assigned to current like this and we have to merge these two intervals now so we'll use the same formula the new interval do start will become the minimum of current do start which is six and new interval do start which is two so minimum will give two so new interval do start will become two which is already at two now new intervals end will become the max of current do end and new interval. end so max of current do end which is 7 and new interval do end which is six so it will give seven so here is the one critical step that new interval. end will become seven now because after merging this Two element the new interval will expand to 7 like this that we have merged this two intervals moving ahead we will increment I I becomes 9A 10 I is still less than intervals do size because value of I is this is 0 1 2 3 3 is less than 4 intervals. get I which is 3 will give 9A 10 and here you can see this 9A 10 is actually belonging to the third region so therefore it start if we compare it with new intervals. end so 9 is less than equal to new intervals Dot and which is 7 so this condition comes out to be false it means 9 comma 10 is the remaining element and it doesn't overlaps with 2A 7 so we can directly add this 9 comma 10 and all the elements after that via this while loop so this condition comes s to be false so here you can see that before adding 9A 10 into the result list we have to also insert 2A 7 which is our merged interval into the result which is actually merging 2 comma 6 which was our new interval with 3A 5 and 6 comma 7 so after this three intervals merch we get 2A 7 so this is one important step we have to add this new interval into the result so it will become like this and now using this while loop we will add the remaining interval into the result so I is still less than intervals. size and as this condition reached this while loop we are sure that all the remaining elements will be non overlapping with this new interval so we can directly add 9 comma 10 to the result we do result. add and we pass in intervals. get I which is 9A 10 so it looks something like this and then we increment I so I goes beyond the boundaries of this interval list and now this file Loop condition comes out to be false because value of I is four and interval do size is also four 4 is not less than four so this condition comes out to be false and at the end we simply return return the result which which is 0a 1 2A 7 and 9A 10 0a 1 doesn't overlap with this new interval and 9A 10 also doesn't overlap with this new interval 3A 5 and 6A 7 were merged with 2A 6 and became 2 comma 7 so this was the answer so friend this was all about the algorithm I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss about the TR data structure we will discuss about what is a try and what are its real life applications so friends what is a try so here you can see the word try actually came from the word retr so the main purpose of this data structure was to retrive the stored information very fast so basically in real life application we actually store the collection of strings inside the try and whenever we want to get that string we can retrive that string very fast below you can see the symbolic representation of a tri data structure so here you can see that green circles are nothing but the trodes and multiple trodes actually form a try and also you can see the topmost node is actually empty which is been pointed by the root so root actually points to an empty trodde and from the root the other wordss originate so here you can see let's suppose if we store this four wordss into a tri data structure then here we actually start from the root which is an empty trodde and let's say for an example as we want to store a word dog then we simply create three trotes storing one alphabet into it and the try note pointing to others in sequence so friends here you can see that from root we pointed to node D then from D we pointed to node o from o to G so friends after storing G we know that dog is in the try so we Mark the last node in yellow color stating that this is the end of the word for example if we take head then from root we point to H from H we point to a and from a we point to T now as T is the end of the word we usually mark it in the yellow color moving ahead friends if we talk about the applications of the tri data structure then here you can see the one application would be the auto complete of the words so friends you must have searched something on the Google search engine so there as soon as you type something the search engine suggest the complete word to you so this autocomplete feature is basically implemented with the help of tries moving ahead the other application would be the search contacts in phone so friend in your smartphone whenever you want to search any particular contact you just type the initi letters of the person name and the application automatically suggests the name of the persons so this application also implemented with the help of try data structure also friend one more application would be the spell checking so here you can see that many editors such as word Pages implement this spell check so here what happens whenever us types any wrong spelling the application Auto suggest the correct spelling so here you can see the spelling is wrong therefore the application is suggesting the correct spelling so that user can select from one of these option and correct the spelling so friend this was the introduction to the try and also it applications in our upcoming tutorial we will discuss more on how to implement a try the try node and other methods which try supports thanks 7 day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in our previous tutorial we actually discussed about the tri data structure and also about it usage in real life applications so in this tutorial we'll actually see how we can represent a trode in Java so friends what is a trode so friends in our previous tutorial we actually discuss that TR data structure most of the time store the collection of strings so here a trode basically represents a single alphabet of the word so here you can see if you take an example of dog so this green circle having the word as D is nothing but a trode and let's say in order to store a word dog which is three alphabet we actually need three trotes which is one for each alphabet so here you can see the topmost TR node is empty which is being referred by root and all the words which we want to insert into the try originate after that so here let's take an example of word head and let's say we want to store the head into this TR data structure so from the root we need to create three trodes storing three alphabet such as h a and t so here you can see we have created three trodes from root there is a link to H from H there is a link to a and from a there is a link to T and as T is the end of the word therefore we are marking it in the yellow color so friend let's see about the representation of a trode in try so a trode class in TR consist of two data members so here you can see a trode has two data members so the First Data member is nothing but an array of trodde which are nothing but the children of that particular trodde so here it's an array which refers to other tr notes in try and also they are called as the child notes of a particular trode so friends here you can see in the most of the applications we actually store the English words therefore the size of the array is usually taken is 26 because there are 26 six alphabets in English language so here if we take an example of this trode there here you can see that there is one link to D and there is one link to H and similarly it refers to the other letters of English alphabets and that referring is done through an array which actually refers to other trotes and let's say if we are on any particular trode and it refers to other trodes then those are nothing but the children of the trode so here the trode array is nothing but the First Data member which a trode holds so if we talk about the second data member so it is nothing but a Boolean value which signifies that a word is ended or not so here you can see in the symbolic representation of try we know that dog is a complete word so here you can see from D it goes to O and from o it goes to G now we need to pass some information to this node so that we can come to know that that this word is in the try and it is the end of the word so usually in the symbolic representation we mark this node in the yellow color stating that it is an end of the word but in Java we actually create a Boolean value so this value is set as true when a word is inserted completely so friends we will discuss more about these two properties in upcoming tutorials so that we can understand more about the representation of a trode and try so friend let's see the demonstration of a trode so friends if we take an example of hat so we can see how it gets represented into Java because here you can see the symbolic representation and here we will see the actual representation so at the top there is a root which is empty so in Java we represented something like that a trode root points to an empty trode which has an array of size 26 because we have this 26 alphabets from a to zed and when we actually initialize a try root points to an empty trodde so here you can see the default value of his word is false and also you can see the size of aray is 26 and each index points to a different trodde but here when we initialize this root they all point to null value now let's suppose you want to insert H so in order to insert H we need to create a trodde and from H we need to refer that so here it looks something like this that we have created one trodde and from H we are simply pointing to this trodde so this represent that there is a children to the root whose value is H and its default value is false because this is not the end of the word and then we actually insert a so here you can see that a points to null so then we create a trode and we simp provide a link from a to this trode stating that there is a children which points to a and finally let's say we insert T so it would look something like this that initially T was pointing to null but then we created a trode and we simply provided a value of this trode into this index so T points to this trodde and friends here you can see as this is the the end of the word we simply Mark the Boolean value to be true so friends here you can see if you're storing the English words then each trode will actually point to the other 26 trodes so that they can store a particular word so here we actually saw that root which is an empty node it points to H H points to a and a points to T and also friend all the other values of this points to null because there are no more words inserted here so here you can see that all other links points to null and also friends here you can see that this is an array so zero index points to a 1 index points to B second index points to C and similarly 25th index points to zed so how this mapping is done we'll discuss later so for now you can keep an information that a particular trode has an array which refers to other trodes and whose size is basically 26 if we are taking the English words and it also has other property which tells that whether a particular word has ended here or not so friends in our upcoming tutorial we'll actually discuss more about this trodes and how this linking is done and how this mapping is done of English alphabet to the index of an till then have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in our previous tutorial we actually discussed about the representation of a tri node in Java so in this tutorial we'll actually see how we can Implement a try in Java friends in our previous lecture we saw about the representation of a trodde in try that a trode has two data members one is the trode array which actually points to the other trodes and which are also called as child nodes of that particular trodde and we also discussed that if you're taking the English words then the size of this array is 26 because the English language contains 26 alphabets also friends the second data member is nothing but a Boolean value which indicates the end of the word so we set this value as true when we know that word is inserted completely so we will discuss about this two data members in depth in our upcoming lectures so friends let's see the implementation of the TR class so friends here try will be implemented using the trode class which we actually discussed in our previous tutorial you can also see that root trode is at the top top of the try which has empty value and it has an trode array which actually refers to other trotes so here you can see if you are working with English alphabets then there are 26 links and these links actually point to other trodes signifying that there is a letter into a try or they actually point to null so friends in the tri class we actually create an instance variable of trodde and we give it a name as root and whenever we initialize this Tri class we simply create an empty trodde and then using that root trode we actually insert the other trodes signifying that there are letters into this try moving ahead friends now here we'll discuss about the character and the index mapping that how it is done so friends as here you can see that it is an array of trode and arrays indexes so in order to store these English alphabets we usually take the values of the index and we map it to the alphabets so here into this array we are not actually storing these values we are actually using the indexes and we are figuring out the alphabets so here you can see a. to 0th index B point to 1 index C point to Second index and similarly the rest of the alphabets so how this mapping is done let's see this demonstration through a code so here you can see a care in Java is nothing but a 16bit value which starts from zero and goes till 65,536 so here we are creating a care value which points to a and let's say if you type cast it to integer value then it prints 97 so this 97 is nothing but the asky value of this character a and let's say next step from a v minus the care value a it prints zero similarly let's say we Define another value H and if we subtract the care value a from H it prints 7 because from a h is seven Step Ahead and similarly if we Define a value Zed and on the console if you print Z minus the care value a it prints 25 which signifies that Z is 25 values away from a so friends here you can see that we can actually map the character with an index value by using a formula that whatever the letter we pass and if we subtract the value a we will actually get the index value so for example if we pass a and if we minus a from it we get zero if you pass H and if you minus a we get value 7 if we pass that and if we subtract a then we'll get the value 25 so friends in try as we are referring to this array we are implicitly mapping the index value to character we are not actually storing these characters but any particular index value we are simply mapping it to a character so friend this implicit character to index mapping we will be using in our upcoming tutorials when we will actually insert a word into a try and when we actually search for a particular word in try also friends in our previous tutorial we actually saw this demonstration so let's look it one more time to make it more clear so here you can see the root p is empty and whatever the values we will be storing we will be actually storing into the children's of the root we won't be storing any value inside this root because this root is also type of trode which refers to other trodes through this array which are nothing but the child of this Roots so let's say we want to insert H so what we do is we simply Traverse the H index we see that it value is null so then we create a trodde like this and then we'll simply refer its value into this index moving ahead let's say we want to store a so as soon as we have inserted a value H and after that we have to insert a so we use this link to Traverse to this trode and then we go to a and we see see that it's pointing to null so then we create a trode and whatever value it has we simply put it into this index and similarly after a we go to T so from this TR after inserting a we simply Traverse to this trode we go to the index which maps to T and we see that it has null value so we'll simply create one trode and whatever the value this object will hold into the memory we'll simply store it into this index because here a particular trode actually refers to other trodes so here this trode is actually referring to this trode from the index whose character value is T also friend T is the end of the word which is marked here as in yellow so what we do is we simply set the Boolean value of is word to be true which signifies that we have completely inserted the word hat into this try so friend in this tutorial we actually saw the implementation of a try that it is made up of a try node now let's go to eclipse and Implement a try Hello friends in our previous tutorial we actually discussed about how to implement a try we also discussed that how a TR node is represented into a try so in this tutorial we actually Cote the basic implementation of a TR data structure so here I have created one class by name try having a main method so let's start our implementation so friends in our previous tutorial we discussed data Tri implemented by trode class so first we'll create a inner class and we'll give the name to it as trode also we discussed that a trode has two data members one is trodde array which are nothing but children of this trodde the other data member is a Boolean value which signifies that this trode is nothing but end of the word so we'll give it a name as is word we'll also provide a Constructor to this trodde and inside this Constructor we will initialize this trode array with the size is 26 because here we are storing English words so these words are from a to zed also the value of his word is by default false so we set its value to be true when this trode is actually an end of the word also friend we discussed that a try contains an instance variable type is trodde which is nothing but the root of the tri data structure so this trode which is root will point to other trode through this trode array we'll also provide it a Constructor so whenever we initialize a tri glass we simply create the instance of trode and we'll assign it to root so here root is empty so here whenever we initialize a tri class root points of the trode which is empty and after that we insert a particular word character by character which this root points so friend this is how we actually Implement a try using this TR note class also friends in our upcoming tutorial we will see that how we can insert a particular word into this try we'll also discuss that how we can search for a particular value that whether it's there in this try or not so friends in our upcoming tutorial we'll actually see how we can insert a word into this try and we'll also see that how we can search for a particular word into this try so friends I hope you like this video thanks have a nice day hello friend friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to insert a word in try so friend let's see a demonstration of how to insert a word in a try friends in our previous tutorial we discussed that whenever we initialize a TR class root points to an empty TR node because in the Constructor of the try we create a new trode and we simply assign it to the root now for example let's say we want to insert a word as cat so here you can see the word cat has three characters C A and T and as we are using the English alphabets we will initialize this trode array with a size of 26 where index0 will correspond to a index one will be corresponding to B and index 2 will be corresponding to C and similarly index 25 will correspond to zed friends we also know that each character in this word will be represented by a trode so using this root so first we will insert C from the root so here what we do we go to index 2 which maps to character C and we will see that whether TR noted index two is null or Not So currently as root is empty the Tred index 2 is null therefore in order to insert the character C first we will create a trodde and after creating this trode we will simply refer it from the index to which maps to see also friends once we insert this trode using this link We simply Traverse to this position and after reaching to this trode now we will insert a so what we do is we simply go to the index zero which maps to a and we'll see that whether it's null or Not So currently you can see that it points to null so in order to insert a we'll again create a trodde and after creating the trode we'll simply refer to this trode from index zero which maps to a also friends once you have inserted this trode using this link we will simply Traverse to this trode and then we will insert the character t so when we reach to this trode we simply Traverse to a index which maps to T and we'll see that whether it's null or not so here you can see it points to null so in order to insert T we'll first create a new trodde and then we will simply refer to this trode from the index which maps to T also friends once we insert this trode using this link we'll simply Traverse to this TR and after we reach to this trode we see that there are no more characters left to be inserted so we also know that this is the end of the word so in order to Mark cat as the end of the word what we do to this trode we simply assign the value as true so this value signifies that when you reach to this trode this makes end of the word and it also signifies that cat is in the try friend let us take one more example we'll insert a word Sun so when we call the insert method we'll start from the root and as we want to insert s we simply reach to index which maps to S and we'll see that whether it's equal to null or not so here you can see it points to null therefore in order to insert the character s we will first create a trodde and we'll simply refer to this trode through this link from the index which maps to S and after we insert this trode we simply Traverse to this trode through this link and once we reach to this link we'll now insert the character o so here we go to index which maps to O and we'll see whether it points to null or not so here you can see it points to null so in in order to insert o we'll again create a trode and we'll simply refer to this trode through this link from index which maps to O and then we'll simply Traverse to this trode and after we reach to this trode we'll now insert n so we simply Traverse to an index which maps to n and we'll see whether it's equal to null or not so here you can see it points to null therefore in order to insert n we'll again create a trode and after we create a trode we'll simply refer it through this link from index which maps to n and also friends here you can see now this word is inserted completely so using this link when we reach to this trode we'll now simply mark this bullan value to be true which signifies that this is the end of the word moving ahead now friends let's suppose you want to insert a word so so here you can see we have already inserted sun and the word so is prefix to Sun so let's see how we'll insert so into this try so we'll start from the root we go to index which maps to S and we'll see whether it points to null or not so here you can see this time it's not pointing to null and it is pointing to a trode which signifies that there is a character s into this try so we will not create a new trode and we'll simply Traverse to this trodde and then we'll insert o so here we'll reach to index which maps to O and we'll see that whether it points to null or not so here you can see that this index doesn't point to null and it points to a trode which signifies that there is a character o into this try so what we'll do we simply Traverse to this trode now using this link and once we reach to this trode we see there are no more characters left to be inserted so in order to mark this word so that it is present into this try what we'll do we'll simply assign a value true which will signify that this is the end of the word and the word so is present into this try so friends this bullan value is very important which let us know that whether the particular word is present into this try or not also friends if you see the symbolic representation of this try then it looks something like this that root is empty and from root there are three words c a t t is the end of the word and Sun s o n where n is the end of the word and also so where o is the end of the word so basically this try has three words moving ahead friends whenever we insert into a try there are few use cases which we will look one by one so the first use case is let's say we have an empty try and now we are inserting a completely new word so when we say an empty try it means root is pointing to an empty trodde and let's say we insert a word as cat so from root we will first insert C so it would look something like this then we'll Traverse to C and now we'll insert a so it would look something like this and then we'll Traverse to a and finally we'll insert T so it looks something like this and then we will Traverse to T and we know that now we have inserted this word completely therefore we will Mark T as the end of the word by making it in yellow color so this was the use case one now friend the Second Use case is when we want to insert a word into this try and this try contain already many words but the word which you want to insert has no prefix to this word so the new word which we are inserting is completely allog together new to all the words inside this try so here let's suppose you want to insert Sun so here you can see that sun doesn't have any prefix to cat so this is an all together completely new word into this existing try so we'll see how we can insert Sun into this try so we'll start from the root and first we will insert s so it would look something like this that there is now another branch which takes in a word s from the root because friends we also discussed that root has a trode array which points to all the English alphabets so in this trode array from the index which maps to see there is a word and from the index s we will start inserting our new word so after we insert s we'll simply Traverse to S and then we will insert U so it would look something like this and after we insert U we simply Travers to u to insert n so it would look something like this and once we insert n we'll simply Traverse to this node and here we also know that we inserted this word completely therefore will mark this node as the end of the word by making it in yellow color friend use case 3 is insertion with word which is having a common prefix so here you can see in our try there is already one word there and let's say we want to insert a word there so here you can see both these words have common prefix so the letters t h e is also present here t h e so these three letters are common to this both words so let's see how we can insert there into this try so here we will start from the root and we'll see that whether T is present or not so here you can see T is already present so we simply Traverse to T and once we reach to T we see whether H is present or not so H is already present so we'll simply Traverse to H after that we'll see that whether e is present or not so here e is present so we'll simply Traverse to E and now we'll see that whether I is present or not so here you can see I is not present so here from E there will be another Branch coming out we'll create a new trode I and we'll simply link to this new trode from E so it would look something like this that from me there is a link to a character I and once we insert I we'll simply Traverse to I and we finally insert R so we'll check whether R is present or not so here you can see R is not present so we'll create a new trode and we'll insert R and finally we see here that it is an end of the word so we'll simply Mark R as the end of the word also friends one final use case would be that insertion with word already present into the try so here let's suppose our try consist of a word daddy so it has five notes which points to d a d d y and let's suppose we want to insert a word Dad so we know that Dad is already present into this try but we need to perform some work to make sure the dad is inserted into this try so what we do is we start from the root we see whether D is present or not so D is present so we'll simply Traverse to D we check whether a is present or not so a is present so we'll simply Traverse to a we check whether D is present or not so D is present so we'll simply Traverse to D and as we know that we have inserted this word completely so one last thing we do is we simply Mark D as the end of the word by making the Boolean value is word to be true so friends in this tutorial we actually saw the demonstration of how we can insert a word into a try through all the possible use cases in our next tutorial we'll actually see the codee to insert a word into a try I hope you like this video thanks have a nice day Hello friends welcome to my new data structures and algorithms in Java tutorial series video friends in this tutorial we will discuss how to insert a word in try friends in our previous tutorial we actually saw a demo of how to insert a word in Try by seeing the different use cases so friend in this tutorial we'll actually see the working of this algorithm step by step so friend below you can see the code to insert a word into a try so let's see it demonstration step by step so friends whenever we initialize a try we know that root points to a empty trodde because in the Constructor we simply create a new trode and we'll simply assign it to root so root will point to an empty trode now let's say we want to insert a word cat so here string word will point to cat so here we are simply seeing the string word in the form of character array where C is has index zero a at 1 and T at 2 so we'll see how we can insert cat into this try character by character also friends in our previous tutorials we discussed that we always start from the root when we are inserting any new word so in the step one what we'll do we'll simply create a temporary node current and whatever the node root points will simply assign it to current so it would look something like this that current points to a node which root refers moving ahead friends now we will provide a for Loop because we need to iterate each and every character of this word and we have to insert into this try so we'll start from the zeroth index and we'll iterate this for Loop till index 2 so the condition we place in the for Loop is I should be less than word do length so here word do length will be nothing but three so as we are starting from zero we need to Traverse till two moving ahead so on the for Loop what we'll do we'll first take the character at index zero so we'll simply call the car method of the string and we will take the character at index zero because currently the value of I is zero so the KC will point to character C also friends in our previous tutorial we discussed that how we are mapping this index with the actual character and we saw that if you subtracting a from any particular character we'll get the index value so here the value stored in C is C and when we'll subtract a from it we get the index value so here index becomes two so in the trode array index two maps to character C so using this current trode we'll see in the children array which is nothing but the array of P note and we'll see the value of index 2 we'll check whether value of index 2 is null or not so here you can see currently value with index 2 which maps to C is null therefore the condition in if block comes out to be true which means that c is not present into this try and now we'll insert C into this try so the first step we do is we simply create a new trde and we'll simply assign it to a temporary trode also friend as we have created this new trode we have to link the trod at index 2 which maps to C to this trode so what we do is we simply assign a value of node to current. children at index 2 which maps to C so it would look something like this that now there is a link established from root to this trodde from the index two which maps to C moving ahead and also friends in our previous tutorial we also discussed that as soon as we insert a trode we simply Traverse to that particular node so here we'll simply assign the value of node to current so now current will point to this trodde moving ahead so after incrementing value of I I becomes 1 so the character at index one is a so value of C becomes a we will evaluate the value of index by subtracting a from the value stored in car c which is nothing but a so when we'll do a minus a we get the value as zero which makes sense because index Z will map to a character a moving ahead now as current is pointing to this trode we will check into its children array that at index zero whether it value is null or Not So currently you can see the value at trode which is at index zero points to null therefore condition in blog comes out to be true so in order to insert a a we'll first create a new trodde and we'll simply assign it to a temporary node and in order to insert this trodde in try what we'll do we'll simply assign the value of node which is this TR node to current do children at index zero so here it would look something like this that now there would be a link from index zero to this trodde then we'll simply Traverse to this trodde by assigning value of node to current so now current will point to this trode moving ahead now after incrementing value of I by 1 it becomes two so now we will insert the value at index2 which is T into this try so value of KC will become from T then we will evaluate the index of the character T so we'll simply subtract a from T so it will give index value as 19 so in the F blog we'll again check that value at index 19 is equal to null or not so here you can see the value at index 19 of this trode array which maps to T is is null therefore condition in ifog comes out to be true now in order to insert T we'll first create a new trodde and we'll simply assign it to a temporary node moving ahead and now we'll assign the value of node to this trode array at index 19 which maps to T so it would look something like this the TR noted index 19 will now point to it newly created trodde and finally we'll simply Traverse current to this newly created trode by assigning the value of node to current so it would look something like this that current will now point to this newly created trode now after incrementing the value of I by 1 I becomes 3 so the condition in for Loop comes out to be false because 3 is not less than three so here we simply take an exit from this for Loop and also friends in our previous tutorial we discussed that the last step we do is we simply Mark the Boolean value is word to be true stating that this is the end of the word so we'll simply assign the value true to current do is word so it becomes true moving ahead now friend let's suppose we want to insert a string Sun so we'll again call the insert method by passing in word as Sun so it would look something like this so as we are inserting a new word we'll start from the root so we'll create a temporary note current which will start from the root and then we'll simply iterate each and every character of this word using this for Loop so in the first step we'll insert s so c will have value as s we will evaluate its index position by subtracting a from s so index will become 18 then we'll provide if block and we'll check that into this trode array at index 18 what's the value whether it's point to null or not so here you can see currently it is pointing to null so the condition in IFL comes out to be true so in order to insert s we'll first create a new trodde and we'll assign it to a temporary trodde and as we are inserting this new trode into the try we'll simply assign the value of node to this trodde array at index 18 which maps to S so it would look something like this that the trode at index 18 which maps to S now points to this newly created trode moving ahead so after this assignment we simply Traverse current to this newly created trodde by assigning the value of node to current current so it would look something like this that current will now point to this newly created trode so after incrementing the value of I by 1 I becomes one so now we'll insert O So value of KC will become o we will evaluate index position by subtracting a from o so it would give index as 14 now as current is pointing to this node so we will check that value of trode array at index 14 which maps to O whether it's null or Not So currently you can see this value is pointing to null therefore the condition in ifog comes out to be true now in order to insert o into this try first we'll create a new TR node and we'll assign it to a temporary trodde and as you want to insert this new trode into try we'll simply assign the value of node to this trodde array at index 14 which maps to O So it would look something like this moving ahead head then we'll simply Traverse current to this newly created trodde by assigning the value of node to current now after incrementing I by 1 I becomes 2 so now we'll insert the value n so the value of KC will become n we will evaluate its index by subtracting a from n so it would give index is 13 so in the F block we'll simply check that value of this children array at index 13 which maps to n is null or Not So currently you can see this value points to null so the condition in IFL comes out to be true so in order to insert n into this try we'll first create a new TR node and we'll assign it to a temporary node and then we'll simply assign this newly created node to the index 13 of this trode array which maps to n so it would look something like this and then we'll simply move current to this newly created trode by assigning the value of node to current so it would look something like this so after incrementing the value of I I becomes three so the condition in for Loop comes out to be false and then we will exit from this for Loop so friend as you inserted the word Sun completely into this try the last step we do is we simply assign the value true to current do is word stating that this is the end of the word so it becomes true now friend let's suppose you want to insert a word cab so here you can see that we have already inserted word cat and cab has a prefix C A which maps to C A of cat so we'll see how we can insert cab into this track so we'll call the insert method by passing in word as cab so word will have the value as cab we'll start from the root by creating a temporary trode by name current and we'll assign a value of root to it so it would look something like this and then we'll provide a for Loop which will iterate over each and every element of the word so we'll start from C we'll evaluate his index position by subtracting a from C so index become two so into this children array and we will see that whether value at index 2 which maps to C is equal to null or not so here you can see the value is not null because it is pointing to a trodde therefore the condition in if blog comes out to be false which tells us that c is already there into this try so the lse part will be executed so in the L spot will simply Traverse current to a trode which this trode array holds at index 2 which maps to C so it would look something like this moving ahead now after incrementing I by 1 I becomes one so now we will insert a we will evaluate an index position by subtracting a from a which gives index as zero then in the F blog we will check that what's the value of children array at index 0o so here you can see that it is not equal to null and it is pointing to a trode therefore the condition in if block comes out to be false and the lse block will be executed and in the L block whatever the value this trodde array at index Z is referring will simply Traverse current to that trodde so it would look something like this that current will now point to this trodde now after incrementing I by 1 I becomes two so now we will insert B then we will evaluate index position of B by simply subtracting a from B so it would give index as one and now we'll provide an if loog and we'll check the value of this trode array at index one which maps to B that whether it's null or not so here you can see that it is pointing to null so the condition in if block comes out to be true now in order to insert B we'll first create a new trodde and we'll assign its value to node and then as we have to insert this trodde into the try we'll simply assign the value of node to this trodde array at index one which maps to B so it would look something like this and then we'll simply Traverse current to this newly created trodde so after incrementing I by 1 I becomes 3 so the condition in for Loop comes out to be false because 3 is not less than three so this for Loop will exit and in the last step we'll simply assign the value of true to current do is word which states that this is the end of the word moving ahead so friend now let's cover the last use Case by inserting a value so so here you can see we have already inserted a word sun and the new word which we are inserting is so so so is already there into this try but we need to provide some additional info to this try so that it can come to know that so is actually a word so we'll simply call insert method Again by providing a word as so we will start from the rout by creating a temporary trodde by name current we'll provide a for Loop which will iterate over each and every value of this word so first we'll insert s we'll first evaluate the index position by subtracting a from s so index become 18 now we'll provide an if block and we'll check the value of this trodde array at index 18 which maps to C so here you can see that value is not equal to null so the condition in if block comes thought to be false so the lse block will be executed and in the lse block whatever the node this children array at index 18 is pointing will simply Traverse current to that node so it would look something like this moving ahead after incrementing the value of I by 1 it becomes 1 so now we'll insert o we will evaluate index of O by subtracting a from O So index is 14 now we'll again provide an if blog and we'll check the value in this trode array at index 14 so here you can see the value is not pointing to null it is pointing to a trode therefore the condition in if BL comes out to be false and the L's block will be executed so in the L's block whatever the value this trodde array at index 14 is pointing will simply Traverse current to that trodde so it would look something like this now after incrementing I by 1 I becomes two so the condition in for Loop comes out to be false because 2 is not less than two so the for Loop exits and here is the most important part that as current is pointing to this trode and we have inserted this word completely into this try we will Mark the a word property of this TR node to be true stating that this is the end of the word so by assigning the value true to this TR Noe we are telling try that the word so is in the try so at the later point of time whenever we perform a search over in this try this Boolean value will help us return a value true or false that whether a particular word is present into a try or not which we will be seeing in our upcoming tutorials so friends in this tutorial we actually saw the demonstration of how to insert a word into a try step by step now let's go to eclipse and see the working of this code Hello friends in our previous tutorial we actually discussed how to insert a word in a try and we saw the demonstration of the algorithm step by step and also in our previous tutorial we created one class by name try and we implemented try with the help of TR note class so in this tutorial we'll actually code a method which will insert a word into a try so here I already created one method as insert which takes in a word and whose return type is void so we need to insert this word into the try so let's write the code for it so in the first step we simply check that whether word is equal to null or not and also we'll check that word is empty or not because if word is equal to null or empty then we'll simply throw illegal argument exception saying invalid input so friend these are the basic age cases and also friends in our previous tutorial we discussed that we will be storing the English words into the try so we have taken the size of this triod AR to be 26 so here we will be dealing with lowercase letters so we'll convert the word to lower case and also friends before calling insert method we actually initialize this TR class so root points to an empty trodde so whenever we insert any word we basically start from the root so we'll create a temporary trodde and we'll assign a value of root to it now we'll provide a for Loop which will iterate over this word character by character so we'll start this traversing from zero to a value less than word. length and inside this for Loop we will insert this word character by character so we'll first fetch the character R the value I by calling the carat method of the string after getting the character value we will evaluate its index position by subtracting k a from the value which C holds so this will give us back the index position of this trode array that where we want to insert this particular character so after getting the index position we'll provide an if block and inside this Z block we'll provide a condition the trode array to a trode which current points and at its index value which we just evaluated we'll check whether it's equal to null or not so so if this value is null therefore we know that this character is not inserted into try so in order to insert this character into try we'll first create a new TR node and we will assign its value to a temporary node and after creating this new trode we will assign its value to the trode array at the index which we just calculated and after inserting this trodde into a try we'll simply Traverse current to this newly created trode by assigning the value of node to current also friend if the the value is not equal to null then we'll simply provide an else block and in this lse block we'll simply Traverse current to a value this trode array holds at the index so friends after inserting this word character by character after the for Loop we'll simply assign the value of is word to be true stating that this is the end of the word so friend this is the code to insert a word into a try so in order to call this insert method in the main method we'll first create the instance of try so when we will create the instance of try into the tri Constructor the root will be initialized to an empty trodde and then we'll simply call the insert method by passing in few values say cat cab sun and so so these are the values which we actually discussed in our previous tutorial so at last I will simply print values inserted successfully if I run this code now youed printed values inserted successfully also friends in our upcoming tutorials when we'll actually perform the search we can actually test the working of this insert method that whether these words are inserted properly or not so friend in this tutorial we actually discussed how to insert a word into a try I hope you like this video thanks have a nice day hello everyone so in this section of course we will be discussing about dynamic programming and we'll see that how we can solve the problems related to dynamic programming so in this lecture we'll simply see that what is dynamic programming with a simple introduction so friends what is dynamic programming so if you visited the website Kora there was a question asked on how you can explain what is dynamic programming in a simple Manner and to that question a guy named Jonathan Paulson gave an amazing reply so what analogy is demonstrated so let's say we write something this on a sheet of paper and we ask that what's that equal to so your answer would be you will simply count each one as 1 + 1 2 2 + 1 3 3 + 1 4 4 + 1 5 6 7 8 so you simply reply 8 now let's say if we write 1+ to the left of it and we ask what about that so you will be quickly replying nine so initially it took some time to just add all those numbers but when we simply added plus one to the left of it you straight away replied nine so how would you know it was nine so fast so our basic answer would be that we simply added one more and we didn't need to recount everything again because we remembered this result which is equal to 8 and we simply added + one which became 9 so friends here you can see the dynamic programming is just a fancy way to say remembering stuff to save time later so here what we do is let's say we calculated these values and when we added plus one we didn't need to count everything again and we knew that all these values were added to eight and we simply added plus one and we gave the answer as nine and let's say if we do 2 plus to it then we wouldn't have counted everything again we would have straight away replied 11 because 9 + 2 gave us 11 so friends your dynamic programming also works the same let's say when we solve any small problem so what we do is we simply store that result and when we encounter that same problem again we we simply take that stored result instead of recalculating the values in the problem so friend this is our dynamic programming Works let's say we are given a problem to solve so what we do is we simply break that problem into smaller problems we solve those problems and we store the result of those problems so while building up the solution to the large problem if that smaller problem comes again we don't recalculate it we simply use the value which we already computed so what it does is it simply saves our time and the problem takes less time to compute what the exact value is so friends when we discuss dynamic programming in the world of algorithms it is basically a technique in which a complex problem is solved by first breaking it into smaller sub problems second solving those sub problems and simply storing their results and third reuse those store results if sub problem occurs or overlaps again so what it means that we are simply avoiding solving that sub problem again and finally using solutions to smaller sub problems to build up the solution for the complex problem so friend as we saw an example in our previous slide that when we counted all the ones we came to know that they are equal to 8 so what we did was we simply remembered that all these ones were equal to 8 and when we added plus one we straight away came to an answer that now it's equal to 9 so here also we break the problem into smaller sub problems and we simply store their results so that when those sub problems come again we simply use that stored results so that our time is saved and we are not recomputing those values and finally using these steps we build a solution to the complex problem so friend if we use dynamic programming then we can solve a complex problem very fast by simply breaking down into smaller sub problems remembering the result of those sub problems and while building up the solution to comp complex problem if those sub problems are coming again then we simply use those stored values instead of recalculating those sub problems again and finally coming to a solution for the complex problem so friend this is how we use the dynamic programming as a tool to optimize an algorithm so friends in our next lecture we'll take a problem we will solve it without dynamic programming we'll see the problem associated with it and then we'll introduce dynamic programming and we'll see that how fast it makes the algorithm hope you like the lecture thanks have a nice day hello everyone so friends in our previous lecture we discussed about what is dynamic programming so in this lecture we will discuss more about dynamic programming and its relationship with recursion we will see how recursion and dynamic programming go handin hand so here if you see we mostly use dynamic programming to provide an optimization over recursion so here let's say we use recursion to solve any problem so usually it happens that when we solve a recursive problem we tend to make the code inefficient which means using recursion we can solve the problem but what it happens is the problem is solved but it tends to take more time so in our previous lecture we discussed that how dynamic programming usually help us to solve a complex Problem by breaking it down into smaller sub problems and then solving those sub problems and while solving those sub problems what we do is we simply store the result of those sub problems and whenever that sub problem comes again into picture we usually extract the stored result and we reuse rather than Computing it again and again so similarly when we solve any recursive problem what we do is we simply break it down to smaller sub problems and we solve those sub problems and we store those results so whenever that sub problem comes back into picture we usually use the showed result of that sub problem and we avoid recalculating the solution to that sub problem so by doing that a recursive problem gets optimized so if we see the basic definition of dynamic programming is basically taking recursion plus memorization so here we tend to solve a problem recursively and when we solve the sub problem we usually memorize those Solutions and later point of time if that sub problem comes again back into picture we use the memorization solution rather than again calculating those sub problems so friends in order to explain what is the problem with using recursion directly and what's the advantage of bringing in dynamic programming with recursive Solutions we'll see an example so we'll take the example of fibon series so what is Fibonacci series so as per the definition it is a series of numbers in which first two numbers are 0 and 1 after that each coming number is the sum of the two preceding numbers so if you go by this definition then this is the formula which comes out so here first two numbers are 0 and 1 so here you can see the Fibonacci of 0 is 0 and fibon of one is 1 which means that first two numbers are zero and one after that each coming number is sum of the two preceding numbers so let's say I want to calculate the net Fibonacci number so in order to calculate the N at Fibonacci number what I can do is I can simply do the sum of the N minus 1 at Fibonacci number and N minus 2th Fibonacci number so which means that we are simply doing the sum of the two preceding numbers and getting the current number so here you can see this is the Fibonacci series of first few numbers where the first two numbers are zero and one which is this so let's say we want to calculate what's the Fibonacci number two so the Fibonacci number two is the fibon number 1 plus the fibon number 0o so here you can see the Fibonacci number one is 1 and Fibonacci number 0 is 0 so we do 0 + 1 we get the number one if you want to calculate Fibonacci number three we simply take the two preceding numbers which is 1 and 1 so when we do 1 + 1 we get two and similarly 1 + 2 will give 3 2 + 3 will give 5 3 + 5 will give 8 5 + 8 will give 13 and 8 + 13 will give 21 so this is how the series goes if you want to calculate any Fibonacci number we simply take the preceding two numbers we do the sum of it and we get the number so this is the basic formula to calculate the Fibonacci number so friends in know next lecture we'll take this example of Fibonacci series and we'll see that how plane recursion in calculating the Fibonacci number is less optimized and then we'll see that how we can bring dynamic programming more optimized I hope you like this video thanks have a nice day hello everyone so friends in our previous lecture we discussed that how recursion and dynamic programming go hand in hand and we also discussed the dynamic programming provides an optimization to recursion problems and we also discussed about the Fibonacci series and we saw that fibon series is nothing but a series where first two numbers are zero and one and after that each number is the sum of two preceding numbers and we saw that we can calculate the Fibonacci number using this formula so in this lecture we'll take the example of fibon Naki series and we'll see that how recursion is less optimized when solving the problem of the fibon number and then we'll see that how we can use dynamic programming to make this recursion problem highly optimized so friends in order to calculate the N Fibonacci number this is the basic algorithm which uses the recursion so here you can see that we are using this formula to calculate the n fibon number so you can see that when value of n is zero we are simply returning zero when the value of n is 1 we are returning one and in order to calculate the N Fibonacci number we are recursively calling this fif function with the value of n minus1 and n minus 2 and we are simply doing the sum of it to get the value of n fibon II number so here you can see that we are calling this method recursively by passing n minus one and whatever is return from it we are storing in a integer variable left and then we are calling recursively the fif function with a value n minus 2 and we are simply storing it in the integer value right and finally we are doing the sum of it because we know that we need need to do the sum of the two preceding numbers so which is these two numbers we are doing left plus right and we are simply returning the result so this is the plain recursion without using any dynamic programming so we'll see step by step how this algorithm goes so let's say we want to calculate the fifth Fibonacci number so then you can see that the fifth function will be called where n will be equal to 5 so we have called FIB of five then we move ahead n is equal to 5 therefore the condition if blog comes out to be false we move ahead n is not equal to 1 therefore the condition if BL comes out to be false so we move ahead and here you can see now we are again calling the fifth function with the value as n minus one which is nothing but 5 - 1 4 and we are going to call this fif function recursively so it would look something like this that the fif function will be called again with a value of NS 4 like this and then we'll move ahead and is not equal to zero so we move ahead n is not equal to 1 so we simply move ahead and then we again call the fifth function with the value is n minus 1 which is 4 - 1 so it would look something like this the fifth function will be called with a value as three like this we move ahead the condition in if blog comes out to be false because n is not equal to zero similarly n is not equal to 1 so we move ahead and here we again call the fifth function with the value as 3 - 1 which is 2 so it would look something like this the fifth function will be called with the value as two n is not equal to zero so we simply move ahead n is not equal to 1 so we move ahead now we are again calling the fifth function recursively with a value as 2 - 1 which is 1 so it would look something like this the fifth function will be called again with the value as one like this so n is not equal to zero so we simply move ahead but now you can see that n is equal to 1 which is this so we have encountered a base case where we want to return one now so here FIB of one is actually one so one will be return returned from this FIB of one to FIB of two so it would look something like this and as we have left the FIB of two at this point we'll start executing from this point where now left will get the value as one because we have returned one and now we'll move ahead so here you can see that n is 2 and when we do n minus 2 and call the fifth function again so it would look something like this that it will call FIB of zero so it would look something like this now n is equal to Z so now we'll simply return zero from here so it would look something like this that zero will be return to FIB of Two And as we have left FIB of two here we are again coming back to this point and finally we'll return left plus right which is 1 + 0 which comes out to be 1 so from FIB of two we'll simply return one and as we have left FIB of three at this point we'll start executing now from this point here n is three we'll again call the FIB of 3 - 2 which is 1 so now FIB of 1 will be called again it would look something like this n is not equal to Zer n is equal to 1 so we'll return one from here and as we have left FIB of three from this line we'll start executing from this line and we'll simply return left plus right which is 1 + 1 so from FIB of three we are simply returning two to FIB of 4 so we know that we had left FIB of four at this point so we'll start executing from this line and then we'll call again this fif function recursively with the value as 4 - 2 which is 2 so now fifth function will be called with the value as two so it would look something like this so n is not equal to zero so we'll simply move ahead n is not equal to 1 so we'll simply move ahead and then from FIB of two we are again calling the FIB function recursively because in order to calculate the FIB of two we need to do the sum of two preceding numbers which is fib of one and Fib of0 so first we are calling the FIB of 1 because 2 - 1 is 1 so it would look something like this the FIB will be called with the n as one and it would look something like this so we will now again calculate FIB of fun we know that n is not equal to zero so we'll simply move ahead and here we know that n is equal to 1 because we are calculating FIB of one so the condition in ifog comes out to be true and we are simply returning one so one will be return to FIB of two and we had left FIB of two from the left side so one will be stored in left and then we'll simply move ahead and then we'll go to its right by calling FIB of n minus 2 so FIB of 2 - 2 is 0 so we'll simply call FIB of 0 again so it would look something like this that now we are going to its right right so here we know that n is equal to 0 so we'll simply return 0o from its right so we'll go back to FIB of Two And as we are returning it from the right we start our execution from this point where n is equal to 2 now so finally we'll simply return return left plus right which is 1 + 0 so F of two will be returning 1 to FIB 4 from its right so as we are returning it from the right we'll start executing from this point that we had left FIB of four from the right side so right will be having the value as one which we have returned it from FIB of two and finally we'll return left plus right which is 2 + 1 from the FIB of four which is three so this three will return to FIB of 5 which we had left from the left side so we'll start our execution from this point where n is five now and now we'll go to its right right by again calling FIB of n minus 2 which is 5 - 2 which is 3 so F of three will be called again n is not equal to 0 n is not equal to 1 now we'll go to its left because in order to calculate FIB of three we need to to calculate FIB of 2 and FIB of 1 so we'll call FIB of n minus 1 which is 3 - 1 2 so it would look something like this n is not equal to z n is not equal to 1 and in order to calculate FIB of two we'll first call FIB again recursively by passing 2 minus 1 which is one so it would look something like this n is not equal to Z now here n is equal to 1 so we'll simply return one from FIB of 1 to FIB of two like this and as we have left FIB of two from its left we'll start our execution from this point and we'll simply store one to the left because this is what is WR from FIB of n minus one and now we'll simply go to its right by calling FIB of n minus 2 which is 2 - 2 which is Fib of0 so it would look something like this that F of zero will be called again and here n is equal to 0 so we'll simply return 0 so as we are returning it from the right side we'll start our execution from this point because zero will be stored in right and finally from FIB of two we simply return left plus right which is 1 + 0 so 1 will be return from fave of Two And as we have left fave of three from its left we'll start our execution from this point and one will be stored in the left then we'll go to its right again by calling FIB of n minus 2 which is 3 - 2 which is 1 so FIB of 1 will be called called again n is not equal to zero n is equal to 1 so we'll simply return 1 so one will be returned to FIB of three and as we are returning it from the right we'll start our execution from this point where one will be stored in right and finally from the FIB of three will return left plus right which is 1 + 1 which is equal to 2 so two will be return return from the FIB of three to FIB of five and as we have left FIB of five from its right we'll start our execution from the right where two will be stored in right and finally we'll simply return left plus right from the FIB of five which is 3 + 2 which equals to 5 so friends the fifth fibon number has a value of five which you have returned finally from FIB of five so friends here you can see that we use plain recursion to calculate the fifth fibon number so this solves our problem but here you can see that it is very less efficient code as you can see that we are calculating FIB of five FIB of four FIB of 3 FIB of two FIB of 1 and FIB of zero but here you can see the boxes in blue color are recalculated again so for example here you can see that FIB of 3 we calculated the value as two and here we again calculated the value of Fibonacci 3s2 so we went inside again this tree which you see here and similarly you can see that FIB of two we calculated here then we calculated here and then we calculated here and similarly FIB of one we calculated here here here and here and same as Fibonacci zero we calculated it here here here so here you can see the boxes in green were the actual calculation which we wanted to calculate but as we were using this recursion we need to again recalculate everything here again in the blue boxes so this makes this algorithm very less efficient so what dynamic programming says is when we were Computing Fibonacci of 3 Fibonacci 2 1 Z what if we stored those values somewhere and later point of time when we wanted to recalculate Fibonacci 3 2 1 0 we could have used those values directly without going into again recalculating those values so as per the dynamic programming definition a complex problem is solved by making into smaller sub problems we store those sub problems result somewhere and when we get those problems again like here here here here instead of recalculating those thing again and again we can simply use the stored result and we can solve this problems very fast so here you can see the dynamic programming basically provides an optimization to the recursion and as we saw in the definition that it is basically an optimization over recursion plus dynamic programming is nothing but recursion plus memorization so here we use recursion but somewhere we memorize the solutions and we store it somewhere so that when those sub problems comes again into picture we usually use the stored Solutions rather than recalculating them again and again so using this technique dynamic programming provides an optimization over recursion so friend in this lecture we saw that how plain recursion can be a problem in solving a complex problem so friends in the upcoming lecture we'll see the demonstration of how we can use dynamic programming to use recursion with memorization and we'll see that how we can solve the problem such as Fibonacci series very fast I hope you like this video thanks have nice day hello everyone so friends in our previous lecture we saw an example to calculate the N fibon number and we saw that how we can solve the problem using recursion and we also saw that when we use recursion in calculating the nth foni number the problem was solved but the solution was very less efficient so friends in this lecture we'll discuss that how we can identify that a particular problem comes under dynamic programming so usually dynamic programming problem has few characteristics so one of the characteristic is optimal substructure so what do we mean by Optimal substructure so here you can see that a given problem has optimal substructure property if optimal solution of the given problem can be obtained by using the optimal solution of its sub problems so which means we are given a complex problem and we want to solve that problem and if that problem can be solved by breaking it down into smaller sub problems and using the solution of those sub problems and obtaining the solution to the complex problem gives the problem a property known as optimal substructure so in our previous lecture we saw that how we can calculate the N Fibonacci number and we also saw that how we can solve the problem of n fibon number by using the formula is if you want to calculate the N fibon number you need to find the sum of its preceding fibon numbers which is fib of n minus one and FIB of n minus 2 so here you can see the complex problem has been broken down into smaller sub problems which again gets broken down into more smaller sub problems which we saw in our last lecture therefore as an example we can say that if you want to calculate the N fibon number we can calculate by breaking it down into smaller sub problems thus this problem has optimal substructure so in our last lecture we saw that in order to calculate the N Fibonacci number we can use the recursion and we can solve this problem so while using recursion we saw that if you want to calculate let's say the fifth fibon number so here in order to calculate the fifth Fibonacci number we break this problem into two sub Problems by first calculating the fourth foni number and the third fibon number so we further broke this problem into sub problems and similarly it goes on like this so finally when we reach to a point that a problem cannot be divided further so we usually encounter the base cases which is n is equal to 0 and N is equal to 1 and then using the result of those Bas cases we solve the sub problems then we use the solution to solve the bigger sub problem and doing this we finally solve our main problem so here you can see that this complex problem has a property of optimal substructure where a complex problem can be solved by breaking it out into smaller sub problems and using its solutions to solve the main problem so this one property optimal substructure has helps us to identify that whether a problem can be a dynamic programming problem or not so friends in our next lecture we'll see that there is one more property combined with this property makes a problem a dynamic programming problem so we'll discuss that property in our next lecture I hope you like this video thanks have a nice day hello everyone so friends in our previous lecture we discussed that how to identify a particular problem that whether it is a dynamic programming problem or not we saw that dynamic programming has few characteristic so one of the characteristic which we discussed in our last lecture was optimal substructure so in this lecture we will see that there is one more characteristic which basically help us to identify that whether whether a particular problem is a dynamic programming problem or not so here the other characteristic is overlapping sub problems so what is overlapping sub problems so friend let's suppose we are given a problem and we want to identify that whether the given problem has overlapping sub problems property or not so we can simply identify the overlapping sub problems property by first taking the problem and breaking it down into smaller sub problems and solving those sub problems to get the solution of main problems now what this overlapping sub problems means so let's say if our solution of a given problem is obtained by solving the same sub problems multiple times so friends few lectures back we saw that when we solved the N fibon number problem using recursion there we saw that in order to solve the N fibon number we first broke it down into smaller sub problems using recursion and when we were building up the solution back by solving the smaller sub problems we saw that those smaller sub problems were encountered multiple times so here the example of calculating the an Fibonacci number has few sub problems which are overlapping to each other so here you can see that in one of our previous lecture we calculated the N fibon number using recursion and here you can see that in order to solve the fifth faki number we broke it down into smaller sub problems something like this by using these properties that n Fibonacci number is equal to n minus 1th Fibonacci number plus n minus 2th fibon number which is nothing but taking the sum of previous two Fibonacci numbers so friends here you can see that when we solve this problem so in this diagram you can see the boxes which are in blue color are basically the smaller sub problems which have occurred multiple times so for example you can see that when we want to calculate the third Fibonacci number we calculated second Fibonacci number first fibon number and again to get the value of second fibon number we broke it down into smaller sub Problems by calculating the FIB of one and FIB of zero if we see the tree of FIB of three this much you can see that we have recalculated this tree here again and also if you see the tree of FIB of two which is this much portion we have recalculated it here and here and similarly FIB of one we have recalculated it here here and here and same goes with FIB of zero we have calculated it here here here so friends here you can see that when we solve this problem by breaking it down into smaller sub problems wec counted that this problem has multiple overlapping sub problems here this same problem overlapped with this this sub problem overlapped with this this and this thus the problem to calculate the N Fibonacci number has overlapping sub problems and also friends you can see that it also has optimal substructure where we are breaking it down into smaller sub problems and solving those sub problems to get the solution to the main problem so friend the problem is considered to be a dynamic programming problem when it follows the two properties the optimal substructure which we discussed in our last lecture and overlapping sub problems which we are discussing now so friends in our previous lecture we also discussed that this solution is very less optimized because we are recalculating the values of the sub problems multiple times so for example let's say we calculated FIB of three which has value two now what if if I store this value somewhere and let's say when I encountered FIB off 3 again instead of going to this deep tree I can just return two so I don't have to calculate this tree again similarly with FIB of two if I store the value as one I can avoid recalculating this sub tree and this sub tree thus you can see that if I calculate the values in green box once I can store those values and simply I can reuse whenever these values are required again therefore it's a perfect example of demonstrating that n fibon number is a dynamic programming problem so friends in our next lecture we'll see that how we can store these values somewhere and can reuse them again whenever the same sub problems occurs multiple times so friends I hope you like this video thanks have a nice day hello everyone so friends in our previous lecture we discussed about the two main characteristic of a dynamic programming problem which was optimal substructure property and overlapping sub problems property so friends till now we saw that how we can solve a problem using recursion so in this lecture and in upcoming lecture we'll see that how we can solve a problem using dynamic programming so friends there are two approaches to solve a dynamic programming problem the first approach is bottom up approach so what do we mean by it in bottom of approach we try to solve smaller sub problem first use their solution to build on and arrive at the solution to bigger sub problems so which simply means so let's say if you want to solve a complex problem so instead of solving the complex problem at once what we do is we start with the smaller sub problems we try to solve those sub problems we use those sub problem solution to arrive at a solution to the bigger sub problems and this this way we try to solve the bigger sub problems and finally reach to the solution of our main problem so the bottom of approach is also called the tabulation method because in this approach when we solve the smaller sub problems we usually store the result of those smaller sub problems into a table and when those smaller sub problems are encountered again then we simply use the values from the the table to arrive the solutions to the bigger sub problems and this way solving the chain of sub problems we reach to the solution of the main problem therefore the solution is built in a tabular form by using the solutions of smaller sub problems iteratively and generating solutions to bigger sub problems so friends in the previous lecture we saw that when we use recursion and when we solved the N Fibonacci number problem we saw that it was less efficient code because we were recalculating the sub problems again and again so instead of recalculating the sub problems again and again what we do is we store the results of those sub problems in a table and when those sub problems are encountered again we simply use the values of those smaller sub problems from the table table itself without going to solve those sub problems again and again so friends now let's look at the demonstration of bottom of approach that how we can use the tabulation method to memorize the solution of the sub problems and reuse them later when those sub problems are encountered again so here you can see that in this example we are simply calculating the nth Fibonacci number and this time instead of us using recursion we are using the bottom up approach which is nothing but solving it via one of the methods of dynamic programming so let's say we want to calculate the fifth faki number so here when we call this function FIB the value of n will be five so in the first step what we do is we simply create a table which is nothing but an array to store the result of the smaller sub problems so when we want to use the result of those sub problems again we can simply refer this table pick up that value and simply reuse so friends here we will simply create a table of length n + 1 we will see why we are taking the length is n+1 so it would look something like this that there will be an array by name table having six elements from 0 to five and we are using n + 1 because we know that array starts from zero and if you want to calculate the fifth Fibonacci number the value of fifth fibon number will be stored at the fifth index of the array so therefore we are using n + 1 moving ahead so friends as we know the that Fibonacci series starts with 0 and 1 so here you can see we are simply assigning the value as 0 and 1 to the zeroth index and the first index so we are assigning zero to the zeroth index and then we are assigning one to the first index moving ahead so friends here you can see that we want to calculate the fifth Fibonacci number which is this but we are starting from the bottom by using these base cases therefore this approach is also called as bottom of approach because we build our Solution by traversing from the bottom and we move up and finally we reach to our solution so friends here you can see that we have calculated the value at zero index and at the first index so now what we do is we provide a for Loop we start from the second index and this for Loop will go till the value of I is less than equal to 5 so here you can see I becomes 2 and as I is equal to 2 here we can see that I is less than equal to 5 therefore the condition in for Loop comes out to be true and the for Loop executes also friends we know that how we can calculate the Fibonacci number we simply do the sum of its two preceding numbers so here what we are simply doing we have already stored the result of zeroth index and the first index and when we want to calculate the second Fibonacci number we simply do the addition of the first preceding number which is i - 1 and the second preceding number which is I -2 so this is nothing but we are doing the sum of its two preceding numbers because in this table we are actually storing the Fibonacci series and when we want to calculate the second Fibonacci number we simply do the addition of its two preceding numbers which is 0 and 1 so here you can see the value stored at table i - 1 which is 2 -1 index has value 1 and the value stored at table i - 2 which is 2 - 2 has the value 0o so we'll simply add 1 + 0 and store the value one at the second index here so these are the two preceding numbers which you will add and store at this position so now the value at second index becomes one moving ahead now we'll increment I so I becomes three and now we want to calculate the value at the third index so so we'll simply do the sum of its two preceding numbers with i-1 and I -2 so i-1 gives the second index value and IUS 2 gives the first index value we'll do its sum which is two and we'll store two at the third index so value two is nothing but the third Fibonacci number moving ahead now when we increment I by 1 I becomes 4 now we want to calculate the value of the fourth Fibonacci number which is stored at Fourth index and this value can be obtained by doing the sum of its two preceding numbers which is at index 2 and 3 which can be obtained by taking the value of the table IUS 1 plus I - 2 so I -1 gives the value at third index I -2 gives the value at 4 - 2 which is the second index so we'll do its sum 1 + 2 becomes 3 we store three at the fourth index moving ahead now we'll increment I by 1 so I becomes five and then we'll simply calculate the fifth Fibonacci number by doing the sum of its two preceding numbers which is nothing but I minus one which is 5 - 1 = 4 the fourth index and I - 2 which is 5 - 2 which is 3 and that is nothing but value stored at index so we'll do the sum of these two values which is 2 + 3 = 5 and we'll store the F at the fifth index and now we'll increment I again so I becomes 6 but here you can see that 6 is not less than equal to 5 therefore the condition in for Loop comes out to be false and for Loop terminates so friends we simply return the value stored at fifth index which is nothing but our fifth Fibonacci number which is five so friends here you can see that in our previous lecture we used recursion to solve the N Fibonacci number problem and we saw the solution was very less efficient because we recalculated the values of the sub problems again and again so here what we did we simply created a table to store the results of the sub problems and when we wanted to use the values of the sub problems again we simply referred this table Ed those solution and build up upon the solution to the main problem so here we started from the bottom which is from the zero index and the first index and as we knew that the first two number of Fibonacci series are 0 and one we simply used those two values to come up with the second Fibonacci number then we used the first fibon number and the second Fibonacci number we did it sum we got the value of the third Fibonacci number and similarly we got the value of fif funaki number so friends here you can see that using this tabulation method we are storing the results of the sub problems and we are not recalculating the values of those sub problems we are simply referring to this array we are taking out the values and we are simply using to build up upon the solution to the main problem so this is the bottom of approach to solve the problem of calculating the N Fibonacci numbers so friends now let's go to eclipse and see the demonst ation of this code I hope you like this video thanks have a nice day hello everyone so friend in this lecture we'll see how we can code a program to find the N Fibonacci number using dynamic programming and in this lecture we'll use the bottom up approach so friends in our previous lecture we saw the algorithm of how to find the N fibon number using the bottom up approach we saw its animation and here in Eclipse we'll actually code the algorithm and using this main method we'll see it's working so here we'll create one method as public which will return us back the N Fibonacci number so int we'll give the method Ms Vib which will take the value of n for which we want to find the Fibonacci number so friends for the positive values of n we need to return the N fibon number from this method and as we are discussing the bottom up approach using dynamic programming we know that this approach is nothing but the tabulation approach where we create the table and store the results of the sub problems and when those sub problems comes again into picture instead of recalculating them we simply reuse the values stored in the table so here we'll create an array we'll give it a name as table and the size of the array would be n + 1 because as array is index from zero and we are using this table to store the individual Fibonacci number so in order to get the N Fibonacci number we need to create a table which can store n+1 items so that it will start from 0 to n and at the ne index we will have our n Fibonacci number also friends what we discussed in our previous lectures that the first two numbers of the Fibonacci series are nothing but zero and one so table at the zero index will have value as zero and table at the first index will have value as one and also friends we discussed that in Fibonacci series if you want to know the current number you just need to do the sum of it two previous numbers so here we have this first two numbers if we do sum of these two numbers we'll get the second number and similarly using this approach we can come to know that what is the nth number so we are simply storing the Fibonacci numbers in this table array so we have used the zero index and one index so now we'll start from the second index we are starting from the second index and as here you can see the table as size of n + 1 so we'll provide a Boolean condition here that if I is less than equal to n just iterate this for Loop we'll do I ++ so so friends here you can see the advantage of creating a table array what we can do is simply let's say if we want to calculate the a fibon Naki number we simply do the sum of its to previous numbers and whatever the values computed from this equation we simply store it into the table at aat index so does this table help us in Computing the N fibon number from the bottom which is from the zeroth index to the nth index so we have this first two values as index 0 and one the second value is computed by adding this value and this value which is ius1 and IUS 2 and storing it into the second index and similarly the third index will be calculated by adding the value at second index and the first index so this Loop keeps on going ahead and ahead taking previous two values doing their sum and storing it into the current aat position and finally when this Loop terminates the final value will be stored in the table at the N index which we also saw in our previous lecture using the animation so we'll simply return that value so here first we'll create the object of Fibonacci number class we'll provide a s out to print the N fibon number let's say we want to print the sixth Fibonacci number we simply call the method fib we'll pass the value as six and now we'll simply run the program so here you can see the 6 F9 number is eight so which is something like this that Series starts from 0o 1 and then the rest of the values are calculated by using the sum Su of its two previous numbers so 0 + 1 gives 1 1 + 1 give 2 2 + 1 gives 3 3 + 2 gives 5 and 3 + 5 gives 8 so the six fibach number which comes out is8 so friends this was the demonstration of code to find the n f number using dynamic programming with a tabulation method which is nothing but bottom up approach I hope you like this video thanks have a nice day hello everyone so friends in this lecture we will discuss about the top- down approach so in our previous lecture we saw that how we can solve a problem using dynamic programming with a bottom up approach and in this lecture we'll see that how we can solve a problem using topown approach so what is topown approach so this method is also called as memorization so what it means is that in this method we break the LGE problem into multiple sub problems each of the sub problems are solved and solutions are remembered so by remembering the solutions we treat it as a memorization and the term given to it is memorization which means that something we are remembering to reuse it later so how does it work is if the sub problem is solved already we simply reuse the answer so here you can see that we are solving the sub problems and IT solutions are remembered so later point of time if that sub problem comes again into picture we simply reuse the remembered answer or else what we do is we simply solve the sub problem and store the result which simply means that we are remembering the solution somewhere does it memorizes the solution of the sub problem to avoid the recomputing the value of sub problem is encountered again so friends in our previous lecture we also saw that that when we are doing recursion we can solve the problems by breaking it down into multiple sub problems and if those sub problems are encountered again then instead of recalculating it again we simply store the solution of that sub problem and when those sub problems are encountered again we simply use those Solutions rather than Computing them again and again does it bring the optimization to our recursion so here we'll see a program to find the N fibon number using top down approach so here you can see this is the algorithm where we need to find the N fibon number and here we are also passing an integer array which will simply help us in memorizing the solutions of the sub problems and we will frequently check this integer array to see if those sub problems are solved already or not so if those sub problems are not solved we proceed ahead we solve those problems and we store it into this integer array and if the sub problems are solved already we simply reuse the solution so this memo array help us in remembering the solutions so that we can reuse those Solutions if the same sub problem is encountered again does it provides the optimizations to our recursive Solutions so friend as this this is the recursive Solutions we'll also see the demonstration using the call stack so let's say we want to calculate the fifth fibon number so we'll simply pass an empty array with the size is 5 + 1 which is six because we know that the indexes of array are starting from zero and this memo table will store our Fibonacci numbers from 1 to 5 so the value stored at the fifth index will be our answer so therefore we are creating an array of size six so in the first step it would look something like this that we have an array of size six having the default value is zero and on the call St you will see the fif method has started this execution with the value of n as five and with the integer array shown here having all the values as zero so friends here you can see that as we are using the top down approach we are starting from the fifth index which is the topmost index and then we are going to the bottom in the bottom up approach we started from the zeroth index and we went till the fifth index but here we are starting from fifth index and we are going to the bottom so here we are simply checking if the value of fifth IND is zero or not so here you can see the value of fifth index is zero which in terms of this problem it is not solved so the condition in ifog comes out to be true and we need to calculate this value so first we check whether the N is less than 2 or not so here you can see the value of n is 5 which is not less than two so the condition if block comes out to be false and the L sport gets executed so here we also know that in order to calculate the fifth fibon number we need to do the sum of its two previous numbers which is the number stored at third index and the fourth index so in order to do that we simply call the fif function again passing in the memo array and the value is n minus one because we need to calculate this value and this value and then do the sum of these two values to get this value so here you can see that now this fifth function is called recursively and we are leaving this fifth function on the call St at line number six so we'll simply add the line number six here so that later we can come to know that from which point we need to restart this F function so we have left this function and on the call SEC there will be one more fif function with this memo array and the value of n is four because we are passing N - 1 so 5 - 1 gives 4 so this function will be executed with n equal to 4 we check that whether value of fourth index is computed or not so we know that is equal to Z therefore it's not computed so then we go ahead and compute it 4 is not less than 2 so the condition in if block comes out to be false and now in the else block if we want to compute the value at Fourth index we need to compute the value at second and third index do their sum and get the value at Fourth index so friends here you can see that first we'll need to calculate the the value of third index so we'll again call the fifth function passing in the array and the value is n minus 1 which is 4 - 1 = to 3 and we also know that we have to leave this fifth function at line number six so we'll simply store the line number here and then the fifth function will be called again and on the call stack you can see we have left this fif function and we have started executing this fif function with the value of ns3 we check whether the value of three is computed or not so here you can see the value of n is equal to Z therefore it's not computed we check whether n is less than two or not so 3 is not less than two and here in order to calculate the value of the third Fibonacci number we need to First calculate the values of its two preceding numbers so we again call the fifth function passing it the integer array and the value is 3 - 1 which is 2 and we are leaving this function at line number six so the fifth function will be called again where the value of n is 2 so on the call stack there will be another fifth function with the value as2 we will see the value at second index is computed or not so here it is equal to zero therefore it's not computed we check whether two is less than two or not so 2 is not less than two so we'll start executing the lse part and here also in order to calculate the value at second index we need to First calculate the value of its two preceding numbers do their sum and get the value of second index so first we'll go to the N minus one part which is 2 - 1 which is equal to 1 so here now fif function will be called again so we are leaving this fifth function at line number six so we'll store the line number here and then fif function will called again with a value of n is 1 so on the call St it would look something like this we see that value of first index is computed or not so here you can see it is equal to zero therefore it's not computed and we proceed ahead now we check whether n is less than two or not so here you can see the N is less than two because the value of n is 1 so friends here you can see that why we have provided this if block so we know that the Fibonacci series starts from 0 and 1 so we are simply checking that whether n is less than two or not if it is less than two we are simply storing the value of n to the memo of n so here value of n is 1 so at the first index we are storing the value as one so it would look something like this so one is stored at 1 position so after this step finally we return the value stored at first index so friends here can see that why we are returning this value one here because we called this fif function from this fif function and we left at line number six so at line number six we had to calculate the value of 1 and then we have to calculate the value of nus 2 and then do the sum of these two values to get the value at second index so therefore we have calculated the FIB of n minus 1 which is 1 so we are simply returning the value one from this F function to this fif function so it would look something like this this F function will be removed from the call stack and the call will go to this fif function and we also know that we had left at line number six so we'll start executing from the line number six and whatever we return return from this method will be stored in the left which is nothing but one moving ahead now here you can see that when we are executing this fif function the value of n is two we have computed one of its previous value which is n minus one and now we have to find the value n minus 2 so that we can do the sum of these two values and get the value at the second index so therefore now we'll again call the fifth function to calculate the nus 2 value so here you can see that now we are again calling fif function and we are leaving this fif function at line number 7 so we'll simply update the line number seven so that we can come to know the later that at which line we left this function so we updated the line number and now this fifth function will be called with the value as n minus 2 which is 2 - 2 which is equal to0 so it is called for FIB of zero and here we check if the value at zeroex is computed or not so it is equal to zero therefore it's not computed we check whether n is less than two or not so 0 is less than two therefore condition if blog comes out to be true and finally we'll store the value of n which is zero to this memo table at index0 so here at index 0 will simply storing the value as zero because we know that the Fibonacci series starts from 0 and 1 so if the value of n is less than 2 we simply store that value into its index so now we'll simply return this value because we need to get this value here so this F function will be removed from the call stack and zero will be returned from here and we know that we had left at line number seven so we'll start executing from the line number seven and this F function has returned a value zero so we'll store that value in the right so zero will be stored at the right so friend now you can see that in order to calculate the second Fibonacci number we need to do the sum of its to previous numbers so we have got the sum of it two previous number as 1 and zero we'll do the sum of it and we'll store at the second index so 1 + 0 is 1 so we'll simply store the value one here and then from this fifth function we'll simply return the value stored at second index because value of n is two which is nothing but one so one will be return from this method and this method will be removed from the call stack and now we'll start executing this fif function and we know that we had left at line number six so we'll start executing from the line number six and we also know that we had returned the value one from this fif function so one will be stored in the left integer variable moving ahead now we have calculated the N minus 1th value which is this and we need to calculate the N minus 2 value which is this in order to get the third Fibonacci number because value of n is three so we have computed one value we need to compute the other value so here the fifth function will be called again with the value as n minus 2 which is 3 - 2 which is 1 and we know that we are leaving this fifth function in line number seven so we'll simply update the line number seven here so the fif function will be called again with the value of n is 1 here now we have to calculate the value of the first Fibonacci number so now here you can see the advantage of using this memo table we are checking that whether value at first index has been calculated or not so this sub problem has been incountered again because we have already calculated the value at first index which is one so by providing this simple check that whether memo of n is equal to zero or not so we have already calculated this value so we don't have to recalculate it again here or here so therefore storing this results of the sub problems gives us an optimization over the recursion here so instead of calculating it again here we are simply returning the value stored at the first index so we are simply returning memo of one which is one so this F function will return the value as one and we know that we had left a line number seven so we'll start executing from this line and as the return value is one the value stored in right would be one and finally we can come to know the third fibon Naki number by simply doing the sum of its two preceding values which is 1 and 1 and we'll simply store that value at the third index so 1 + 1 is 2 so we'll simply store the value two at the third index we move ahead and we'll simply return the value two from this F function so this method will be removed from the call stack and it will go to its previous fif function which we had left at line number six so we'll start executing from the line number six and we know that we had written the value of two from this sft function so it will stored in the left and now we'll simply calculate the FIB of n minus 2 to get the value of the right part so on the call stack we are leaving this fif function in line number seven so we'll update the line number seven this s function will be called again and on the call stack we will call FIB with the value as 4 minus 4 - 2 which is 2 moving ahead we'll simply check in this table that whether this sub problem which is fib of two has been solded or not so we are simply checking this memo table and we are simply checking at the second index whether the value is zero or not so here you can see we have already solved this problem and stored its result therefore we don't have to recalculate it again so we are simply returning the value stored at the second index which is one and we are returning the value one from this F function to this F function and as we know that we had left this F function in line number seven we'll start executing from the line number seven and then we'll simply store the value returned from this function which is one into the right variable finally we'll do some of these two numbers and we'll store it in the fourth index because in order to calculate the fourth fibon number we need to do the sum of its two preceding numbers which is at index 2 and three stored in left and right so 2 + 1 gives 3 so we'll simply store three at the fourth index and finally we'll return the value three from this F function to this F function and we also know that we had left this F function in line number six so we'll start executing from the line number six we return the value three from this F function we'll simply store it into the left integer variable three and now in order to calculate the fifth fibon number which is our actual main problem we had calculated one of its preceding value which is n minus 1 here here we just need to calculate n minus 2th value this value and then we can do the sum of its two values and get the solution to our main problem so here we'll again call fif function passing in a value as n minus 2 which is 5 - 2 = to 3 and we are leaving this fifth function at line number seven now so we'll update the line number seven so this F function will called with the ns3 and friends here you can see the advantage of this memo table that we have already calculated the third Fibonacci number because value stored at third index is not equal to zero therefore we don't have to recalculate it again and again using this code so finally we'll return the values stored at the third index which is two and we'll simply return from this method and go to its previous method and we know that we had left at line number 7 so we'll start executing from the line number seven and as two is return from this fifth call we'll simply store it into the right integer variable and then as you want to calculate the fifth fibon number we got the fourth fibon number and the third Fibonacci number stored in left and right we'll do its sum and we'll store at the fifth index so 3 + 2 gives us five so five is stored at the fifth index and finally from this fifth function we'll return the value stored at the fifth index which is our actual answer the fifth foni number has the value of five so we are simply returning the value five and this metal will be removed from the call stack and hence our problem is solved so friends here you can see that we started from the top we move to the bottom therefore it's top down approach and we also know that we have used this memo array which helps us in memorizing the solutions of the sub problems so that those sub problems when encountered again are not recalculated again so we are simply storing those sub problems result here and when those sub problems are encountered again we don't have to compute it again we simply take that value from this memo table and reuse it again therefore using this memo table to our normal recursion we are providing an optimization and we also know that dynamic programming is nothing but the optimization to our recursive problems so friends in this lecture we saw the top- down approach of dynamic programming that how we can use that approach and Sol a complex recursive problems efficiently now let's go to eclipse and see the demonstration of this algorithm I hope you like this video thanks have a nice day hello everyone so friends in our previous lecture we saw the animation for the topown approach that how we can solve the problem related to finding the Fibonacci number using dynamic programming by top down approach so in this lecture we'll cotee the algorithm to find the N Fibonacci number using top down approach so here in Eclipse you can see that few lectures back we saw the bottom up approach and this approach is also a method in dynamic programming so in this lecture we'll see the top down approach so first we'll create a method which will return us back the N Fibonacci number which is an integer and let's say the name of the method is fib now as we discussed in our last lecture that to this fif function we pass in a memo array which help us in storing the solutions to the sub problems and when those sub problems are encountered again instead of recalculating it we just go go to this integer array into that particular index we pick up that value and reuse it th this integer array helps us in optimizing the recursion Solutions so this method also takes the value of n for which we want to find the Fibonacci number so friend in order to find the N Fibonacci number what we simply do is we simply first check that whether the M of n is equal to zero or not so what it means that we are using this array to store the Fibonacci series and as you want to calculate the N fibon number we simply check that this array at index n is equal to Z or not so if it is equal to zero we come to know that the n fibon number has to be calculated so inside this if condition we provide a f block where the condition is if n is less than 2 then what we do is we simply assign the value of n to the integer array at the index n so why we do this because we know that the first two numbers of Fibonacci series are zero and one and as the array starts from zero index so this value will be stored at zero index and this will be stored at the first index so we simply check whether n is less than two or not so if value of n is 0o then 0o is stored at zero index and if the value of n is 1 then one is stored at the first index and if n is not less than two then in the L's part what we do is so here we know that the Fibonacci series as property the current number is sum of its preceding two numbers so based on these two properties what we come to know that if you want to calculate the N fibon number we need to know its two preceding numbers which is n minus1 and nus 2 we do its sum and we get the current number so here let's say current number which we want to calculate is n number so what we do is we first calculate the FIB of n minus one so we call this fif function recursively which we also discussed in our previous lecture so whatever the value it returns we store in the left and then we again call the FIB passing in the memo array and pass in N minus 2 because if you want to calculate the nth fibon I a number we need to know the N minus 1th Fibonacci number and N minus 2th fibon number and once we know these two values we can do their sum which is left plus right and as we know left plus right we simply store this value at the nth index because we know that this integer array basically stores the Fibonacci numbers and as we want to calculate the N fibon number we simply stores the left plus right at the index n and finally we return the answer which is the value stored at the net index so friends here you can see that this line is very much important because because this line checks that whether the sub problem is solved again or not so here what we do is if the M of n is equal to zero we come to know that the value of n index is not been solved so what we do is we go into if block and we calculate the value of net index and we simply store it here and what if the M of n is not equal to zero then we know that we have already solved this problem so then we simply return the value stored at n index also friends in our previous lecture we saw the animation that how this L helps us in optimizing the recursion so that we don't have to solve the sub problems again and again and as we start from the value of N and then we slowly go to the Bottom by doing n minus1 n minus 2 and then again recursively moving down therefore this approach is also known as top down approach because we start from the top and then go to the bottom and as we go to the bottom we encounter these base cases where the first two Valu we store as 0 and one and after getting these two values we build up upon the solution and finally we get the N Fibonacci number so friend now let's see the demonstration of this code in the main method so first we'll initialize the Fibonacci number class and let's say we want to find the six fibon number so here the value of n would be six and as we are calling this fifth function we need to pass an empty array whose size would be n + 1 which is 7 because we want to store the Fibonacci numbers from 0 to 6 and finally we need to return the value of the index 6 so as we are going from 0 to 6 we need to initialize the array of size 7 so we simply pass an empty array of size 6 + 1 and if I run this code now so we get the answer as eight because here you can see that in the array it will be stored in this format 0 1 would be the starting values then we do the sum of these two values we get this value then we do sum of 1 + 1 we get two then 2 plus + 1 we get 3 3 + 2 we get 5 5 + 3 we get 8 so friend this is how we can use dynamic programming to solve this problem to find the N fibon number and using this top down approach we have solved this problem very efficiently and whatever the solution we get is highly optimized so friends I hope you like this video and in case Cas you have any problem you can watch my previous lecture where we go through this code step by step using the animation and in our next lecture we see different problems associated with the dynamic programming thanks have a nice day hello everyone so in this video we'll be looking into a problem maximum sum subar and we will be looking into a specific algorithm which was provided by Ken L to solve this problem so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in this problem we are given with an array with some random elements and it can have negative elements as well we name it usually maximum sub array sum so here in this problem what we actually do is we try to find any sub array such that if we do the sum of the elements of that sub array and whichever is the maximum sum we simply find that out so for example let's say if I take this two elements so a sub array is actually a smaller piece of array of the bigger array and the elements are contiguous so if we do sum of these two elements we will get seven so this is one such sub array one property of sub array is that it should be continuous so for example two we can't take 2 4 5 do their sum and find the maximum sum because three is missing so a sub array is actually a smaller array which is contigous so here we saw that one of the sub array has sum to be seven now there can be multiple sub arrays so we need to find the maximum sum of any particular subarray and we simply want to return that sum so here you can see if we take this sub array 4 3 - 2 and 6 we will get 4 + 3 - 2 + 6 so it will give us 11 so this is one such sum so we try to find that whether this ARR has any other sub array whose sum is maximum or not so here if you see if we take this three elements 7 + -1 + 6 so it will give us 12 so it means we can discard this sum and this would be our answer so 12 is the maximum sum of any sub array so in order to find such sum The Brute Force wave would be that we try to create each and every sub array we do their sum and we see which is the maximum sum so usually this approach is not good so there is one such algorithm which was provided by cadin which actually Travers this array once and figures out what is the maximum sum sub array so here how we actually solve this problem is we usually create two variables current Max and the best sum or maximum so far now what this two variables denote we'll see later and this algorithm we try to Traverse from left to right so at the start we encounter four now what we do here is let's say if our array had only one element four so the maximum sum would have been four only and we would have return from this array saying that four is the maximum so here you can see we will be traversing this array one element at a time and let's say at this index for example we we will be storing two things current Max and the max so far so what this two variables denote is that at index 3 what is the current Max sum and as we have traversed this array we would have encountered many sub arrays so among those sub arrays which what's the max so far or what's the best sum so these two things we keep track while traversing from left to right also when we Traverse the elements one by one at each element the element usually asks two questions that should I become part of the current sub array which will give us the maximum sum or should I start my new sub array so here we'll look into the demonstration and what this two questions actually mean so here if you see at the start we encounter four at index zero so four will ask that should I become part of the current sub array so here you see current subarray is empty because there are no element as this is the first element only should I become part of the current subarray so that sum is maximum so at the start both these questions as there is only single element both this question correspond to the same thing if four becomes part of the current sub array it would be something like this or if four starts a new sub AR it will be something like this so usually at the start the current Max is 4 and it has been formed by this sub array and we simply take 4 as the max so far being formed by this sub aray now we'll go to the first index so at this index three will decide should I become part of the current subarray so here if you see current subarray is four so if it becomes part of the current sub array so sub array will become 43 and sum will become 7 or it will decide that should I start a new sub array so if it decides new sub array sum will become three so among these two questions three will see that it's better to become the part of the current subarray because we are getting a maximum sum among these two sums so three will become part of the current subarray so the subarray will go something like this these two elements are there and the current Max at this point would be 7 which is being formed by 4 and three so here you can see now this Max so far this 7 is greater than 4 so this Max so far will be updated to 7 stating that it is being formed from the elements 4 and three moving ahead now we encounter minus 2 I'll just remove this so min-2 will think should I become part of the current subarray so if it becomes part of the current subarray the sum would be 7 because 7 is the sum of the current sub array plus minus 2 which will give it a value as five or it will decide should I start a new sub array so if it starts a new subarray the sum will become min-2 because we will be discarding this sub array if we are starting a new sub array from here so minus 2 sees that okay uh if I become part of the current sub array the sum will be five and if I start my own we get min-2 so it's better to go with the current sub array and get the sum of five so here at this position the sum will become five it it has been formed by 4 3 and minus 2 and this five is actually smaller than 7 so max so far will remain this only it means that though we have taken up min-2 into this sub aray but the sum is not actually greater than the maximum sum so far or the best sum so the best sum will actually remain this so let's say if we had only this three elements in the array so the current Max would have been five and our answer would have been seven stating that we usually take four and three and we will get the max sum we will discard minus two from the best sum and also here one question arises why we are taking min-2 into the consideration here why we are actually adding minus two because because there could be a possibility let's say the current number is here is six so there could be possibility here number is 1,000 if we don't take minus 2 then our current sub array will start from this because the sub array is contigous and if we are not taking any element it means we are discarding the previous sub array so the sum would have become th000 if we have not included minus 2 and now if we include min-2 so here you can see the sum came out to be five and let's suppose here would have been th000 so we would have included th000 also and got 1 05 so which is much way better than th000 therefore we simply include min-2 based on these two questions because we are not sure what comes after this minus 2 it could be any negative value or it could have been any maximum value so it's better to include min-2 into this sub array so now our sub array reaches like this that it has included everything 4 3 and minus 2 I will remove this so now we counter six so here six will decide that okay should I become part of the current sub array so if it becomes part of the current sub array so the sum will become five because the sum is five + 6 which will give us 11 or decide that should I start a new subarray so if it discards this previous subarray and starts a new subarray from here here so the sum will be six only so the element six will decide okay I will go with the current sub array because this gives the maximum sum so here the current Max will become 11 which will be the addition of these four elements of the subarray so now here you can see that this 11 actually beats 7 so max so far will take the maximum sum is 11 because it will figure out that okay now I need to include 4 3 - 2 and 6 together because this is giving me a maximum sum moving ahead I will remove this so now six has become part of our subarray now we encounter -2 so -2 will decide should I become part of current sub array so the current sub AR is this so 11 + - 12 will give us minus1 or it decide should I start my new sub array so if it starts its new sub the sum would be -12 so -12 sees that okay -1 is greater than -2 so it's better I should become part of the current subarray so here now our current Max become minus one being formed like this but this minus1 is very much less than 11 so max so far will remain the same that let's suppose if our array would have ended here so the answer would have been 11 which is being formed from the elements 4 3 - 2 and 6 so this is the significance of Max so far it keeps the track of the maximum sum of any sub array so far so I'll just simply remove this and here - 12 comes with the current subarray now we encounter 7 so seven will ask should I become part of the current subarray so it sees the current subar is this and it sum is -1 so -1 + 7 will give us 6 or it decid should I start my own new subarray so if it start its own new subarray it has to discard this sub array and if it starts a new subarray from here like this so the sum will be seven so this element thinks that okay I should not go with the current sub array because it is giving a sum only six but if I start my own it will be a maximum sum of seven so here is the critical step where the current element decides that okay I won't go with the current sub aray I will start my own subarray which is a new sub array so here we simply discard this sub array because current Max will now be 7even and it will be formed by only digit 7 but this 7 is less than 11 so the max so far will remain the same so now this sub array is actually discarded and a new subarray will start from seven so now we encounter minus one so minus one decides that okay should I become part of the current sub AR so 7 + -1 will give 6 or should I start my own sub array so the sum will be minus one if it starts its own sub array so it decides that okay I will be part of the current subarray because it is giving me a maximum sum so here now our current Max will become 6 because minus one has decided to go with the current sub array 7 comma -1 okay but this six is less than 11 so our Max so far will still remain the same moving ahead so now our subar has two elements 7 and minus one so now the last element comes which is six so six ask should I become part of current sub AR so six plus this six will give sum as 12 or should I start a new sub array so if it starts a new sub array the sum will be six so this six decides okay I will go with the current sub are because it is giving me a maximum sum if I compare these two values so here now current sum will become 12 7 - 1 6 so this will be included like this and now here you can see 12 is actually greater than the max sum So Far So Max so far will see that okay I need to now discard this because we have found one more sub array whose sum is actually maximum from the current Max so far which is 12 formed by 7 -1 and 6 and here there are no more elements left so the answer would be our Max so far which is 12 so this will get written so friends in this video we saw that how we can solve the maximum sum subar problem using cens algorithm in our next video we will actually see the demonstration of the algorithm step by step that how we can use the code and come up with this logic we will see it via an animation in our upcoming video I hope you must have liked this video and in case if you're new to my channel then please subscribe to my channel thanks have a nice day hello everyone so in our previous video we discussed about the idea behind how the cut algorithm work in finding the maximum sums of AR so in our previous video we actually discussed the idea behind the algorithm we saw that how current Max and Max so far are the best sum help us in determining the maximum sum sub array in this given array and we also saw that we Traverse the array and on each element the element decides that should it be part of the current sub array or should it start a new sub AR so now let's see the demonstration of this algorithm step by step so here you can see that we have been provided with an algorithm which is the cens algorithm so usually the method name is Max subarray sum it takes in integer array and finds as a maximum sum for any sub array in this array so let's see the demonstration of this algorithm step by step so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so at the start let's say we provide an arrs what we discussed in our previous example so usually at the start the first element is simply taken as Max so far and the current Max so max so far is four this value and current Max also becomes four now the algorithm basically starts with second element so here I starts from one and goes till array. length so here AR do length is 8 so I will travel from 1 to 7 because 7 is less than 8 now on this point 3 has two choices either it should become the part of the current sub array so the current sub array is this or it should start its new subar so as we discussed in the previous slide what we do is we take current Max and we add the value stored at the index of I and we assign it to the current Max so here we are simply taking the current element value and we are adding it with the current Max and assigning it to the current Max so it means three decided to go with the four it means 4 + 3 will give us 7 so 7 is assigned to the current Max so current Max becomes seven now why we directly assigned it because in the next step this current Max is actually compared with the with the elements value so this is our second question that should I start my new sub array here this part was where element decides to go with the current sub array and in this if block there is our second question that should I start my new subarray so if current Max is less than the value of the current element then we simply assign this value to the current Max so here 7 is compared with three because array of I is three so whichever is the bigger value is simply assigned to the current Max so 7 is the bigger value among these two values so current Max Remains the Same so friends here you can see that when element decides to be a part of current sub array we simply add it to the current Max and here we are simply assigning it to the current Max because in the next step we will reassign it if current Max is less than the current elements value which means that three has decided to create its own subarray so this is actually our question one and this is actually question two so whichever wins that value is assigned to the current Max and if this condition comes out to be false then we do nothing with the current because we have already assigned current Max Plus array of I2 current Max which is 4 + 3 = to 7 to current Max so now this value is included in the sub array so the current Max is 7 being formed from the subarray 4 comma 3 which is these two elements and now we'll simply compare this sum current Max sum with the maximum sum so far so if Max so far is less than current Max we simply assign the current max value to the max so far because current Max actually beats the maximum sum so far so here Max so far is four and current Max is 7 so this condition comes out to be true and Max so far becomes 7 so here this is current Max and this is Max So Far So at the start it was 4 then it became 7 taking in 4 comma 3 moving ahead now we'll increment I by 1 so I points to the second index now this Min -2 has two questions that should I become part of the current sub array so we simply take their sum current Max Plus array of I it means we are including array of I so here it will become 7 which is the current Max Plus -2 so 7 which will give us five so current Max will become five and then this element simply ask that okay can I start my own sub array so this check actually decides that that if current Max which is five so if it is less than array of I value which is min-2 so ARR of I value is simply assigned to current Max So currently so this condition comes out to be false because 5 is greater than -2 then we simply check whether Max so far is less than current Max or not so why we are doing this check is we are simply keeping the track of the maximum sum so far so if at any step current Max becomes greater than Max so far it means we have found the maximum sum so far so we simply assign current Max to Max of far so as of now Max s far is 7even and current Max is five therefore this condition comes out to be false because 7 is not less than 5 so here the current Max will become five taking in 4 3 and minus 2 and Max so far will remain same so now we'll increment I and here you can see this element has been included in the current Max subarray so friend here you can see as we know that each element asks two questions whether it should become part of the current sub array by simply adding its value to the current Max or they decide to create their own subarray so this piece of code decides that so you can also think this piece of code as something like current Max equals we can also write something as math do Max and the two values would be current Max Plus array of I or array of I so whichever is the maximum value we simply assign to the current Max so this is question one and this is question two that should I become part of the current sub array if that is maximum that value is assigned to the current Max or if element decides to create its own sub array so it's simply its value is assigned to the current Max so either we can do this or we can do this that first we directly assign current Max Plus array of I value to current Max and then with this if block we reassign the array of I value to current max if the value at index is actually greater than the current Max so it means this value is greater than current Max Plus array of I so this value will be assigned or else we have already assigned this value to current Max here so now value at I index is six so we simply assign five + 6 which is 11 to current Max so current Max becomes 11 11 and then we simply decide that whether current maass which is 11 is less than the value six or not so if it is less than six then we simply reassign current Max to the array value with ADD index so this condition comes out to be false because 11 is greater than 6 so here 11 is our current Max we have taken this four values now we'll simply compare that whether the maximum sum so far is less than current Max or not so here you can see 7 is less than 11 it means we have found a new Max so far so we simply update current Max to Max so far so it becomes 11 4 3 - 2 and 6 so it means we have found a sub array of Max sus 11 having this four elements so now we'll continue with the rest of the elements we'll increment I so I will now point to the fourth index so here array of I is -2 so here we are simply adding current Max which is 11 it will give us minus1 so current Max will become minus one and then this element will decide that can I start my own sub array so it will compare its value which is this part with the current Max which is min-1 so minus1 is greater than -2 so this condition comes out to be false and the current Max which is minus1 is actually less than Max so far so this if condition also will come out to be false so max so far will remain 11 which makes sense because a sub whose maximum sum is 11 is being form from these four elements so here we simply write 11 only 4 3 - 2 and 6 moving ahead so here -2 has been included in the current sub aray I will now point to index 5 current Max will become -1 + 7 which is 6 so this is the part when array of I decides to go with the current Max and then it checks okay can I start my own sub array because my own value is 7even but if I go with the current sub array the current Max is six so therefore it decides that it's better I create my own sub array because if I create my own sub array I will give a sum of seven and if I go with the current sub array the sum will be six so therefore this condition decides that the current Max is 6 and it is actually less than 7 so the current Max will become 7 by simply assigning array of I to current Max which signifies that 7 has decided to go and create its own new sub array so current Max becomes seven so now this sub array will be removed and from here a new sub array will start and here we'll simply denote 7 by taking in only seven and this current Max doesn't beats the max so far so this condition comes out to be false now we'll go to the next element which is minus1 so here minus1 will be added to the current Max it will give six so current Max will become six now and now this minus one will see that if I become part of the current sub array which is this I am getting sum as six if I start my own sub array I will get sum as minus one because because this is the only element so it sees that okay it's better to go with the current sub array so this condition comes out to be false because current Max which is six is actually greater than minus1 so here now our current Max is six taking in 7 and minus1 together now this six doesn't beats the 11 so it Remains the Same now we'll increment I so now I will point to the seventh index and here this current sub array has included minus1 with it now we'll simply add the value six which is this value with the current Max so 6 + 6 is 12 so current Max will become 12 and this six also checks that if I start a new sub aray from here what's the sum so this is the only element so sum is six so it doesn't beats the actual current Max so this six decides to go with the current sub array by adding itself to the current Max so this condition comes out to be false because because current Max is 12 and it is greater than 6 so now this element is included in the current sub array so the current Max is 12 taking in 7 Min - 1 and 6 and here you can see that this current Max 12 actually beats the max so far so this condition comes out to be true because Max so far is less than current Max so it means we simply update the max so far which is 12 so this value is assigned to the max so far stating that this sum was made from this sub array it becomes 12 will'll increment I so this for Loop will exit because now value of I is 8 and 8 is not less than ar. length it is equal to ar. length so it means we have traversed this array completely and at the last we will simply return 12 because this is the maximum sum so far created by a sub ARR this 7 - 1 and 6 so this 12 is returned so friends here we saw that there was one sub AR 4 3 - 2 and 6 which actually gave the sum as 11 so this subar was Max so far for most of the time and at the end this sub whose total sum came out to be 12 became the max so far so 7 - 1 and 6 which gave the sum as 12 was the maximum subar sum which we finally returned from this method so friend this is how the cens algorithm work so here one more question arises that why we are actually taking in the negative values in the current Max like we did here we included min-2 and the current Max became five from 7even because here you can see that current max value is five after including min-2 if this value would have been let's say 1,000 so in the next iteration if we have included 1,000 we would have got 1,5 because we will be adding 5 2,000 but if we would have discarded this value so from this part a new sub array would have been started which only would have given 1,000 so we are not sure what next element is coming up so therefore we have included min-2 because this value is less than this value so therefore we have included minus 2 also because we are not sure what is coming up there could be a very large maximum value which would have raised this sum to, 5 and if it would have discarded minus 2 so this subar would have been ended here and a new sub would have started here which only could have given a sum as thousand I hope you must have liked this video and in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so now previous video we saw that how cens algorithm help us in finding the maximum sum of a sub array in a given array we saw the demonstration of the algorithm step by step now in this video we will actually code the algorithm and we'll test its working in the main method so if you want to understand the algorithm more you watch the previous videos to this where the algorithm is being explained in a very detailed manner so let's see the code of the cens algorithm so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here we will be creating one method as public static we'll give it a name as Max sub array sum so this method will take in an array and will return the maximum sum of any sub array so it return type is integer so here codewise this algorithm is simple but to actually understand the concept behind it is very much complex and you can watch my previous videos to it to understand more so in this algorithm we simply create two variables one is current Max and we simply assign the first value to it which is the value stored at zero to index and the other variable is Max so far we also assign it a value of what the first element is holding so here we are assuming that array has at least one element so the algorithm basically starts from second element from I = to 1 and I goes from one two array do length so in our previous video we discussed that when we are encountering the current element this current element basically ask two questions that should I be part of the current sub array which is the current Max or should I start my own sub array so these two questions basically decides what will be the value of current Max so at the start we simply assign array of I to current Max so this is the question one where the element becomes part of current sub array so here we have taken the sum of current Max and the value of the array at aod index so this satisfied question one and we simply assign it to current Max so in the next step we can't directly go with the current max value with this sum this element we also ask a question that can I start my own subarray by taking my own value so here we simply compare current Max with array of I so if array of I is greater than this current Max so it means that this element has started its own sub array because this value has been assigned to current Max so here this is the question two where element decides to start its own subar so after evaluating the current Max what we do is We compare it with Max so far so if this current Max beats our Max so far so we simply assign current Max to Max so far so friends you can watch my previous video to understand more about this logic that usually at each iteration we asked this two questions and based on these two questions current max value decided and if this current max value is greater than Max so far so we simply assign current Max to Max so far and at the end we simply return Max so far because after this value will terminate whatever the value Max sof far is holding it decides the maximum sum of any sub array in this array so now let's test its working in the main method so this is the array which we discussed in our previous video as well in the slide here we'll simply call Max sub array sum method we pass in the array and if I run the main method so here you can see it written the maximum sum as 12 so which is being form by this sub array 7 minus 1 and 6 if we add all of these three values we'll get sum as 12 so friend this was all about the Cadence algorithm I hope you must have like this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day Hello friends welcome to my new data structures and algorithm in Java tutorial series video friends in this tutorial we will discuss the famous Tome problem in Java so here the problem is something like we are given an array of integers and we need to return the indexes of the two numbers such that they add up to a specific Target so if we take an example then let's say we we have this array of integers 2 11 5 10 7 8 and let's say we are given a Target is 9 so we need to return the indexes of two numbers such that they add up to this target so here the problem states that we need to find two such numbers into this complete array which will add up to the Target so if you take the above example then the solution would be the element at zero position is two and the element at Fourth position which is seven so they add up to the Target so we need to return the indexes of it so we need to return return 0 and four so 0o is the index position for the number two and four is the index position for the number 7even so let's move ahead and see the demo of the algorithm so friends let's say we are given the array of integers and we are denoting it with the variable name as numbers so here the array elements are 2 11 5 10 7 8 which we saw in the previous slide and below are the index position of it and if you see the below is the algorithm for finding two such numbers which add to make a specific Target now let's say we are given a Target as nine and we want to find two such numbers which add to make the number is nine so we know that 2 and 7 make up to 9 so in order to find find those two numbers the below is the algorithm for it so let's quickly see the demo of it so as we need to return the indexes of it we will store it in the integer array of having two elements so we need to return the indexes of two such numbers so we'll store it into the result array so it would be something like this so first we'll create a hashmap we'll see see what the significance of the hashmap is so here we are encountering a for Loop which traverses the complete array so in the first iteration I value is zero and numbers. length is six because we have the six integers as 2 11 5 10 7 8 so we'll Traverse this array from zeroth index to fifth index and currently for the first iteration i points to zero so I would be pointing to the zeroth index of the numbers array so friends the basic idea behind this algorithm is like we will Traverse each element one by one and we'll store the element into hashmap with its index value so that on traversing this complete array we'll take a particular number we'll subtract it from this Target and we'll find that whether this contains in the map or not so instead of adding this this two numbers and making it to a Target we'll just subtract that particular number from the Target and we'll look up into this hash map and we'll see whether that particular number is there or not so let's see how it works so here if you see we have this target is nine and we have this number at I portion which is number at I portion is two so what we'll do we'll just check whether the our map contains 9 - 2 which is 7 and into this hash map or Not So currently the map do contains key will comes comes out to be false because the hash map is empty and if you do a reverse of it then this condition in if statement comes out to be true therefore what we'll do we'll just put the number at a position along with its index so moving ahead now I becomes one and if you see the i points to the index at first position and also one is less than six therefore this for Lo will be executed so now we'll again check whether Target which is nine and we'll subtract the number at I position so if we subtract 11 from 9 we'll get- 2 and we'll check whether minus 2 is a key in this hashmap or Not So currently minus 2 is not a key into this hashmap therefore this condition map. contain key comes out to be false and the if you make a reverse of it then it then the if condition comes out to be true therefore the if statement will be executed and we'll simply put the number at a position along with the index value so we'll put 11 and one so 11 is the number at a position and value is the index position which is one so basically friends we are putting these numbers so that we can have a quick lookup into this hashmap and we can come to know that whether whe there is a number whose addition with this current number will make the target as nine so moving ahead so now I becomes two and it will point to the second index of the array so we'll again check whether Target which is N9 minus number at I position so number at I position is five so we'll check whether 9 - 5 which is four is present in this hash map or not so number four is not present in the hashmap therefore this condition map. contains key comes out to be for false and if you do the reverse of it it comes out to be true so the if condition comes out to be true and we'll simply put the number at I position along with the index value in the hashmap so we'll store five with two so five is the number at I position which is two and two is the index value moving ahead now I becomes three so I will point at the third index and we'll again check whether map contains Target minus number at I position so Target is nine and number at I position is 10 so we'll check whether 9 - 10 which is minus1 is there in the hash map or Not So currently it's not there so map. contains key comes out to be false and if we do the reverse of it it comes out to be true so if blog gets executed and we'll simply put the number at a position and the index value in the hashmap so we are storing 10 along with this index value moving ahead so now I becomes four and here it points to the fourth index now friends we'll again check whether map do contains key Target minus number at I position so Target is 9 and number at a portion is 7 so we'll just check with 9 - 7 which is two present in this hash map or not so if you see when we do 9 - 7 it comes out to be two and two is present in the hashmap so it means that the first number is 7even and the other number is 2 so when we do 2 + 7 we'll get 9 so it's like a fast look up into the hashmap So currently 9 - 7 which is 2 is present in the hash map therefore the map do conty comes out to be true and the and if you do a reverse of it it comes out to be false so it means we have found our two numbers which will add up to make a specific Target and now as you want to return the indexes of those two values so first indexes would be the current value of I because 7 is one of the number so we'll store the index value and the result array at the first position moving ahead and we need to store the index of the number two so what we'll do we'll just do a map doget Target minus number at I position so we are simply doing 9 minus number position which is 7 so 9 - 7 which comes out to be two and we are passing the key as two and we are getting the value out of it from the hashmap so it comes out to be zero and we are storing it into the result array so these are the two indexes which we found which is 0 and four and finally we'll just return the result so friend this was the one of the way by which we can find the two numbers whose sum makes up to a specific Target value and suppose if you don't find any number then you can simply either return a result array having the indexes at 0 0 or we can throw an exception like illegal argument exception so friends this was the demo of the algorithm now let's go to eclipse and see the working code so friends let's cotee the algorithm what we saw in the slide so here I have just created one class by name two sum and it has one method the main method so let's say I give the method name as public static to sum so the return type is the integer array because it will return back as the indexes of the two numbers and and the method takes in an integer array which is the numbers array and it also takes a integer by name Target so in this method first we'll create a result array so this result array will store the indexes of the two numbers and then we'll create a hash map which will store the integers as key value pairer so map so we can simply give the name as map new hash map we'll just import it now we'll create the for Loop so we'll iterate the complete array from 0 to numbers. length so this will basically iterate the each and every element in the numbers array so in the for loop our first condition would be if map dot contains key and here we'll provide Target minus numbers at I position so we'll just we'll we'll just check whether the map contains the target minus number at I position key and if it doesn't contain then we'll simply put do put the number at I position within index value and in the else now the else part will come when we have found the two numbers so we'll just populate the result array say at one we'll put the index and at zero position we'll put map do get Target minus numbers at I position and finally we'll just return the result and if suppose we haven't found the two numbers then we can either throw an exception we can throw an exception say illegal argument exception the string is two numbers not found so friend this is the code for finding the two numbers which add up to make a specific Target now let's see is working in this main method so here first we'll create the numbers array so I will populate the values I had given in the slide 2 11 5 10 7 and 8 now s and result array will be return return therefore created integer array variable by name result and I will just call two sub method by providing the numbers array and let's say we give Target as 9 and let's say we print both the indexes so the two indices are result zero plus result at one position so friends let's run this Java code so friend you see the two indexes are 0 and four so at Zer we'll we'll find a number having the value is two and at index four we have found seven so if we add 2 and 7even we get the value as 9 so friend this was a tutorial about two some problem I hope you like this video please like comment share and subscribe my YouTube channel thanks have a nice day hello everyone so in this video we will be discussing about the two sum problem in Java so in one of our previous video we have actually seen the solution to two sum problem where we used a hashmap so in this video we will be looking into yet another approach to solve the twm problem so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here if you see we are given an array of integers let's say having different values 2 11 5 10 7 8 now the integers in this array are not repeated and we are also given a Target let's say 9 so in this problem we have to write a function where this array and this target will be given one and we want to return return a pair of numbers such that they add up to a specific Target which is N9 so here if you see 2 + 7 will give the value as 9 which is equal to our Target so we need to Simply return return 2 and 7 in a form of integer array so let's move ahead and see the demonstration of this algorithm step by step so here's the algorithm which we will be using to find the pair of numbers which is equal to our Target so the method name is two sum it is taking in an array and a Target and it is returning an integer array so at the first step we usually call two Su method by passing in the array and the target is nine so this method will start its execution this is the array having values as 11 2 0 10 7 and 6 so these are six elements from index 0 to 5 and the target we are providing it as 9 so we want to find a pair of number such that if we sum them we get the value 9 moving ahead so here if you see has this numbers are in random order so in order to find the pair 2 and seven which will be resulting to our Target we have to compare each element of this array to another element but doing so will be the timec consuming algorithm so what we do in the first step is we try to sort this array we will see its significance later so after we sort this array here you can see the elements are are arranged in ascending order 0 2 6 7 10 11 moving ahead now we'll see the significance that why we sorted this array so in order to solve this problem what we actually do is we actually take two pointers one is the left pointer and one is the right pointer so the left pointer usually points to index zero and the right pointer usually points points to the last index of this array so here if you see we will be creating a variable left we'll assign a value zero to it so this zero signifies the index so it would look something like this that left is pointing to index zero moving ahead we will create a right variable we'll assign the value as array do length minus one so if if you see array do length value is six and if we do minus one we'll get five so right will point to fifth index moving ahead now what we do is as we want to return the pair so we create a result array which will only take two values so this is the result array so by default the values will be 0 0 because we are taking the integer array moving ahead now here we actually did two things first we sorted the array in ascending order then we created two pointers left and right now what we do is we provide a while loop and inside this Val we provide a condition as left should be less than right so here if you see left is at zeroth index and right is at fifth index so left is less than right Now using these two pointers what we do is we try to find out the pair so first number will be denoted by left and second number will be denoted by right so these two pointers will help us in pointing both the pairs so the condition is left should be less than right in the while loop so at the start this while loop will execute because left is less than right now at the first step what we do is we take the value associated with the left pointer and with the right pointer and as we want to find the pair sum we usually do their sum so here if you see we do 11 + 0 which will give us 11 so sum will be 11 now what we do is we try to compare our sum with Target to Simply check that whether sum is equal to Target or not so here if you see Target is 9 and our sum is 11 so 11 is not equal to 9 it means this is not a valid sum so basically when we do this comparison there are three possibilities sum is equal to Target sum is less than Target or Su is greater than Target so sum is not equal to Target so the else part will be executed and now here we will be checking whether sum is less than Target or not so here if you see sum is 11 and Target is 9 so 11 is not less than Target now why we have provided this condition is because so here if you see that when we sorted this array in ascending order now the advantage will come into picture at these two steps so if 11 is not equal to 9 which means sum is not equal to Target so there are two possibilities either sum is less than Target or some is greater than Target so here currently 11 is greater than Target and as we have this array in sorted form in ascending order we know that we need to reduce this sum by two or whatever value so that it is equal to 9 so we have two choices either we Traverse left this side or we go right this side so here you can see if we go left this side we will get a value greater than zero and if we go in this direction to right we will get a value which is lesser than 11 and we want to reduce this sum so here we can't go in this direction by moving left to this position because in the next iteration when we will do sum we will get 11 + 2 which will give us 13 2 and 11 will give us 133 and 13 is way more far than 9 so we have only one choice to make that we reduce the sum by moving right into this direction so here these are the two checks which we perform so sum less than Target so this condition comes out to be false because sum value is 11 and Target is 9 so the else part will be executed where you will see the significance that why we are doing right minus minus because we need to shift right to this position which means from fifth index we need to move to Fourth index so we'll simply decrement value of right so it would look something like this right becomes four and now it will point to the fourth index I'll simply remove this now again our execution point will reach here we will check whether left is less than right or not so left is less than right so the while loop will execute we will again calculate the sum by taking in the values at left and at right pointers so now our values would be 0 + 10 so these are the values it will give us a value of 10 so sum will become 10 now we'll compare sum to the Target so here we can see that sum is not equal to Target so the lse part will be executed we will again check whether sum is less than Target or not so here you can see 10 is greater than 9 so therefore this if condition will come out to be false because we can't move left to right because if we move left to right then we'll get a value which will be more than 9 which is like 10 + 2 which will give us 12 which will make us more far from the target so what we do is we simply shift right by decrementing it by one position because we know that as the array is sorted if we move right to this position we will get a number lesser than 10 so the else part will be executed now right will Point 23 which is the third index we'll again check in the while loop whether left is less than right or not so left is less than right we'll again do the sum so this time it would be 0 + 7 which will give us value 7 so sum becomes seven We compare sum with the target so sum is not equal to Target now again our lse block will be executed so here you can see now that sum is actually less than Target so initially sum was actually greater than Target so we moved right pointer in this direction because we wanted to decrease the actual sum but now sum is actually less than Target so what we need to do is if we move again to this point so when this while loop will execute again we will get 6 + 0 which is like we are going to a more lesser value than Target so if sum is less than Target we need to increase the sum so that we reach the target so the only way we can increase the sum is by moving left to this point because we know that here it value is z and this array is in ascending order so whatever value we'll get after that will be greater than zero so this condition is for that so LF part will be executed and we simply increment left by one position so left becomes one now it will point to the first index moving ahead we will check whether left is less than right or not so left is less than right we will take their sum at their respective indexes so it will be 2 + 7 which is 9 so sum will become 9 so friends here you can see now sum is equal to Target so it means we have reached to a point where we can simply return this pair because we have found a pair whose sum is equal to our Target so this is block will be executed because this condition came out to be true so in the If part what what we do is one value is two so we'll simply assign the value stored at left pointer to the zeroth index of the result so this two will come here and then we'll simply assign the value stored at the right pointer to the first index of result so here 7 will come to the first index so we have found our pair which is if we do the sum of 2 + 7 we will get 9 which is the value equal to our Target so at the last step we will simply return return the result integer array so friends here you saw the significance that why we sorted the array because if the array is not sorted then we need to compare each element with every other element so this would have given us a Time complexity of O of n² which is are not a good time complexity so we actually sorted the array so that we know that the first element is the smallest and the last element is the largest so when we do the s in we usually go to n log and time complexity and then using this V Loop we simply do one iteration and we find the pair using this two pointers because as the numbers are sorted left starts from here and right starts from here and then we simply take these values stored at right and the left pointer we do their sum and we try to compare it with our Target so if the sum is less than Target what we do is we simply shift left by 1 position we simply moved right to this direction by incrementing or decrementing respective variables so friends I hope you have likeed this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thank thanks have a nice day hello everyone so in our previous video we saw an animation that how we can solve the two some problem in Java now in this video we will actually code the algorithm and we'll test its working in main method so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that I have created one class as array util and in one of our previous video we saw the two sum problem in that video we discussed one of the solution to solve the two some problem we basically took the help of a hashmap and we solved the problem now in this video we will see one more way to solve this problem so let's suppose I create one method here [Music] as public static two sum two because we are discussing the second approach here so this method will take in an array where we will be provided with different numbers and those numbers will be unique and we will be also provided with a Target and usually there will be one such pair which will be equal to the Target so we need to find that pair and after finding that pair we'll simply return return it in the form of an array of length two so in our previous video we discussed that how we can solve this problem we took the help of sorting and two pointer approach so the first step we do is we sort the array so using arrays. sort we will pass in the array so we'll get the sorted array so here you can see this arrays class in Java has a sort method where if we provide the array we get the sorted array in ascending order so here you can use your own sorting algorithm or we can use the Sorting algorithm provided by Java now after sorting this array what we'll do is we create two pointers one is the left pointer which starts from zero index of this array and one is the right index which usually start from the end of the array so if you want to know the last index of an array what we can do is we'll simply call array do length so this will give us complete length and if we do minus one we'll get that particular index because array starts from zero index and goes to ar. length minus one index now after creating these two pointers as we want to return the pair of numbers whose sum is equal to Target we will create an array we'll name it as result and this array will be of size two because it will take two numbers now after creating this array we have this two variables left and right now these two variables will help us in finding that pair of numbers whose sum is equal to the Target now here we will provide a while loop and as left is starting from zeroth index and right is starting from the last index this Val Loop Will Go On Till left is less than right if left becomes right then we'll simply break from this V Loop so in the while loop what we'll do is we'll first calculate the sum of the values stored in the left and the right index so we'll do array of left plus array of right now in our previous video we discussed that after calculating the sum we try to compare it with the target so there are basically three possibilities so the first possibility is if sum is equal to Target it means we have found our Target and we'll simply store the both the values array of left and array of right into this result and we'll simply return the result so here what we'll do is result at the zero index we'll simply store array of left and at the first index we'll store array of right because these two are the numbers when we did the sum of it it became equal to our Target so we are storing both these values into the result array and here we are simply returning result now this is the first condition when sum is equal to Target there could be two more [Music] condition that some could be less than Target or sum could be greater than Target so friends here is the significance that why we actually sorted the array if our sum is less than the target then what we do is we need to increase our sum in the next iteration so here we simply increment left by one position so let's say if I take this example here let's say the sorted array comes out to be 0 2 6 7 10 11 so here you can see left will be pointing to zero and right would be pointing to 11 so if we do sum of it we will get value is 11 and let's say our Target we want is 9 so here we know that 0 + 11 which is our sum is greater than Target so what we do is we need to reduce the sum so we have two possib it is either we Traverse left towards the second value or we can Traverse right towards the second last value so here currently sum is 11 but if we Traverse left to the second position in the next iteration our sum will become 2 + 11 which will give us 13 so we are going way more far than the target so here our only possibility is we move right to the second last position because in the next iteration if we do the sum we will get 10 + 0 which would be 10 so 10 is pretty much close to the Target so these are the fs provided for that so if sum is less than Target then we need to increase the sum so that it matches Target and the only way to increase the sum is by incrementing left so that left can go to the higher values and if sum is greater than Target then we need to reduce the sum so for that what we need to do is we need to decrement right because as the array is sorted if right is pointing here let say to 11 if it goes to the second last position we will get a value which is lesser than 11 so here we'll do write minus minus so after this Val will terminate what we can do is we can simply return [Music] a dummy integer array or we can throw an exception like we did here the two numbers not found so now let's test it working in the main method so let's suppose we are provided with this array and here what we do is we simply call two sum we pass in the array and let's say we pass in the Target is nine and we'll simply print the array so if I run the main method now so here you can see it returned two values 2 and 7 so if we do 2 + 7 we will get our Target as 9 so friend this was all about solving two sum problem using the sorting and two-p pointer technique I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel thanks have a nice day hello everyone so in this video we will be discussing a subsequence problem in Java so so first we will see what is a subsequence so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so usually a subsequence of a string is actually a new string which is formed from the original string only and how it is formed by deleting some or no characters and only thing to keep in mind is we should not change the order of the remaining characters so what it means now let's see by example let's suppose we are given with the original string a b c d e and we are given a sequence a c e now we have to find whether a c e is a subsequence of a b CDE e or not so so here you can see if we delete b and d and we don't change the order of the remaining elements we actually get a c and e so therefore a c e is a subsequence of a b c d e if you look into a e c so it is not a subsequence of a b CDE e so here a e c is is present in a b CDE e but if we remove B and D the remaining characters doesn't form a e c it actually forms a c and e so the only thing we need to keep in mind is the order of the elements shouldn't get changed so here C is actually coming before e but here e is coming before c so therefore the order of the element has changed so therefore a e c is not a sub sequence of a b CDE now if suppose we were given a string as a b c d e so here you can see by deleting some or no characters so if we were given this string this string also is a subsequence of a bcde because we are not removing any characters and we will be getting the same string back so this is a subsequence of ab bcde so one other way to look into subsequences we simply see in this direction in both the string and we see whether those characters come into this order only or not so here first we encounter a and here we see we have got a so we move ahead now we see C so here is B so we simp L move ahead we encounter C so we simply move ahead we see e and here we see D so we simply discard it and we move ahead and at the last we find e so therefore AC is a subsequence of ABCDE e now here we see a a so we move ahead we go go to E we go to B so these two are not equal so we discard it we go here we see e and C we discard this we go here we find D and E we discard this we come here we find e so e and e matches so now we move here but here you can see complete string is exhausted and there are no more elements therefore we come to a conclusion that a is not a subsequence of ABCDE so we will be applying the similar algorithm to solve this problem so here you can see this is the algorithm where we will be provided with the original string and a sequence we need to Simply find out whether this sequence is actually a subsequence of this string or not so let's see the demonstration of this algorithm step by step so we'll call a subsequence method by passing in two strings one is the original string and other is the sequence and here you can see the return return type of this method is bullion so we will either return return true or false so at the First Step A B C D is our string and the sequence is a c e so we are figuring out whether a c e is subsequence of a bcde or not so this is our original string and this is the sequence so here you can see that we have represented a string in a form of a character array so in Java string class has this method character at where we pass in an index and we get a particular character present at particular index IND X so if we pass one we will get the character as B so we can use this method to Simply get a particular character at a particular index we can also use two care array method which actually gives us the character array and then we can perform our Logic on this character array but here I will be simply using this carat method and we will see the string in a form of a character array moving ahead now what we discussed in our previous slide that we simply look into this direction in both the string so for that we create two pointers I and J so I will simply Traverse into the original string and J Will Traverse into the sequence now we want to Simply check whether a c e is present in this particular order into a b CDE or not so for that we have provided a while loop where the condition is this while loop will continue till I is than String's length so your string length is five and J should be less than sequence length so here I will be traveling from 0 to 4 and J will be traveling from 0 to 2 because the length of the sequence is three so this is the condition we need to keep in mind so why we have provided this condition is I should be less than string do length is so if I goes beyond the length of the string then we need to break from this V Loop because there are no more characters left to be compared and similarly with the J if J travels beyond the sequence then it simply signifies that we have found our sequence and we should simply break from this while loop because the original string can have n number of elements and as we have found our sequence we should break from this value because we don't want to go further into the string so at the start I is less than 5 and J is less than three so this condition comes out to be true the first step what we do is we simply compare the character at I index with a character of the sequence at jth index so it means we are simply comparing this character with this character so J is pointing to sequence so and J is also referring to the index zero so this character is compared with this character now if they are equal So currently a is equal to a so this condition comes out to be true now what it signifies is one of the sequence character has matched so now we can safely move j to the next index so we do j++ so J becomes one moving ahead and after that we do I ++ because now our second character should match with the rest of the string which is this because this is already being matched so we do I ++ so I points to index one moving ahead I is less than 5 as 1 is less than 5 and 1 is less than three because J is pointing to one so both condition comes out to be true we again check whether character at I index of string is it equal to the car at J index of the sequence so it simply means we are comparing B with C now here you can see B is not equal to C therefore this condition comes out to be false now as this condition comes out to be false we don't increment J because there could be a possibility C might come out later in the string so therefore condition in this comes out to be false and we only increment I so we don't touch J we only increment I so I becomes two so I'll just remove everything now we again check whether I is less than 5 so this condition comes out to be true and we also check whether J is less than three because sequence. length is three so both this condition comes out to be true we compare the respective characters at I and J index so here we are comparing C with C because I and J are pointing to these two indexes so here you can see C is equal to C so this condition comes out to be true it means our second character actually matched with the character in the original string so we'll simply increment now J by one because because we have matched our character and now we simply move to the next character so J becomes two and we'll increment I because this character is already matched so I becomes three now here 3 is less than 5 and 2 is less than 3 so both condition comes out to be true we compare the characters at these respective indexes so it means we are comparing now D with e so here you can see D is not equal to e therefore this condition comes out to be false and we don't increment J and here as we discuss why we don't increment J because later in the string there could be e coming up so here you can see e is here but but if here the character would have been different so there could be a chance that e might have come later so we don't increment J we only increment I so I becomes four so I'll just remove this so 4 is less than 5 this condition is true and 2 is less than three so this condition is also true we'll compare e and e which is this character with this character so this comes out to be true so we'll increment J because because our character is mashed so J becomes three it means now J has crossed the limits of sequence moving ahead we'll increment I so I becomes five it means I is also crossed the limit of the string so now here going see value of I is 5 and 5 is not less than 5 so this condition comes out to be false so the overall condition comes out to be false so this V Loop will exit so friends here at the last step this condition is pretty much important because if value of J is actually equal to the sequence length it means J has traversed the sequence complete and we have found our element So currently J value is three and sequence length is three so 3 is actually equal to 3 therefore we will return true because J is equal to sequence. length and this expression returns true S 3 is equal to 3 Because when J will equal to the length of the sequence it means it has traversed a c and e completely so here we are returning true so now we'll see one more example let's say we call AB c d with a sequence a e c so we'll go over this example quickly I is zero and J is also zero here string length is five and sequence length is three both the condition comes out to be true because I is less than 5 and J is less than three We compare the characters at the respective indexes of their respective strings so we are comparing a with a which is true so we'll increment J J becomes one and we'll increment I so I will become one both this condition is true because I is less than 5 and J is less than 3 we'll compare B with e by this expression so B is not equal to e so this condition comes out to be false we won't increment J because there could be possibility e might lie somewhere after B so we'll only increment I I becomes two both the condition comes out to be true I is less than 5 and J is less than 3 we'll compare C with e now so this condition comes out to be false we'll increment I I becomes 3 I is less than 5 and J is less than 3 we'll compare D with e so they are not equal so we'll simply again increment I I becomes four I is less than 5 J is less than 3 now we'll compare e with e so they are actually equal so it means the F blog condition came out to be true so we'll increment J so J becomes two and will increment I so I becomes five so this is the important moment this I has become five it means I has crossed the boundaries of this string so here value of I is five and string length is five so therefore this condition comes out to be false so this V Loop will exit so friends here you can see now value of J is 2 and sequence length is three so this condition is very much important to figure out whether all the characters of the sequence were traversed or not so here you can see J is 2 and 2 is not equal to 3 therefore a e c is not a subsequence of a b CDE e so we'll simply return false so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel thanks have a nice day hello everyone so in our previous video we discussed the problem of is subsequence where we were given two strings one was the original string another was a sequence and we need to find out that whether that sequence is actually a subsequence of that original string or not so before going through this video you watch that animation so that you get an idea that how we can find out that whether a sequence is a subsequence of any other string so in this video we will actually code the algorithm and will'll test it working in the main method so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that I have created on class as string util and inside that class we will be creating our method public static we'll give it a name as is subc Quin now this method will take two strings one is the original string and another is the sequence so we need to find out whether this sequence is actually a subsequence of the string or not so the return return type would be a Boolean so in our previous video where we saw the animation we actually used the two- pointer technique where we created two pointers i n j so I usually Traverse the string and J Traverse the sequence and usually we Traverse both from left to right and we simply try to compare the character present at that particular index which is being denoted by I and J into their respective strings so we provide a while loop and inside this V Loop we provide the condition as the this value Will Go On Till I is less than String's length and J is less than sequence length because as we are traversing this two pointers from start to finish if any of the pointer crosses the limit of their respective strings we simply break from this V Loop so inside this V Loop we simply compare the character at I and jth index of their respective strings so here we do if carat I is it equal to sequence. carared J so if they are equal so here let's say if we take the string as a b c d e and let's say we take the sequence as a c and e so here you can see that J starts from zero and I starts from zero so we are simply comparing the first element if they are equal it means we have found one of the character of the sequence into the original string so we simply increment J by one because now we try to compare the next element into the original string and after this if block we always increment I by one position because we have matched this character with this character now c and e will be compared with the rest of the string so in the next iteration you will see that b is compared with the c via this condition so this condition comes out to be false because B is not equal to C so we don't increment J we only increment I because there could be a possibility that c might come later in the string because we are trying to find out the subsequence here so we always increment I in respective whether we have found our element or not because if we have found our element here then we increment I because we have to compare the rest of the sequence with the rest of the original string and if we don't find the matching character which is here where we are comparing B with C so this condition comes out to be false so we try to only increment I because there could be a possibility that next character should match with the sequence character at J index so this Loop goes on and at the end what happens either this condition comes out to be false or this this condition comes out to be false or both condition comes out to be false so this while loop will terminate so after this while loop will terminate we simply return is J is equal to sequence do length or not so why we are doing this is because let's say if this condition comes out to be false it means J is equal to sequence. length which signifies that if J is equal to sequence. length we have found our subsequence we have found that this sequence is actually a subsequence of this string because we have traversed each and every element and we have found them to be true and at the last increment of J it will actually reach to the sequence do length so if J is equal to sequence. length it means this sequence is actually a sub sub sequence of our original string and let's say friend if we provide a e c so this a would have matched with this a this e would have matched to this e and after that J would have remained to C because our original string would have been exhausted here as I would have become equal to string do length so at that moment of time this condition would have come out to be false which says that a e c is not a subsequence of ab bcde so friend this is the algorithm which help us in determining that whether any sequence is a subsequence of the original string or not so now let's test it working in the main method here we will simply print is subse sequence let's say we pass the string as a b c d e and we pass a c and e if I run the main method now you will see it came out to be true now let's say if I run it with a e n c so it came out to be false so why because a though it's present in s AB BC D but the order of elements which constitutes the property of subsequence is not matched here you can see C is coming before e but here e is coming before for C therefore this cannot be the subsequence of this string because the order matters in the subsequence so friends I hope you like this video and in case if you're new to my channel then please subscribe to my channel thanks have a nice day hello everyone so in this video we will be discussing first non-repeating character problem so this is a very famous interview question which is being asked by many companies so we'll see what this problem is and we will see the demonstration of this algorithm step by step so here you can see that we are given a string s which only has lowercase letters now we need to return return the index of first non-repeating character first non- repeating we mean is the unique character which occurs first and if it doesn't occurs or doesn't exist we can return minus one so we need to return the index let's see with an example suppose the string provided is code for code so here you can see the answer is fourth index the first non repeating character is f and is found at index 4 so let's see how we actually Traverse the string from left to right because we need to find the first non-re repeating character so here you can see if you see c c occurs here as well so this is not a unique character we check o is here and here at three places so o is also not unique we see d d is here and here so D is also not the unique character or first unique character e is here also so e is not the first unique character now we see F so here you can see f is not present in the rest of the string so f is the first non-re repeating or unique character in this string and the index is let's say 0 1 2 3 4 so four is the answer now let's suppose we have provided with string as a a b b so here you can see a occurs twice and B is occurring twice so it doesn't have any non-re repeating character so we simply return minus one now let's see the algorithm for it and its demonstration step by step so here you can see this is the algorithm to solve first non-re repeating character problem so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here let's say we call this method first non- repeating character we pass the string as race cars so here the string is race cars something like this so friends the basic idea behind this algorithm is we actually take the help of a hashing data structure which is a hash map which basically has key and value so your key is unique which is is our character and the value is a integer which will actually hold the count of the character occurring in the string and why we are taking a hash map is because if you see somewhere here we are doing get now this get operation when we pass any character will return return as the count for that particular character and this happens in O of one time if we don't use hashmap then the algorithm will take multi mple for loops and will increase the time complexity so therefore to get the character count very fast we use this hashing data structure which is our hashmap so we'll see its significance when we see the algorithm step by step so first we will create a map having key and value of type character and integer so here I am simply demonstrating it as key value pair but internally this map uses a hash function to store this key value pair such that the retrieval becomes faster you can watch my videos on hashing data structure and hashmap but here I will be simply demonstrating it with the values so here we have the string race cars now what we do is as we need to find out a single character which is first non- repeating we first take this string we call two care array method on it and and this will return us a character array so this method is present in a string class so it would look something like this that we have got our character array where this array at each index holds one character like this moving ahead now what we do is we iterate over each and every character one by one and we put it the character into the map and we put it such a way that if that character is not present we put one and if the character is present we take that Value First and we add one to it so we'll see how this line works but here you can see that we are putting the character because key is the character and as the integer what we are doing is we are calling hashmaps method get or default so when we do map. get or default if this character is already present then its corresponding value is returned and we simply add one to it and we put it back into the map and if the character is not present then we return a default value so it's like get or default so for the default value here you can see we provide zero which signifies that the particular character if it is not present in the map it means just return the count as zero and while we are doing plus one and putting it back into the map you will get more when we'll see the working of this for Loop so here this for Loop will iterate each character one by one so it will start with r here we will put R and here you can see the map is empty it doesn't have R so the default value of 0 is return and when 0 is return We do+ one to it so it becomes one and we put it into the map so here it would look something like this we put r as our key and value as one so this one signifies that character R occurred one time as we are traversing from left to right so at this moment R is occurred one time so therefore we are returning this zero because we are adding one to it so if R again comes up we will do map do get or default we will get actually one because R is already present as a key so we we add one to it which means the count of R is two we extracted one and we added one to it so the count became two and if the value is not present we add 1 to the zero and put it back into the map moving ahead now it will pick the second character which is a it checks whether a is present or not so a is not present in the map so it simply Returns the default value zero we add one to it and we put a as a key and value as one so it goes like this it takes C now and similarly it puts c as a key and one as a value because C is also not present in the map so get or default will return zero as a default value now takes the fourth character which is e we put e also as one because the count is still one now take C so here you can see when we will do map. get or default now this time zero won't be returned because C is already present and with a value as one so this one will be returned and we'll simply do + one and we put C with value as two so this complete expression gives us two for C so here it becomes two and which makes sense because till this point we have encountered C two times so we are simply storing the frequency of the character in the value field moving ahead now it will pick a a is also present so it will take this value it will add one to it and it will insert it back so it will become two it will pick R so R also becomes two and at the end it picks s so here s is not present so therefore the default value Zer will be return we do + one and we put s with one so now this for Loop will end so friends here you can see this is the character frequency map so why we have done this is to Simply count the number of occurrence of a particular character so here you can see R occurred two times here and here a occurred two times here and here c one here and one here and e and s occurred only once here and here so now the next for Loop will help us in deciding which is the first non-re repeating character so here we will again iterate the car array from zero index to the end so initially I is zero and I is less than C do length which is8 so car do length is 8 so we pick the first character we provide the index zero so R will be picked and now we'll simply call map doget and we pass the character so when we do map doget we will get its corresponding value because we are passing in the key and this map will return us back the value associated with this key and that to an O of one time which is very fast so that's why we were using hashmap so here when we do map. get R we will get the value as two so here you can see 2 is not equal to 1 it means R cannot be our first non repeating character because it has value two so we move ahead with the next character I becomes 1 1 is less than 8 we take take the next character which is a at index one because value of I is 1 we do map. get a so we pass in the key as a and we get value as two it means a cannot be our first non-re repeating character we move ahead I becomes two 2 is less than 8 we pick C now we do map. get C we get the value as two 2 is not equal to 1 so therefore C can't be our first non- repeating character because it has value two it means it has occurred two times we'll increment I 2 three we'll pick now e now here you can see when we do map. get e we get a value as 1 so 1 is equal to 1 it means this condition comes out to be true and which signifies that we have found our first non-repeating character because we were traversing this for loop from this end and whichever value we found to be one we simply return its index so here whatever the value I will have we simply return it back so the answer would be three so now let's see this example one more time with Valu is ABAB so we'll quickly go over it string is ABAB we create a hashmap like this we convert this AB a into character array by calling two care array so it comes out to be like this now we literate each and every character and we put its frequency as a value in this hashmap so we start with a we check whether a is present or Not by this it is not present so we return the default value as zero whatever value is return we add one to it and we put a into the hashmap so the value would be one signifies that a has occurred one time we go with the B and similarly B will have one because B is not present in the map we take a and we see a is already present so we get this value out we add one to it and we put it back so 1 + 1 will give two and and we put two back into the hash map we take the last character B we see B is also present so we do 1 + 1 and add it back so occurrence of B is also two now this for Loop will end so here you can see looking into the hash map a occurred two times here and here B occurred two times here and here so here we can see that in this string no character has appeared once so this for Loop will help us and figuring that out we will start with i equal to 0 index we go till car. length so car do length is 4 0 is less than 4 we take first element which is a so we do map. get a we pass the a we get value as two so here we can see that 2 is not equal to 1 so this condition comes out to be false we increment I I becomes 1 1 is less than 4 we take the first index character which is B I'll remove this we do map. getet B we pass the key B we get value as two so here here 2 is not equal to 1 so this condition comes out to be false I becomes 2 2 is less than 4 now we take the second index value which is a we do map. get a it returns 2 2 is not equal to 1 this condition comes out to be false and similarly we do for the last character we take B we do map. gr B it will return two 2 is not equal to 1 so this condition comes out to be false so here now I will become four and four is not less than four so this for Loop will end and once this for Loop will end if we haven't written anything from this condition at the end we know that there are no characters in this string which are unique so we simply return return minus one so friends here we saw two examples in one we found the first non-re repeating character and in other we didn't found any non-re repeating character so if I go to the previous slide so here you can see that when we did race cars we actually saw that e and s both had a count one but here e occurred before s so therefore this e was the first non-re repeating character not s so this is one thing we need to keep in mind that we need to find first non repeating character I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw the detailed demonstration of the algorithm to find first non- repeating character in a string where we were given a string in lowercase letters and we wanted to find the index of the first non-re repeating character in it so in case if you want to understand more you can watch my previous video so in this video we will actually code the algorithm and will test it's working in the main method so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here in string util class I'll be creating the method as public static we give the method name is first non repeating character so this method will take a string and it will return the index which is of integer type for the first non-re repeating character so friends here in order to find the first non-repeating character we first it iterate this string completely and we figure out the character frequency that how many times a particular character has occurred so for that we are using the map whose key is character and value is integer which is the count of that particular character that how many time it has occurred so we can give it a name as character frequency map new hashmap now we want to iterate each and every character of the string one by one so for that we take the string and we convert it into character array by calling two care array method then we provide a for Loop so here we will iterate one one character in each iteration now here what we do is as we want to count the character frequency that how many times it has occurred what we do is we do character frequency map dot put we put the character as key and the value we put is we first check that whether this character is present in the map or not so we do it by Method get or default we pass the key to it if that character is present the value corresponding to it will be returned and if that character is not present so we can return a default value because the method is get or default so we need to pass the default value to it which is let's say if the character is not present we want it should return zero so here you can see default value is zero and what we need to do is let's say if the string has a character a which is not present so here we have encountered a so we need to put the count as one because a has occurred once so we'll do plus one to it and let's say next time for example let's say our string has something like a b a so for this map will have a as a key and value is one now when this a will again occur so this get or default will return the previous value which is one and we will add one to it so now map will have a as a key and value is two because a occurred two times so this we do for each and every character and after doing that we provide another for Loop and we iterate this car array once again and now as we want to find the first non repeating character and we are starting from zero to index so whichever character value in this character frequency map will have one it means when we Traverse this character array completely that particular element was the one which had only occurrence one and which was the first non- repeating character so here what we do is we take the care from the a index we provide a if check if the character frequency map we do get we pass the character and if the value returned is one it means this is our character which is first and non- repeating so we simply return its corresponding index which is I and if we don't find any such character whose frequency is one then at the end we simply return minus one so now let's test it's working in the main method here we will call first non- repeating character let's say we pass the string what we saw in our previous video race cars so here you can see it should return 0 1 2 3 because e is the first non-re repeating character why because R A and C have occurred two times in this string so if I run this so here you can see it return return three and let's say if we put a string which doesn't have any unique character so here a has occurred three times B has also occurred three times if I run it it should return return minus one and let's say we provide a value here as e so now we have e as a character which has occurred only once and it's the first non-re repeating character so if I do run it we will get its index as 6 because 0 1 2 3 4 5 6 so E is at 6 index now let's say if I do in between I do F so now now f is our first non-re repeating character because e comes later so now it should return three so it comes out to be three so 0 1 2 and 3 so friend this was all about the algorithm to find the first non-re repeating character in a string I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we will be discussing a problem that how we can remove vels from a string so here we are given with a string and we need to remove the vels from that string and return that string and the string only contains the lower G letters so if we talk about vowels then there are five vowels a e i o u so let's suppose we are given with this string what is your name so the output would be this A I O U A and E this will be removed because those are vels and this string will be written like this so now let's see the demonstration of the algorithm step by step that how we can remove the vels from a string so before we start in case if you new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here you can see that this is the algorithm to remove vels from a string so now let's see the demonstration of this algorithm step by step with the example so we'll call remove WS method we'll pass the string as ice cream so your string would be ice cream so here you can see that it has vels like i e e and a so here in order to remove the vels from this string we take each character and we see whether it's a Vel or not so for that first we create a set which we denote as vowels and this set will only have the characters so this is a set of a e i o u and why we are taking it as a set because here you can see that we are using for Loop we are iterating over each character of this string and we are checking whether this particular character is present in in this Vel set or not so this contains method is very fast and it has an average time complexity of O of one which is nearly constant so therefore we are using set in order to know more about set and hashing data structure you can watch my series on hashing so after creating the Vel set we will be creating a instance of string Builder now why we are making string Builder is because when we will be removing the vels from this string we will be creating a lot of intermediate strings So to avoid that we are basically using string Builder so string Builder class is provided by Java which actually deals with the operations perform over the string and which help us in generating a string without giving a performance hit moving ahead now this string has a method to two care array in Java so when we call this method we will get a character array so this ice cream will be separated out in a form of a character array so it would look something like this that this is the character array going from index 0 to 8 because it is taking ice cream one single character at a time so now we'll Traverse each and every character one by one using this for Loop so this for Loop tells that iterate over each character present in the care array so when this for Loop will start CH which is the character it will point to the first character which is I so CH is I so we take this character and we search into our Vel set that whether it contains CH or not not so here you can see Vel set has character I so it means this is a Vel and we don't want to include this into our final string so what we do is here you can see the condition as vels do contents will come out to be true and if we negate that it will become false so this condition comes out to be false and we will simply skip I because it is a Vel so now we'll go to the second character which is at index one so CH will become C we check whether C is present in the Vel set or not so vels do contains will return false because C is not present and if we negate that this will become true it means C is not W so we need to include this C into our final string so this condition comes out to be true so string Builder has a method append where we will simply append the character C so it would look something like this that c comes into the string Builder moving ahead we'll go to the third character which is e now e is a Vel so vels do contains e will come out to be true and this condition after negating becomes false so therefore we will skip e because e is a vowel moving ahead now the fourth character is actually empty string or a blank character so CH will point to this empty thing or space so this condition vels do contains will come out to be false and if we negate that it will come out to be true because this is not a Vel so we will include this so we'll simply append the space moving ahead the fifth character is C so we'll simply include this because C is not a Vel so C gets appended now sixth character is R so vels do contains R comes out to be false because R is not a Vel if we negate this overall condition comes out to be true it means R is not a Vel and we need to include this so we'll simply append R the seventh character is e so e is a Vel so vels do contents will return true and if we negate it this condition will become false so will simply skip e because e is a vowel now we will take the eight character which is a a is a vowel so we need to skip it and at the last we will take M so m is not a Vel so this this condition is false and overall condition after negating becomes true so we need to include M because m is not a Vel so we have included M and after M there is no more character left so this for Loop will terminate so here you can see at the end whatever we collected into our string Builder if we do two string we will get a string like this and we'll simply return it from the remove WS method so friends in this video we saw the algorithm to remove WS from a string we took the help of the set and string Builder to remove the vels and return the final string without this vels I hope you must have liked this video and in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in our previous video we saw an animation and we discussed the problem that how we can remove the vels from a string so in this video we will be actually coding the algorithm and we'll test its working in the main method so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here we have created on class as string util and inside that class I'll will be creating one method as public static we'll give it a name as remove vels this method will take a string and this method will return back as a string without vels so the input is a string with vels what we get in return is a string without vels so here basic idea behind this algorithm is we iterate over this string character by character and we figure out that which character is Vel and which character is not so how can we figure that out first we will create a set of vels using set. off method now this method will simply take the characters so we can provide the vels as a e i o u also here this string will only only contain the lowercase letters so we have only provided the lowercase vels now after creating the set of vels what we can do is we will create string Builder class so this string Builder class will help us in creating the string which we want to return and this string Builder class is performance efficient it has many utility methods by which we can manipulate the string now in order to iterate the input string character by character what we can do is we will call two care array method now this method basically return us a character array so after getting the character array we will provide a for Loop where we will simply iterate over each character one by one so what we do is we provide if condition if vels contains the character so if Vel contains the character it means this character is actually a Vel and we don't want to include it but if it is not a Vel then we need to include that character into our final L string so here what we do is we do the negation of it so if character is present into this set this will return return true and if we negate it we will we are simply skipping the W and let's suppose character is something like c b j k for example when we will call vels do contains this let's say C so it will return false this condition will come out to be false and if we negate it it becomes true which means that if there is C then we need to include that into our string so we'll simply append the character to our string Builder class so basically when we will encounter any Vel this part will be skipped because ws. contain will return return true and if we negate it this condition comes out to be false and this part is skipped so after doing this for each and every character at the end we'll simply return ASB do two string so this string Builder will simply append only the characters which are not vels and at the end when we will call two string it will convert everything into the string and it will return so this is the algorithm now let's test it working here we'll call remove ws and let's say we provide string as ice cream and if I run it so here you can see all the vels are removed i e e and a everything is removed and rest of the string is returned also friends why we are using this set is because when we do conents on a set this is a very faster operation the average time complexity of this operation is O of one so basically it signifies that in O of n time we can simply find out the vels from the string and remove it so friends I hope you must have liked this video in case if if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss that how we can reverse an integer in Java so here let's suppose we are given an integer X now we need to return x with its digits reversed so if you see an example here let's say if you are given with an integer as 1 2 3 4 so our output should be 4 3 2 1 we are simply reversing the digits of this integer similarly if you're given an integer which is NE 1 2 3 4 so it should return return -43 2 1 so the sign should be there with only digits being reversed and let's say if we see example three here we are given an integer which is nothing but integer. max value which is 21 4 7483 647 now when we reverse this integer we get 74 6 384 7412 so here you can see that this is the integers max value and if we reverse it this value May overflow the integer range so we need to encounter this use case as well that when we are reversing the max or the Min value or any value of the integer which on its reversal May overflow we need to encounter that use case as well so let's move ahead and see the demonstration of the algorithm step by step so here you can see that we are given with a method as reverse and we are passing in the number which we want to reverse so this method return return type is long now why we have kept the return return type as long is because there may be a chance that let's suppose this int value is maximum or any number which on its reversal May overflow the integers maximum range or minimum range so therefore in order to fit that particular range we are taking a long value which will be returned from this method so here this long is basically handling our overflow case because when we cross the integers range the data type which can handle that overflow range would be the long so now let's see the demonstration of this algorithm step by step let's say we want to reverse a negative number 1 2 3 4 so here the number will be Min - 1 2 3 4 so here can the first thing we do is we simply check that whether this number is negative or not so if we provide this condition then whether number is less than zero or not so if number is less than zero the is negative will have value as true currently number is less than zero so the value of his negative will be true by this condition and while we are evaluating whether number is less than zero or not because when we are reversing the digits we need to take its absolute value without the sign we'll see this later so for time being we just evaluate whether number is less than zero or not if it is less than zero then we simply multiply it with minus1 to make it a positive number so now number will become 1 2 3 4 so here here - 1 2 3 4 into -1 will give 1 2 3 4 this minus minus becomes positive moving ahead now in order to store the reverse we are taking in a long value and why we are taking it as a long value is because because this integer value number if we reverse the digit of it there may be a chance that this number May overflow the maximum or minimum range of the integer so therefore in order to accommodate this overflow condition we are taking it as long because any value which crosses integers Max or Min range can be fit into the long variable so at the start reverse is zero we will create the last digit integer value so this integer value will hold only one single digit which would be the last digit which we will see later here so friends in order to reverse this integer value these are the three main critical steps we need to perform in a while loop this is one of the approach to reverse the integer value now there can be one more approach we can simply take the string value of this number convert it into the character array and then we simply reverse the characters in that particular array so that could be one case but here we are taking the help of modulus operator and the division operator because this modulus operator is very important when dealing with numbers so here we will discuss what actually this modulus operator does and division operator does So currently number is greater than Z so this while loop will execute till number is greater than Zer when number will be equal to Z or less than Z then this value will terminate so friends here you can see that in order to reverse this number 1 2 3 4 it should become 4 3 2 1 so what we need to do is we need to First Take the last digit bring to this position then second last digit bring to this position third last to this position and fourth last to the last position so these are the things we need to do so how we can extract the single single digits from this number is we can take the help of modulus operator so here you can see let's say we want to divide 12 by 10 so 10 is the divisor 12 is the dividend and in normal mathematics when we divide 12 by 10 we get quotient as one and the remainder is two so here this remainder is nothing but the result of the modulus operator which you see here and this one is nothing but the result of the division which we do here so using the simple mathematics we will evaluate the reverse of this number and also friends here you can see that in order to get four when we divide any number by 10 whatever the remainder we get that would be our last digit so here if we divide 1 2 3 4 let's say if I do 1 2 3 4 and let's say divide it by 10 so 1 to so here you can see that this is our quotient and this is our remainder so when we have divided 1 2 3 4 by 10 we get the remainder as 4 which is nothing but our last digit and the question would be the remaining digits just before the last digit so this is the Crux of the algorithm that when we divide any number by 10 the remainder will give the last digit and the quotient will give the remaining digits so here when we take the remainder of the number which is 1 2 3 4 the last digit will have value as four because this is our remainder here moving ahead now friends as we have extracted the last digit this would be our first digit when we do the reversal so here if I reverse 1 2 3 we get 4 3 2 1 so this would be our first digit now so in order to make it first digit what we do is whatever the value reverse will hold we will simply multiply it by 10 and we will add the value stored in the last digit we will see the importance of this part later so currently reverse is 0 so 0 into 10 will give 0 and when we will add four to it we get reverse as four so reverse will become four this part will be clear in the next iteration moving ahead now as we have extracted one digit we need the rest of the digits now and how we can get the rest of the digit is the quotient of this division so when we will do number divided by 10 we get the quotient as 1 2 3 so the new number will become 1 2 3 moving ahead so number is greater than zero 1 2 3 is greater than Z so this condition comes out to be true now we need this last digit so what we need to do is we need the remainder so when we will divide 1 2 3 by 10 because this is our new number so here we'll get 10 1 so here you can see when when we divide 1 2 3 by 10 we get remainder as 3 and the quotient as 12 so this is a similar approach when we divide any number by 10 the last digit is our remainder and the remaining digit is our quotient so now last digit will become three because we need three to Simply append it here somehow moving ahead so friends now as we have got three as last digit and we need to append it here we can't directly add this three to the reverse what we do is whatever the value reverse will hold if suppose this is four and If I multiply it by 10 we will get 40 and then if I add the last digit which is three we will get 43 which is the stuff we want if it reverse 1 2 3 4 we should get 4 3 2 1 so 4 and 3 should be next to each other so this is the important step here that when we are multiplying the reverse by 10 we are simply Shifting the digit by one place and we are adding the last digit to it so that both these numbers are next to each other so this is the important step so here now reverse will become 43 what we discussed here and as we are done with the digit three we need the remaining digits so the remaining digits we get by number divided by 10 which will give us the quotient so number will become 12 the number is still greater than zero so this condition comes out to be true now we will take the last digit and how we can get the last digit is we divide the number by 10 so this is our remainder and this is our quotient so our last digit is two because number modulus 10 will give us the remainder is two so two will be assigned to the last digit and now how we can append two just after three is we need to create one space here and how we can create the spaces we simply multiply it by 10 we get 430 and then we simply add two to it which is our last digit we get 4 3 2 so this is the step which help us in appending the last digit to the reverse so after this line gets executed reverse will become 4 3 2 with this multiplication and addition moving ahead we are done with two and now we simply need one so our new number will become the new quotient by number divided by 10 so we'll get the new number is one number is still greater than zero so this condition comes out to be true now we need the last digit but here you can see one is the only digit left left so here when we will divide 1 by 10 we get remainder as 1 and quotient is zero because 1 is not divisible by 10 so 1 will be our remainder and quotient will be zero so now last digit will become one this and here how we can append this last digit to 432 is 432 into 10 it will give us 4 3 2 0 we will do + 1 we get 4 3 2 1 so this is our last digit so by this two operations the reverse will become 43 2 1 and now we'll simply assign number divided by 10 value to number so here you can see when 1 got divided by 10 the quent was Zero which is the result of our division so 0o will be assigned to the number so number became 0 so now here you can see this while Lo will terminate because number number is equal to Z and not greater than Z so this value will terminate and here is the important step that why we are providing this condition is because we have used up all the digits of the our original number and we have reversed it so therefore this condition is very important that number should be greater than zero because when number will be equal to zer it means there is no value left in the number to be reversed and at the last we simply check whether our original number was negative or not so our original number here was negative so if it is negative then this condition will be executed we will simply multiply Reverse by minus1 so 4 3 2 1 into Min -1 will give - 4 3 2 1 so - 4 3 2 1 will be returned from this reverse method and if is negative would have been false then we would have simply return the reverse so friends this is how we actually reverse an integer value there are three steps to remember first we need to evaluate whether the number is less than zero or not the second is we we need to take this data type as long because when we reverse a bigger integer value there may be a chance that its reversal May overflow the integer value so if we take integer here then this reverse will only hold the garbage value which we don't want so in order to accommodate the large overflow integer value we will store it in the long because long can accommodate that value the other thing is this simple mathematics here which is very important when we divide any number by any value whatever is the remainder if we want to achieve the remainder directly we can use the modulus operator which is here and if we want to access the quotient we can simply take the value of the division here and using this three steps we have actually performed the reversal of this integer so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a lead code problem remove element so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any upat so in this problem we are given an integer array and we are also given with a integer value now our task is to remove all the occurrences of that value from the integer array and that to in place so what do we mean by in placees let's say if we take this example and this is our input array and this is the value given to us which is three now our task is to remove all the occurrences of this value from this array de to in place so it means that we have to modify the given array in such a way that we have to remove all the occurrences of this value we can't use additional data structure or an additional array for this removal whatever operation we need to do we have to perform in the given array itself and in this problem after removal of all the occurrences of the value it is okay that order of the elements may change so for example in the second array when the value is two you can see after removing the two we are getting 0 1 4 0 3 now here we can also return something like 4 1 0 0 3 so the order of the elements may get changed but our task is to just remove all the occurrences of the given value and finally we have to return an integer value which is a count of the elements which are not equal to the given value so here in the first example you can see the array is 3 2 2 3 and the given value is three so after removing three we are only left with two two so the output would be two because there are two values 1 and two similarly here let's say we are given with this array and the value is two so after removal of all the occurrences of two we get 1 2 3 4 5 so our output should be five now here we have to do two task first is we need to return the count of the values which are not equal to well so which is our K and the second task is we have to actually perform this removal in place in the given array so we have to remove all occurrences of well in Array and de to in place so we have to perform this two task now if we look into the problem this is the problem on lead code we have to do this two tasks so whatever the array is given to us we have to modify the same array and we have to return the total number of elements which are not equal to this value so for example in the first stest case if the Val is three and the array is 3 2 2 3 so we know that after removing three the number of elements which are not equal to Val is two 1 and two so here if I directly return let's say two so this test case should get passed but if I run the code so here you can see that we have return two which is our output but we haven't modified the array in place so the lead code editor will also check over the given array that we have remove all the occurrences of the given value from the given array now let's see how we can approach the solution of this problem so for example let's suppose we are given with this array 0 1 2 2 3 0 4 2 our task is to remove all occurrences of two the output should be five because the total number of elements which are not equal to 2 are five 1 2 3 4 5 and the remaining element is shown blank because the test case doesn't look beyond our output which is five so here how we can approach this problem is we can use two pointers let's say I and J so let's suppose if this is our array and we have to remove all the occurrences of two so this is our well now here two pointers will move throughout this array in such a way that one is slow pointer and another is fast pointer so let's say they both started zero index and here let's suppose J is our fast pointer and I is slow pointer so J Will Travel each and every element throughout this array so it's just for iteration and here I will move slowly and its main purpose is to actually remove all the occurrences of the given value so once it removes the occurrences of the given Val it will then move ahead slowly so here it helps to remove the element so here what do we do is as J is iterating over complete array we simply compare the value at J index with the value we want to remove and I is actually helping us to remove that value so here if the value of jth index is not equal to two it means we have found an element which we need to keep in the array so we simply take that value and assign it to the ayat index and then we actually increment I so let's see why an example So currently the value of J index is zero it is not equal to 2 so 0 is not equal to 2 so it means that we have found a value which which we need to keep in this array and we know that I will help us in keeping that value in the array so at the start we will assign zero to the I index so this value stays here and we increment I to the next index so I comes here and J is actually traversing the array so it will also get incremented now we again check that value of jth index 1 whether it is equal to two or not so 1 is not equal to two so we assign the one to I index it means the same value is assigned to this index and we move ahead so I moves to this index and J also moves to the second index now here the value at J index is two and 2 is actually equal to two so here we know that we have to remove this occurrence so I will actually point to the same index because it's task is to actually remove this element so when the value of J index is equal to our value which we want to remove we don't move the I index we only move the J index because I is actually helping us to remove this value so here I stays at the same place and J moves so J comes here now again here the value of J's index is 2 and 2 is equal to 2 and we have to remove this occurrence while taking help of aat pointer so here I stays at the same place and J moves so J comes to the fourth index now value of J index is 3 and 3 is not equal to 2 so it means we have to move this value here so that this occurrence can be removed so when we move three here it would look something like this that two is gone and three comes here and after the assignment I will move to its next index because it task is to remove all the occurrences of the given value and J usually moves ahead so it goes to fifth index now here that jth index value is zero and 0 is not equal to 2 so therefore we will assign this value at the aat index like this and here now value will become zero and now both the pointers will move ahead now here value at jth index is four so here four is not equal to two so therefore we will assign this value at the aat index so it would look something like this so three will be gone and here it will be four and both the pointers will move ahead so I will come here and J will come here so now the value of J index is 2 and 2 is equal to 2 so we do nothing here we simply increment J so now J is traversed complete array and here you can see the ayat index will be our answer because this is the last place where we need to remove an element but we didn't find any more elements so after removal of two our output came out to be five so if we put the index at 0 1 2 3 4 and 5 so this five is nothing but a value which is pointed by the ayat index and this would be our answer answer because till this point all the occurrences have been removed and after that there were no more elements to be removed so therefore we have achieved two tasks one is we are returning the output as five and another is we have modified the array in place and we have removed all the occurrences of two so in this problem the basic idea is we are using this two pointers I and J the purpose of J is to Simply Traverse the array compare the value at J index with the value we want to remove and the purpose of I is to actually remove the element via assignment when we actually find a value at J index not equal to the value which you want to remove now let's move ahead and see the demonstration of this algorithm step by step so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here this is the code and let's say we are given with this array which we discussed in our previous slide we are calling remove element method passing in this array and the value is two for which we want to remove all the occurrences in this array so we have nums array and the Val as two now we are creating these two pointers I and J so here I starts from zero and as we know that the purpose of J is to Simply Traverse the array and compare the value J index with the actual value we want to remove so we are using a simple for Loop here so J starts from zero so at the start J is zero and nums do length is eight because we have eight elements 1 2 3 4 5 6 7 8 and 0 is less than 8 so this for Loop will execute and as you already discussed we have to Simply provide one if check that whether value at jth index whether it is equal to Val or not So currently value of J index is 0 and 0 is not equal to 2 so therefore this condition comes out to be true it means that we have found a value which is not equal to two and which we need to keep in the array so the way we keep in the arrays via aat pointer so we simply assign nums of J to nums of I so nums of J is Zer is assigned to nums of I which is at zero index so this value assigned to the same index like this and the actual purpose of I is to actually remove the elements and keep only those Elements which are not equal to two so after putting a value which is not equal to our given value we move I to the next index like this we will increment J J comes to index one and 1 is less than 8 so this for Loop will execute we again compare the value at J index with the given value so the value at J index is 1 and 1 is not equal to 2 so therefore we have again found a value which is not equal to the value which you want to remove so the condition in if blog comes out to be true and we simply assign value at J index to value at I index so one is assigned to the same index because I and J are pointing to the same index and after putting a value which is not equal to two we simply increment I we increment J so value of J is 2 and 2 is less than nums do length which is 8 so this for Loop will execute we again compare the value at J index with the given value so here two is actually equal to two so the condition in if blog comes out to be false whenever we are encountering a value which we want to keep in the array at that time we are doing this assignment and as soon as we are finding a value at the jth index equal to the value which you want to remove we do nothing and we simply increment J so I will actually remain at this position because in the future there could be a values which we want to migrate to this index because we want to remove this two so let's say in future there is 3 0 4 so three should come here and this two should get removed so this I should stay at the same place so now value of J is 3 3 is less than 8 so this for Loop will execute now value of J index again is 2 and 2 is equal to 2 so therefore the condition in if blog comes out to be false and we do nothing we again increment J value of J becomes 4 4 is less than 8 so this for Loop will execute now the value of J index is three so here 3 is not equal to 2 so it means we have found value which is not equal to the given Val and we need to keep this value in the array and this index is not the right place for the value three so therefore this I will actually help us in shifting of this three from here to here via this assignment so the condition if log comes out to be true we assign the value of J index which is three to aat index so now this two will go away and this three will come here like this and after placing three at its correct spot now it's time to move I to the next index because in the future there could be more values which can come here so we simply increment I value of I becomes three we increment J J becomes 5 5 is less than 8 so this for Loop will execute now value of J index is 0 and 0 is not equal to 2 so this condition comes out to be true so it means we have to shift this zero to its correct position which is being denoted by I so here we simply assign value at J index to value at aat index so zero comes here with this assignment and after placing zero at its correct spot we will simply increment I we will increment J J becomes 6 6 is less than 8 so this for Loop will execute so value of J index is 4 4 is not equal to 2 so therefore this condition comes out to be true and we simply shift this value four at index I so four comes here via this assignment and then we simply increment I because we have placed four at its correct spot we increment J J becomes 7 7 is less than 8 so this for Loop will execute so now here value of jth index is two 2 is actually equal to two so therefore the condition in if L comes out to be false so we do nothing and we simply increment J so value of J becomes 8 and 8 is not less than 8 so therefore this for Loop will terminate and at the end we'll simply return the value which is being hold by I which is five because this was the last place where we couldn't remove the occurrence and before that we have removed all the occurrence and as the array starts from zero to index we have to return return a value which is the total number of elements which are not equal to our given Val so here we had 0 1 3 0 4 which were not equal to 2 and if you count them we have 1 2 3 4 5 so whatever value I holds that will be our answer so we simply return return five and we have also modified the array in place by removing all the occurrences of our given value which is two so friend this was all about the remove element problem I hope you must have liked this video thanks have a nice day hello everyone so in this video we are going to to discuss a lead code problem remove duplicates from sorted array so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so in this problem we are given with an integer array and the array is sorted in non decreasing order so as a input we are given with an integer array and the integer array is sorted in ascending order now as the array is sorted in ascending order there may be duplicates now our task is to remove the duplicates and that to in place so by in place we mean that we cannot use additional array or any other data structure we have to modify the same array and we have to remove the duplicate such that each element appears only once so for example let's say we have this input array 1 1 2 so the array is sorted and here we have one duplicate which is one so we have to to remove this duplicate such that only one occurrence of an element occurs such that the element appears only ones so after removal of the duplicates we get two numbers one and two and this one is removed so our output is two and the array is modified like this 1 2 and whatever elements are left over those are ignored and one more thing we need to keep in mind is the relative order of the element should be kept the same so we have to modify the input array in such a way that let's say we have one one and two so at the start there should be one and after that two should come it should not be like this 2 comma 1 because we have to maintain the relative order of the elements so let's say if we are taking the second example now if you remove the duplicates from this sorted array so here we have two zero so one is removed because the element should appear only once after after zero if we see the relative order the next number is one and we have three ones so we have to remove this two ones and we need to keep only one occurrence of one and after that we have two twos so we have to remove one two and we have to keep only one two then we have two threes so we have to remove one three and at the end we have four so four is itself unique so after the removal of duplicates if we count the unique elements so we get one 2 3 4 and five elements so our output is five and we have to modify the array in place so at the start zero comes then one comes then two then three and then four so the relative order is maintained and the rest of the elements are just ignored so let's move ahead and see how we can solve this problem so suppose we are given with this array 0 0 1 1 1 1 2 2 3 3 4 now our task is to remove the duplicates and keep only one occurrences of the element so let's say our array is 0 0 1 1 1 2 2 3 3 4 so your first property is the array is sorted in ascending order so it means whatever duplicates we have they are very adjacent to each other so second properties is duplicates are adjacent to each other now how we will solve this problem is we will take two pointers I and J so here J Will Traverse each and every element of this array so therefore it's a fast pointer and I will move slowly so it's a slow pointer now the purpose of J is to basically iterate the array and compare the duplicates and the purpose of I is to actually remove the duplicates so as soon as I removes the duplicates from this array it will move slowly one step at a time and J will simply Traverse the array once so here both the pointers will start from first index I and J so I start from first index because the zero index already contains a unique element and the next unique element should come here so I starts from here and its main purpose is to remove the duplicates and after removal of duplicates it simply moves ahead now similarly JS starts from first index because it actually Compares current element with previous element so that it can figure out that these two numbers are duplicates so what it does is we simply compare value at J index with value at J minus one index so therefore we have to start from the first index so as soon as J moves ahead we simply compare the current element with its previous element to figure out whether they are duplicates or not so at the start value of J index is zero and J minus 1 as index is also zero so here 0 is equal to 0 therefore this condition comes out to be false so whenever this condition comes out to be false we actually do nothing and we simply Traverse J to its next index so J will come to the second index now value of J index is one and J minus 1 as index is 0 so 1 is not equal to Z so this condition comes out to be true so whenever this condition comes out to be true it means that we have found a unique element because the element just before that is different from this so whenever this condition comes out to be true it simply means that when we compared this two elements they were not equal so the current integer is actually a unique integer which we need to keep in the array so what we do is when this condition comes out to be true we simply assign value at J index to value at I index because the purpose of I is to actually remove the duplicates and we know that zero is a duplicate here so we simply assign value at J index to value at aat index so after this assignment one comes here after this assignment we know that the next unique element should come here so we simply Traverse I ahead so I comes here and J will move to the third index so purpose of J is to Simply Traverse the array one element at a time and compare the current integer with its previous integer so now value of J index is one and value of J minus 1 as index is also one so they are equal so this condition comes out to be false and we know that once this condition comes out to be false we do nothing and we move simply J one step ahead because we didn't find any other unique element so that we can replace it with aat index we simply move j one step ahead now again value of J index is one and value of J minus one index is also one so it means this condition comes out to be false and we do nothing we simply Traverse J once St now here value of J index is two and value of J minus 1 index is 1 so 2 is not equal to 1 so therefore this condition comes out to be true so when this condition comes out to be true we know that we have found a unique element which we need to keep in the array and we know that we are using this ath pointer to Simply put this value in the array so once this condition comes out to be true we perform this step so value at J index we simply assign it to value at a index so this two comes here and this one which is duplicate gets removed so two comes here and after this assignment we do i++ because the next unique element will come here so I comes here and J Travers ahead now value value of J index is two and value of J minus 1 index is also two so this condition comes out to be false so therefore we do nothing and we simply Traverse J ahead now here value of J index is 3 and value of J minus 1 index is 2 so 3 is not equal to two it means we have found one more element which is unique and which we need to keep in the array once this condition comes out to be true the correct place for this three is we simply assign the value of J index to value with a index so this three comes here so this one goes away and three comes here and after this assignment we simply increment I because the next unique element should come here so I moves here and J moves here now the value of J index is 3 and J minus 1 index also 3 so therefore this condition comes out to be false so we do nothing we simply Traverse J to the next index J comes here now value of J's index is four and value of J minus 1 index is 3 so 4 is not equal to 3 so this condition comes out to be true it means we have found one more unique element which we need to keep in the array so we simply assign this value to nums of I so this four will come here and this one will go away and after this assignment we move I one step ahead and J also one step ahead so now J is actually traversed till the end of the array and we know that we have removed all the duplicates till this this point and if we count the number of elements we have 1 2 3 4 5 so our output would be five and here as this is an array so this is zero index first second third fourth and this is fifth so we simply return the value which is stored in I which is five and rest of the elements can be ignored so this array can be ignored our task was to remove all the duplicates such that each element appears only once so now let's move ahead and see the demonstration of this algorithm step by step so friends before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so yeah this is the code and let's say we are given with this array which is sorted in ascending order and our task is to remove the duplicates now as the array sorted the duplicates will be adjacent to each other so when we call this method the first thing we do is we create these two pointers I and J where J is our first pointer it Traverse the array from index one to index 7 and I will start from one because this zero is already at its correct place and unique so we don't touch the zero index and we start from the first index so we start J also from the index one and why we are starting from J equal to 1 is we simply compare the current and the previous element so we start from index one and J Will Travel till nums do length so nums do length is 8 so 1 is less than 8 so this condition comes out to be true and the for Loop will execute now in the for Loop what we do is we simply compare the two adjacent values which is the value of J index and the value of J minus 1th index and we check whether they are duplicates or Not So currently value of J's index is zero and Z minus 1 index is also zero so therefore this condition comes out to be false because both the values are equal so when both the values are equal it means we have found a duplicate and we do nothing we simply increment J J becomes 2 2 is less than 8 so the for Loop will execute value of J minus 1 index is Zer and value of J index is 1 so 0 is not equal to 1 so this condition comes out to be true it means we have found one unique element which we need to keep in the array because the adjacent elements are different it means this value is the first integer which is unque unique so we need to keep this value in the array so the if blog will execute and we know that index I will actually help us in placing this value at its proper position so we simply assign nums of J to nums of Y so one comes here and we know that next unique element should come here so we simply increment I so I becomes two we increment J so J becomes 3 3 is less than 8 We compare these two values now and 1 is not equal to two so therefore this condition comes out to be true it means we have found one more element which is two which is unique in this array and which we need to actually keep in the array so the condition in if log comes out to be true and we assign this value to nums of I because I is actually holding that place where we can only insert a unique element so why this assignment two comes here and next unique element should come here so we simply increment I I becomes three we increment J J becomes 4 4 is less than 8 so this for Loop will execute so now we are comparing these two values so condition in if loog comes out to be false and we do nothing we increment J J becomes 5 5 is less than 8 so the for Loop will execute and now we are comparing this two elements so the condition in if blog comes out to be false we simply increment J J becomes six and 6 is less than 8 so this for Loop will execute and now we are comparing these two elements so 2 is not equal to 4 so this condition comes out to be true and we have found one more element which is four which is unique and which we need to keep in the array so the if log will execute and how we will keep this value four in the arrays we simply assign value of J's index to value of aat index so this four will come here and we know that the next unique element should come here so we simply increment I I becomes four we simply increment J J becomes 7 7 is less than 8 so this for Loop will execute now we'll compare this two elements so here both the element elements are equal it means we haven't found any unique element so the condition in ifog comes out to be false we increment J so J becomes 8 and 8 is not less than 8 it means we have traversed all the elements of this array so this for Loop will terminate and here you can see whatever the value I is holding that will be our answer so if we count the unique elements we have 1 2 2 3 4 and here we can see as the array starts from zero index so whatever the value I is holding which is four will give the total number of elements which are unique in this array which is four so we simply return return four from this method so that is our answer and we have also modified the array in place so friend this was all about remove duplicates from sorted array I hope you must have liked this video thanks have a nice day hello everyone so in this video we are going to discuss a very famous interview problem which is thre sum problem so in this problem we are given an array of distinct integers now our task is to print all such tripletes such that they add up to a specific Target and the triplet should be ordered in ascending order so let's say we are given an array of integers now these are actually distinct integers 2 4 3 7 1 8 90 we need to print all such triplets such that they add up to a specific Target so we have been provided with the array and a Target value the triplet should be ordered in ascending order so we need to find three numbers such a way that when we add them we get a target of six and that two number should be in ascending order so for example 0 + 2 + 4 will give 6 and here 0 2 and 4 are in ascending order 1 + 2 + 3 will also give us six 1 2 3 are in ascending order so we need to find all such triplets with sum of two a specific Target and they are ordered in ascending order so let's see the demonstration of of this algorithm step by step so here this is the algorithm where method name is three Su we are given an array and a Target let's say we are given with an array having six elements 2 4 3 7 1 0 and a Target let's say six so when we call three sum method we pass the array and the target is six so friends basic idea behind this algorithm is first we sort the array second we use three pointers so when we sort the array we can print the triplets in ascending order so that is one of the use case and the Second Use case is when we sort the array we can use three pointers which can provide us three numbers which add up to a specific Target and de to with a optimized time complexity so here the three pointers we use are i j and k which we will be seeing later here so these three pointers will give us three different numbers from the array we will take up their sum and print it on the console if sum is equal to Target so let's see the demonstration of this algorithm step by step so in the first step we are actually sorting the array in ascending order so 2 4 3 7 1 0 will be sorted and it will become 0 1 2 3 4 7 moving ahead now as we discussed that we will be using three pointers i j and k so for I it will start from zero and it will go to error. length minus 2 so we will see why we are taking min-2 later but it will start from zero and it will go to index 3 which is array do length 6 - 2 4 so here less than means that it will go till 3 we will see later that why we are taking a do length minus 2 So currently I will start from zero it means it will be pointing to the zero index of the array now as we need to find the three numbers which are distinct so the J pointer will start from I + 1 so here whenever this for Loop will start with any value of i j will start from a value just ahead of it so value of J will start from one and we will take the K pointer we will start it from ARR do length minus one it means the third pointer will start from the the the last index which is array do length 6 - 1 which is 5 so K will start from 5 we will see it significance that why we are starting it from ARR do length minus one moving ahead so friends as we have now pointed i j and k to three different indexes we will try to find out the sum of these three numbers and then we figure out whether they are equal to the Target or not so this for Loop will actually help us in traversing I and this while loop will help us in traversing J and K so as we want to find the three distinct numbers we have provided a while loop and the condition is J should be less than K so here J and K will Traverse through this array J Will Traverse in this direction and K will Traverse in this direction covering up the elements so this file Loop will go till J is less than K because if J will be equal to K both J and K will point to the same number which we don't want so J should be less than K in the first step what we are doing is we are calculating the sum of AR aat index at J index and at the K index because we need to find out the triplets so i j and k will provide us that triplet so when we do sum of 0 1 and 7 we get eight so sum will become eight now we simply check whether sum is actually equal to our Target or not so our Target is six and sum we want is eight so this condition comes out to be false so here as I is fixed at zero index we have sorted the in ascending order it means whatever value will come after 1 will be greater than 1 and whatever value will come before 7 will be lesser than 7 because the array is sorted now when we compared sum with Target we found out that sum is actually greater than Target sum value is 8 and it is greater than Target so somehow we need to reduce the value of sum in the next iteration so that it matches the target so what we do is we provide this two conditions we check whether sum if it is not equal to Target we check whether it is less than Target or it is greater than Target So currently if sum is greater than Target it means we need to reduce the sum so here AR is sorted I is fixed the only option we have is to move j this dire direction or k this direction if we move I this direction in the next iteration when we will do sum the sum will become 0 + 2 + 7 which will give us N9 which is actually more than the current sum and which we don't want so let's say if we move K this direction so K will come here and if we do sum in the next iteration we will get 0 + 1 + 4 which will be equal to 5 which is actually reducing the sum to get it more closer to six so here as the array is sorted when sum is greater than the target we actually move K to this direction so that in the next iteration the sum will become closer to six which is our Target and if sum is less than Target then we move j to this direction because that will only increase the sum and then it will match our Target So currently sum is greater than Target so this condition also comes out to be false so the only option we have is when sum is greater than Target we move K to this direction because in the next iteration it will help us in minimizing this sum so here the condition is if Su is greater than Target move K left if sum is less than Target move j to right so currently sum is greater than Target so we will move K left so K will become four we are simply moving it one position here J is still less than K so this condition comes out to be true we will evaluate sum again 0 Plus + 1 + 4 will give sum as 5 so sum will become five we compare whether sum is equal to Target or not so sum is not equal to Target so this condition comes out to be false and as the condition has come out to be false we provide these two conditions we check whether sum is less than Target or sum is greater than Target if sum is less than Target then we move j to right because because if we move j to right we will get a value higher than the current value of array at J index and when we will do sum in the next iteration we will get 0 + 2 + 4 which will be equal to 6 so here when we need to reduce the sum we move K to this direction when we need to increase the sum so that it matches the target we move J to this direction So currently sum is less than Target we need to increase the sum so we do j++ J becomes two so J comes here J is less than K now we'll again evaluate the sum so 0 + 2 + 4 will give sum as 6 so sum will become six so here you can see when we provide this condition that whether sum is equal to Target or not so this condition comes out to be true it means we have found one of the triplet which is 0 2 and 4 whose sum is equal to the Target so we are simply printing the value with ith index jth index and K index on the console so it will print 0 2 4 0 2 4 and as I is fixed J value is used up K value is used up so here what we do is we increment J and we decrement K because 0 2 4 is already being found if we only increment J it will come to this position so 0 + 3 + 4 will never give us a sum of 6 because 0 2 4 has already given us the sum of six and as these are the distinct integers here value cannot be two it can be only greater than 2 so therefore if we increment J we also decrement K because we will never find any such pair if it would have been duplicated values and here would have been two then we have incremented only J so we would have found another triplet 0 2 and 4 but here as these are the distinct integers therefore when we increment J we will never find any such other triplet whose sum will be equal to Target so 0 + 3 + 4 will give us sum as 7 so therefore to keep k at this position is also useless so we decrement K also so first first we'll increment J J becomes 3 and then we decrement K now here you can see J is actually equal to K so therefore this file Loop will terminate because we need to find a triplet which is unique so J andk cannot be pointing to the same number and bringing up the sum so this F will terminate so the call will reach here now we will simply increment I by one position by I ++ so I will become one now we have seen all such pairs which can form a triplet with the value as zero and we have used up index zero so when we will start I from 1 we will not go behind the value of I because that we have already seen so the new J value will be I + 1 which is 2 and K we will take this ar. Len minus one which is the last index J is less than K we will take some of these three values value at I index J index and K index we will do their sum so 1 + 2 will give 3 3 + 7 will give 10 so sum will become 10 it is not equal to Target sum is not less than Target so this condition also will come out to be false sum is greater than Target and array is sorted so if we move K to left we will get a smaller number so that in the next iteration this sum will be reduced and can match to the Target because currently sum is greater than Target we need to reduce this sum currently the value is seven which is being used up in forming the sum if we shift K this side we will get a lesser value so in the next iteration our sum will be more closer to Target so therefore we are decrementing K so K becomes 4 J is less than K we again do the sum so 1 + 2 will give 3 3 + 4 will give 7 so sum will become seven so here you can see why we moved K to this direction is in this iteration we actually reduce the sum from 10 to 7 sum is still not equal to Target sum is not less than Target so we need to reduce some further down so we simply do K minus minus so K will become 3 J is less than k j value is 2 and K value is 3 so J is less than K now we will do sum of these three values 1 + 2 + 3 which will give us sum as 6 so sum is equal to Target it means we have found one more triplet so we will print it on the console 1 2 3 1 2 3 and then we simply increment J and decrement K so J will become 3 and K will become two like this now this while loop will terminate because J is actually greater than K we will increment I again I will become two we have used up these elements so our J pointer will become I + 1 which will start from third index and K will start from the last index J is less than K we will take the sum of these three indexes at their respective array positions 2 + 3 + 7 will give sum as 12 sum is not equal to Target sum is not less than Target it is actually greater than Target so we need to reduce the sum and when we reduce the sum we simply decrement k k will become 4 J is less than K the new sum will be 2 + 3 5 + 4 will give 9 so sum is reduced but still it is greater than Target so sum is not equal to Target sum is not less than Target it is actually greater than Target so we again decrement K so K will become three so here you can see J and K are now pointing to the third index so therefore this V Loop will terminate because J is actually equal to K because we need to find triplets which are unique so all these pointers should point to a different values of the array we will increment I I becomes three we have used this position so here you can see if we calculate array do length we will get 6 if we do minus 2 we will get 4 so I is still less than 4 because it is pointing to third index and here you can see that y we have provided this condition is because we need to give space for the other two pointers as well one can occupy this position other can occupy this position if I would have traveled all the way across the array say for example if I would have reached here so J would have started from here and K would have also started from here which we don't want because we want J should be less than K so at least we need to give space for two elements so therefore we are taking it as I should be less than AR do length minus 2 we are doing minus 2 because one slot will be taken by J and other slot can be taken up by K properly so this condition is still true that I is less than a. length minus 2 so J will start from fourth index K will start from the last index J is less than K we will do the sum 3 + 4 + 7 will give 14 sum is not equal to Target sum is not less L than Target if we want to reduce the sum we have to decrement K to reach here so K will become four and as you have decremented K J and K are pointing to the same index so therefore this Val will terminate and again when we will increment I I will become four so 4 is not less than AR do length minus 2 6 - 2 is AR do length minus 2 which is 4 4 is not less than four so therefore this for Loop will terminate and once this for Loop will terminate our method will also get terminated and whatever we have got as a triplet we have printed on the console which is 0 2 4 1 2 3 which are the three numbers which add up to a target of six and they are in ascending order so friends this was all about the thre sum problem where we use the technique of sorting and three pointers to figure out which are those triplets which add up to a Target I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem product of array except self so let's see what this problem is and how to solve this so in this problem we we are given an array of integers we need to return return an array result such that value at index I is actually equal to the product of all elements of array except the element at index I so in the result array let's say any index I we need to store the product of all the elements of the given array leaving the element at that respective index so when we are doing the product the values are given in such a way that product fits in the 32-bit integer one constraint is the algorithm should run in O of and time and without using the division operator so let's understand the problem with an example let's say we are given an array having four elements 1 2 3 4 now in the result array we need to store the product of all the elements of array in such a way that let's say if you are on index one so this is zero Index this is one this is two and this is three so let's set index one we have value two so in the result array we need to store at index one product of all the numbers in this array excluding two so for example at index zero we have 1 so we can directly do the product of rest of the elements 2 into 3 6 6 into 4 is 24 so we can directly Place 24 here we haven't included one into the product now for index one at index one we are storing the product of rest of the elements excluding two so 1 into 3 is 3 3 into 4 is 12 so we are storing 12 here for index X2 we will exclude three we will take the product of rest of the elements which is 4 into 2 8 8 into 1 8 so we are storing eight here for the last index we will exclude four and we will take the product of rest of the elements 1 into 2 is 2 2 into 3 is 6 so we are storing six here so in this problem in the result array at any particular index let's say this index we are storing the product of rest of the elements excluding the element at that particular index so friends we don't have to use the division operator or else the problem would have been very simple we could have multiplied all the numbers so for example if we take the product of all the numbers we will get 24 now let's say if you want to fill for the index one excluding two so we would have directly divided it by two it would have given 12 and we would have placed 12 here so we don't have to use the division operator and secondly we need to solve this problem in O of end time so here you can see if you use two for Loops the nested for Loops the time complexity will be o of n² so the first for Loop will TR the element one by one and the inner for Loop will travel rest of the elements take their product and store it at the respective index of the outer for Loop iterator so the time complexity would have been o of n Square so we need to solve this problem in O of end time so now let's see the algorithm and the demonstration of that algorithm step by step so friends before we start in case if you're new to my channel then please please subscribe to my channel and click the Bell icon so that you never miss any update now here we will call find product method we will pass this array having four elements 1 2 3 4 so friends how we will solve this problem in O of end time is we will Traverse this array two times one in this direction and other in this direction and let's say this is our result array so when we will Traverse in this direction let's say if we take the example of index 2 this element now at this index we need to exclude three and store the product of rest of the elements but here you can see at index 2 we are doing the product of these two elements which is on the left side and all the elements on the right side and excluding three so when we will Traverse the array from the left side in the result array we will store the product of the left part of the array and when we will Traverse from the right side we will include the elements of the right part of this index so when we will Traverse on the left we will do the product of the left part store it here and when we will Traverse on the right side we will take this value whatever value is stored here we will do their product and we will place it here so in the left part we are doing 1 into 2 we will place two here and when we are traveling from the right we will take the value four multiply it with two and store eight here so this we will do for for all the elements at the respective indexes and finally we will get the result array so first we are traveling from the left Direction so at the start we are creating a temporary variable assigning it a value of one we will see it significance later so temp is equal to 1 we will create the result array like this and as total length of array is four we will initialize the result array with array. length which is four now we will start the for loop from index zero and go till the end of the array so at the start I will be equal to zero which is pointing to the zero index now as we discussed when we are traveling in left direction we will store the product of the left side elements So currently for index Zer there are no elements in the left side and here we have created a temporary variable assigned a value one so we will directly store one here which is the value stored in temp because there are no elements in the left part of index Z and we also know that anything multiplied by one will give the same result so therefore we are initializing temp with one so here we will get value as one moving ahead now for the next index let's say for two we need to take the product of the left part so here as we are assigning time directly to the result at a particular index here what we are doing is we are taking the product of of temp with the previous value and then we are storing it in the result array so for the next iteration we have to take product of the left part currently here we have only one element which is one so we are multiplying 10 with the value stored at index I which is index zero so time becomes one because one into 1 gives [Music] 1 you will understand more about this step when we move ahead so now we'll increment I I becomes one now as temp is storing the product of the previous elements we will directly take the value of Temp and store it in the result array at ayat index so one will be stored here because value of temp is one so friends the next iteration I will reach here so for index 2 we need the product of left side we need product of 1 and two so temp already has product of this part here we will multiply it with array of I which is we will multiply it with two and we will get the product of these two elements and that product we can safely store here because when we are traversing from the left side for this particular ular index we will only store the product of these two elements and currently as we have already stored the value of temp into result I which is 1 here if we multiply temp with current element we will get the overall product of these two elements so the new value of temp will be 2 into 1 which will give us [Music] two we will increment I I becomes two and we know that temp already has the product of its two previous values which is 1 into 2 so we will first directly store 1 into 2 which is 2 at index 2 of the result array so this step does that so two comes here now when we will move to the next element we need to include three also in the product because for index 3 which is this index we need to take the product of these three elements we already know the product of these two elements which is stored in the temp if we multiply it with three which is the current element at index I we will get the product of three elements previous to third index so therefore we are multiplying 10 with the current index value of array which is three here so 3 into 2 will give six so 10 becomes six which makes sense because 1 into 2 into 3 will give 6 which we can use directly in the next iteration so we'll increment I I becomes three so in the result array at third index we will first directly store the value of 10th which is six so here you can see for third index the product of its previous values is 6 1 into 2 into 3 6 and we are storing six here and as we are traveling from the left side we are only looking in the elements which are on the left part of the particular index so as there are no more elements left this product makes no sense so temp into AR of i 4 into 6 will give 24 so temp will become 24 but it is of no use because there are no elements going further so we'll increment I I will become four and this for Loop will terminate because four is not less than arror do length which is [Music] four so when we are Travers from the left side in this direction we stored the product of the left part so now we'll again initialize temp with one so time becomes one and now we will Traverse from the right side so here I starting from array do length which is 4 minus 1 which will give us three which means we are starting from the third index and this Loop will go till I greater than or equal to zero so friends we also discussed that let's say if we want to fill for index two we need product of these two elements and whatever the product will come which is two here we will multiply it with the right side Elements which is four here so 2 into 4 will give eight and we will store eight here so in the result array we are already having the product of the left part of each index now we simply need to take the value of the right part do their product and whichever value is stored here we simply need to multiply it with that value so now that thing we will do when we are traversing from the right side so at the result array at index So currently we are at the third index whatever value is stored is actually stored of the product of its previous numbers and S index 3 has no elements to its right we will simply multiply whatever value stored here into temp which is one and store it back into the result array so for index 3 add result of I we will take six which is this value we will multiply it with 10 which is one which will give us six and we will assign six back to index 3 at the result array so it will remain six so here we are doing the same steps for index 2 we need product of its Elements which are on its right side so temp value is one we will multiply it with four and we will get the product of its right side elements so time becomes [Music] four we will decrement I so I will come at index [Music] 2 now at this index you will understand the algorithm more what we are trying to achieve is in the result array for index 2 we need to store the product of the elements excluding index 2 which is three so 1 into 2 which is on the left part excluding three and taking in remaining element which is on the right part so 1 into 2 will give 2 2 into 4 which will give us eight so we need to store it here now in the result array we are already having the product of the left part which is two here we need to Simply multiply this two with the product of its right part so currently it's four which is stored in the 10th so result of I which is 2 multiplied by 4 which is temp so value stored at result of I multiplied by temp will give the actual product of all the elements excluding this index because temp is already having product of its numbers on the right side so 2 into 4 will give eight and we will assign eight back to the result array at index I so it will come here now we will multiply three with temp which will give us 12 and we'll Ascend 12 to Temp so why we are doing it because in the next iteration so when we will decrement I I will come to index one now for this index we already have the product of its left element here in the result array we need the product of its right part previous value of 10 was 4 and we multiplied it with three which gave us value as 12 so temp is currently having value 12 which is the product of all the elements on the right side so for filling the value of index one we need product of the left side which is one which we already calculated we will exclude this element and we need the product of the right side which is already stored in the temp so value at result array the index which is one will give product of the left part temp will give product of the right part when we will multiply them we will get 1 into 12 which is 12 so 1 into 12 which is temp will give 12 so 12 will come here and for the zeroth index we need product of the right part so temp already has product of three and four which is 12 we will multiply it with the two which is the array element at index I so temp will become [Music] 24 we will decrement I so I will come at index0 now at index0 we need to Simply put the product of all the elements on the right side their product with product of the elements on the left side so left side doesn't have any value because we have value is one here we will take value one multiplied with value of 10 which is 24 and we will assign it back to the result areay so here it will come 24 and then we'll evaluate temp again which actually is of no use because we have already filled all the positions here so the new value of temp will be temp which is 24 into array of I which is 1 which will give [Music] 24 so now we'll decrement I and this for Loop will terminate because value of I will become minus one and minus1 is not greater than or equal to Z so this for Loop will terminate and at the end we will simply return the resultant array so friends the basic idea behind solving this problem is we need to do two traversal one is from the left side and one is from the right side when we are traversing from the left side we will only see the elements which are on the left part of any particular index we will do their product and we will store de value in the result array and that will be done from the left part now when we are traversing from the right part let's say for index 2 when we had completed from the left part we had product of these two elements so in the result arror the value would have been two because 1 into two will give two when we are traversing from the right side we need product of the right part so currently as there is only one element which is four we will take four multiplied with two which will give us eight and we will store eight back here and this we will do for all the elements so it's very simple for any index I this is left part this is right part we are excluding the current element left into right and whatever we get value we'll store back it here in the result array so we are excluding this part we are taking left part we are taking right part product we are doing their product and storing back at the respective index so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss sliding window maximum problem so let's move ahead and see what this problem is and how to solve this so in this problem we are given an array of integers and we are given a sliding window of size K so it means we are given with this array and a value K which is the size of sliding window now this sliding window is moving from very left of the array to very right so this sliding window is starting from zero to index having a size of three and it is moving from left to right and as it is moving from left to right we can only see that many numbers so at the start we can see only 44 77 33 so it means we can only see k numbers of the array at a time and this sliding window is moving into this direction by 1 one position so first we will see 44 77 33 then we will see 77 33 44 then we will see 33 44 88 and at the last we will see 44 88 and 11 so for this array with the sliding window of size three what we need to find is for every window which we saw so we need to find Max among this three and then sliding window will move ahead so then it will see this three elements and then we have to find the maximum among this three so which is 77 again so similarly till the end we need to find the maximum in the sliding window so this is the output for this array having the sliding window of size three now how this output came here you can see in the first sliding window 44773 33 the max value among this three element is 77 so for this sliding window the max is 77 then this sliding window will move ahead so 44 will go out and this 44 will come in so now among this three elements 77 33 44 77 is Max so in this sliding window the max would be 77 similarly sliding window will move ahead now we have 33 44 and 88 so among these three elements 88 is Max and at the end the sliding window will reach to the end of the array so among these three elements 44 88 and 11 the max is 88 now let's move ah and see that how we can solve this problem suppose friends we are given with this array and we need to find the max in the sliding window so here in order to solve this problem there are various Solutions so one such solution is is to find the next greater element of each and every element in this array so the problem of next greater element we already discussed in one of our previous video you can watch that video to understand more about this algorithm in this video I will be demonstrating the next greater element problem as well so here actually what we do is for each and every element you see here we find its first next CER element towards right so if you see for 44 if we look in this side we just see the first next greater element to 44 So currently 77 is greater than 44 so it becomes the first next greater element of 44 like this then we look at 77 if we look in this direction 33 is less than 77 44 is less than 77 88 is greater than 77 and it is first next Creator element towards right of 77 so here 88 becomes the first next gror element to 77 similarly for 33 if we look in this direction 44 and 88 both are greater than 33 but the first next greater is 44 so the answer will be 44 4 44 it will be 88 488 here we have only 11 so therefore there is no element in the right of 88 which is greater than 88 so in our previous video we discussed that we simply return minus1 because there are no elements greater than 88 towards its right and similarly with 11 as it is the last element there are no elements after that so for 11 also our answer becomes minus one so in that video this was our output and our answer so we will use the same algorithm here but there will be a slight difference so here you can see below I have written the next character element of each and every value of this array so in our previous video in the next C element array we actually return this as our output but now instead of this as our output first we will evaluate the indexes of this elements and we actually store the indexes in the next L element array so for example for 77 if you see has index one so instead of storing 77 we will store 1 like this so these are the indexes of this next L elements so for example for 77 our answer was 88 so if you see 88 is at index 4 so we are storing four here I'll remove this here if you see for 33 its next critor is 44 which lies at index 3 so we are storing index 3 for 44 the next letter is 88 which lies at index index 4 so we are storing four here and for 88 there is no greater element towards its right so therefore as we are storing indexes here here if you see the last index is fifth index so we are storing a greater value to five which signifies that we have gone out of the boundaries of this array so we are simply storing six so this six is nothing but ar. length which signifies that for 88 there was no greater element towards its right and for 11 as well so we are storing 6 6 and the value we are taking as minus1 and minus1 here we need to store index which is out of the boundaries of this array so that we can justify that 488 there is no greater element towards its right and for 11 there is no greater element towards its right so we are storing the index is array. length so here you can see if we are on at index zero for example we see there is a value 44 now if we go to the index zero of next greater element array we see there is a value one this value is only for demo purposes I have written here but actually we will be playing with this value and this value so at 0o to index we have 44 and we need to find its next greater element so what we do is we simply go to this array we see there is a value one and we know that this is actually an index so what we do is we simply go to the original array at index one and whatever value here it is we simply say that this value 77 is next greater to 44 so it goes like this from here first we go here and then we go here to find the next greater now similarly if you want to find that what's the next greater to 33 we simply go to index 2 we see there is a value three so we go back to index 3 and we find 44 and we know that 44 is next greater to 33 so friends our problem is to find the maximum in the sliding window so how this next letter element array is helping us in finding dat is let's say for example this is our sliding window here we have taken ks3 and let's say after evaluating the maximum of the sliding window the sliding window reached here and now let's say we want to find the max among this three elements and we actually know that it is 88 so here what we do is the step one is from where our sliding window is starting we take that element So currently it is 33 we take 33 and assume that it is the max in this sliding window and here you can see it is at index 2 but we know that 33 is not the max in this sliding window so what we do is this is our assumption in the Second Step what we do is we simply go to the next greater element array at index two and we see there is an index 3 which means that if we go to index 3 we will find an element which is greater than 33 so here what we do is if you see the window is starting from index 2 and the value of K we are taking as three for example so we know that this window will go till 2 + 3 minus one which is still fourth Index this index so we are taking three elements because value of K is 3 from index 2 to 4 so starting is 2 this is our K and if we do minus one we'll reach the last index so when we find three here we first check whether this this index is in the range of the sliding window or not so here you can see three actually lies in the range of sliding window so this point suggests that there is an element greater than 33 and it lies in this sliding window which is 44 so therefore this 33 which was our assumption is wrong and now what we do is we simply go to this element 44 and assume that now it is our maximum so we reach here at the 44 but still we are not sure that 44 is Max or not so what we do is we simply go to the index 3 which is of 44 in the next greater element array here we find our value as four which is the index four and we also see that four is actually in the boundaries of the sliding window which suggest that at index 4 there is a next greater element to 44 and this element is also in the range of the sliding window so our assumption that 44 was Max is also wrong so now what we do is we Simply Now go to 88 here and we assume that now 88 is our Max but now what we do is we simply go to the index 4 here and we see we have value is six and then what we do is we take this six and before going to the sixth index which is out of this array what we first check is whether this six is in the boundaries of this sliding window or not so the maximum range of the sliding window is four and we know that the next C element 288 is at index 6 which is out of the boundaries of the sliding window it means let's at index 6 here we have one element 100 like this so here for 8 we we know that if we go to the index 6 we will find 100 but this 100 is not lying in this sliding window and we need to find the maximum in the sliding window so we know that for 88 its next greater is 100 but it is lying at index 6 it is not in this sliding window so it means we are 100% sure that 88 is Max in this sliding window so therefore we use this algorithm and we can come to know that 88 is Max in this sliding window so this approach we do for every sliding window like this and what we do is we take the first element we assume it's the max in this sliding window but to confirm that we take this index we go to the next greater array at index 2 we pick the index of the next greater to 33 which is this index and the element is 44 and as the index is three we check whether this index 3 is actually in the range of the sliding window here it is from 2 to 4 and three actually lies between 2 to 4 so therefore we know that 33 cannot be our Max in this sliding window because there is one more element in this sliding window which is greater than 33 which is 44 and similarly with 44 we found that its next grer is 88 and this 88 is also lying in this sliding window range so then we came to 88 and for 88 we found that its next set is index 6 here index is out of the range of this array but let's suppose even if the index is had any value let's say 100 but we know that we have to find the max in this sliding window and the next greater to 88 is 100 which is out of this window so therefore our answer would be 88 for this window so friends here is the importance that why we are actually storing the indexes instead of actual values because this window of size K is actually dealing with the indexes and we need to find the index of the elements next greater so therefore instead of storing the actual values in this array which we also saw in the previous video we are actually storing the indexes now the algorithm is very much similar but the only difference is instead of the numbers of next greater we are actually storing their indexes so let's move ahead and see the demonstration of the algorithm step by step so friends before we start in case if you want to master algorithms and data structures you can subscribe to my channel and click the Bell icon so that you never miss any update so here we will call the max sliding window method by passing in the array so this is our array and the sliding window size is three so value of K is three so here the return return type of this method is list because we need to return the max of sliding Windows among this array which we will store and we will return so here at step one what we are doing is we are simply calling next CER element method we are passing in the array so this algorithm we have already discussed in our previous video I will also demonstrate one more time because the only difference is we are storing the indexes in this array not the actual values so when this method will be called this is our array so at step one we will create the result array now this result array will store the next greater elements so now as we need to find the next greater elements of this array what we do is we take the help of Stack so first we create a stack so stack is Leo data structure which means the element inserted last will be the first to be removed so we will use this property and we will figure out the next greater element of all these elements so now we will provide a for Loop where this I will start from the last index which is AR do length minus one and I will go till it is equal to Z it means it will travel in this direction and it will reach till index zero and I will help us in placing the next character element of each and every index so we are starting from the last index because it will make our job easy to find the next character element towards right so first we are actually finding the next C element of 11 so as 11 is the last index and we know that there is no no next greater element to 11 so here we are providing this if block we will discuss this later which says that we first check whether stack is empty or Not So currently stack is empty it means this condition comes out to be false and actually this stack will hold the next greater elements in the stack for the remaining array so as 11 is the last element we know that stack must be empty because there are no greater ments towards its right so we first check whether stag is empty or not so if stag is empty we simply put array do length into the result of I why we are putting array do length is because array do length is six and six suggest an index which is not in this array which also suggests that for 11 there is no next greater elements towards its right and we will also see that how this index will help us in later in the algorithm when we will we will find the max in the sliding window so after the F Els block now this 11 can be a next letter element for the remaining array so for example instead of 88 let's say if the value would have been 9 so for 9 11 would be the next letter element because 9 is less than 11 and 11 is the only element towards its right which is greater than 9 so therefore we will push index 5 it means we are pushing 11 on the stack like this so I will also write the values beside the index we are actually storing the index in the stack because we need to get a result in the form of indexes and you can assume that we are actually storing the values like 11 moving ahead we will decrement I now stack is is not empty so the first thing we do is we provide a while loop now inside this while loop what we are doing we are first checking whether stack is empty or not so stack is not empty so this much condition is true this condition is very important here what we are doing is we are first taking stack. Peak value so if you see stack. Peak is five and if I do array of five and then I do whether it is l less than equal to array of 4 it means we are comparing whether 11 is less than equal to 88 or not so this condition comes out to be true so the while loop will execute and what it will do is this 88 will simply pop 11 out of the stack because we had placed 11 in the stack thinking that there could be a lesser value here for which 11 could become the next greater element but as soon as we figured 888 this 88 will discard this 11 because for the remaining array even if we have any value here its next great element will reach till 88 and it won't go beyond because 88 is already greater than 11 and 11 cannot be the next set element of any of the element in the remaining array let's say if we had 9 here for example so for 9 also the next letterer would become 88 let's say if we had 10 here so for 10 also it would be 88 and let's say if we had 11 so for 11 also it would be 88 but there would be no such value here for which 11 can become the next greater element because we have found one element which is already greater than 11 so therefore the job of a greater value here is to remove the smaller values out of the stack because now they won't contribute in the next C element so first we pop five out of the stack so now stack becomes empty so this Val will terminate we check whether stack is empty or not and we know that if stack is empty it means for this value 88 we didn't find any element which is greater than 88 because stack is empty 88 will pop out the smaller elements and will stop till there are elements which are greater than 88 and those elements will lie for sure in the stack but if stack is empty after this while loop then for 88 there is no greater element towards its right so we simply put ar. length which we had place for 11 we suggest that for 88 also there are no greater elements towards its Right Moving ahead so now 8 can become the next greater element for remaining array till here so so we'll push the index of 88 here which is 4 which corresponds to 88 we'll decrement I I comes at index 3 and now we are figuring out the next greater element to 44 stack is not empty so this condition comes out to be true in the while loop stack is not empty and first we will take the stack do Peak which is four so array of four we will compare whether it is less than equal to array of I which is 3 so here we are simply comparing whether 88 is less than equal to 44 or not so this condition comes out to be false which suggest that 44 cannot pop 88 out of the stack because 44 is less than 88 and we can't pop 88 out of the stack because 88 can become the next next greater element of the remaining array so here for example for 77 its next greater is 88 only so therefore if a value is smaller it cannot pop this element out of the stack and if value is greater it can pop the element out of the stack so this condition we need to keep in mind so for cannot pop this element out of the stack because this condition came out to be false and now we simply check whether stag is empty or not so stag is not empty so the else part will be executed as stack is not empty which suggest that there would be some element in the stack which is greater than 44 because 44 could not pop that element out of the stack and that element will be for sure greater than 44 so at the result of I we store stack. Peak which is the index or indirectly we are storing 88 so we are Shoring index here four and then we will put value of I which is three on the stack like this because this 44 can become the next greater element for the remaining array so for example for 33 88 is also next greater element 44 is also next greater element but 44 is the first next greater element to 33 therefore we can't discard 44 we have to put it on the stack like this we'll decrement I I comes to index 2 stack is not empty in the Y loop stack is not empty and if we do stack. Peak we will get three so array of three we are checking whether it is less than equal to array of I which is 2 so we are simply checking whether 44 is less than equal to 33 or not so this condition comes out to be false which makes sense because 33 cannot pop 44 out of the stack because 44 is next greater to 33 and which is at the peak of the stack so therefore this while loop will terminate stack is not empty so this condition comes out to be false in the else part whatever is at the peak that will become the next greater to 33 so here we are storing stack. Peak which is three which suggest that we are storing a value three which is the third index value which is 44 this and then we will push two on the stack like this so let's say if we had 11 here so for 11 33 would have become the next letter element so therefore we can't discard 33 we have to push it on the stack so two comes here which is the index of 33 we'll decrement I stack is not empty so friend now here one critical step comes stack is not empty in the while loop we are checking array of 2 whether it is less than array of 1 or not so we are checking whether 33 is less than 77 or not which is true and we already discussed here that if we find any value which is greater than the peak value of the stack this value will simply pop the element out of the stack because if we see the remaining elements in this direction let's say if we had more elements here 33 cannot become the next set element for the remaining array because for the remaining array 77 can become the probable next greater element but 33 cannot because 33 is less than 77 and we need to find the next greater element so let's say if we add two here or let's say 33 here so for 33 also the next grer would become 77 and for no value here 33 can become the next grer because so for example if we had 87 so for 87 the next grer if it is not 77 then it will be 88 but we are 100% sure it won't be 33 because 33 is already lesser than 77 so therefore this condition comes out to be true and 77 will pop 33 out of the stack because now we can safely discard this value it will play no role in finding the next greater element two is popped out of the stack stack is still not empty and here if you see this condition we are checking array and passing stack. Peak which is three we are checking whether it is less than array of one or not it means we are now checking 44 is less than 77 or not so this condition comes out to be true it means 77 has rights to pop 44 also out of the stack because 44 also will not be contributing in the next greater element because we have found already one value which is greater than 33 and 44 so first we have popped out 33 now we are popping out 44 which is at index 3 so three will be popped out like this stack is still not empty so now here array of stack. PE which is four we are checking whether it is less than array of I so we are simply checking whether 88 is less than 77 or not so this condition comes out to be false because 77 cannot pop 88 out of the stack because 88 can become a probable next greater for the remaining elements in the array and in fact for 77 88 is the next greater element so therefore 77 will not be able to pop 88 out of the stack so this while loop will terminate because this condition comes out to be false stack is not empty so in the result array we are simply putting stack. Peak so if stack. Peak is not empty and whatever is at the top will become the next set element for the current value which is 77 so we are storing four here with s that if you go to index 4 you will find 88 which is the next greater to 77 and similarly will push one on the stack which is we are pushing 77 on the stack like this we'll decrement I I comes to zero index stack is not empty this condition also comes out to be false because 44 cannot pop pop 77 out of the stack because it is lesser than 77 so this Val Loop will terminate stack is not empty so for 44 the next greater element would be whatever the element is on the peak of the stack which is index one value 77 so we put stack. PE at the result array at ayat index like this and we push zero on the stack and if you decrement I it goes beyond the boundaries of this array so therefore this for Loop will terminate because I should be greater than or equal to zero so then we will simply return the result which is actually storing the indexes of next letter elements so this NG array will have the indexes and I have just written the values for these indexes below that so 44 is at zero index if you go to zero index of next greater element array you will find one which is the index so if you go to index one you will find 77 so I have written 77 directly here so that you can just relate that at four we have 88 like this at three we have 44 like this so now as we need to collect the Max and sliding window window we create a list by name result like this so this is a list of integers and here you can see that now we will start the for loop from IAL to 0 from here and this for Loop will go till array do length minus K why it is going till it is less than equal to array dot length minus KS if you see AR do length which is six if you do minus k which is three in our case so it will give three so it suggest that I will go till index 3 because now in this for Loop we are actually calculating the max in the sliding window and the last window will start from when I will be equal to 3 because the value of K is 3 so this window will go till this index from 3 to 5 and beyond that this condition will come out to be false and we will break from this for Loop so I will travel till index 3 because the last window will be this window which will actually cover the last window which is the last three elements of this array and beyond that we don't have to go so I will travel till it is equal to 3 so when I is equal to 0 we are looking at the first window which will be from 0 2 K - 1 which is 0 + 3 - 1 which is two so it will grow from 0 to 2 so this is the first window of size three and now our Target is to find the max in this window with the help of this next greater element array so as we have already discussed what we do is in the first step the element which is the beginning of this window we assume that it is the max in the sliding window so we are creating an integer value J which is our assumption that it always starts from the first element of this window so we are assuming 44 is Max in this sliding window which is being denoted by J so J is also pointing to zero index like this because value of I is starting of this window from zero so J is also starting from zero to index and now as we discussed that we need to confirm this assumption so what we do is we are providing this while loop and the condition in this while loop is 444 which is that index0 we simply go to this index we see there is one so we take this one out and then we are checking whether this one whether this lie in the range of the sliding window or not so here if you see if I do I + K 0 + 3 so this value will give 3 1 is less than three so it suggests that 444 which is at index 0er if we go to the next C element array at index 0o we are finding a value 1 which suggests that 444 its next greater element lies at index one which is value 77 and this 77 is actually if you see it is in the range of our sliding window it means our assumption that 44 is Max in this sliding window is false because the next greater element to 44 is 77 and this 77 is also in this sliding window so therefore now J will simply travel to index one because now our next assumption is 77 is the max in this sliding window so here we are doing that thing only 1 is less than three so this condition comes out to be true it means the next letter element for J which is 44 is 77 which is that index one and this one is lying in this sliding window so J will simply travel to that index which is the next greater element array of J which is one so it means J Will directly shift to one suggesting that now our assumption is 77 is Max in this sliding window so after this assignment J comes here and our assumption that 44 is Max in this sliding window comes out to be false and now our new assumption is 77 is Max in this sliding window but as this is a while loop we have to confirm that so now we are again checking that next greater element array of J which is 1 which is 77 which is our assumption we are going to this index we are finding a value four so now what we are doing this is giving us a value four so we are checking whether four is in this sliding window range or not and how we can figure out whether four lies in this sliding window is we know that sliding window starts from I so if we do 0 + 3 it will give three and we have to do less than that so it will go till second index which is the first three elements from 0 to two but here four which we evaluated from this part that 77 if we go to this index next greater element array of G J is four so this four is we are checking whether it is less than three or not so this condition comes out to be false which actually proves that 77 is Max in this sliding window because the next greater element 277 is 88 which is at index 4 which is actually beyond the boundaries of this window which proves that whatever element comes after the 77 in the sliding window will be lesser than 77 so there therefore now this Val Loop will terminate because this condition comes out to be false and we have found the first Max in the sliding window where window is starting from zero and going till index 2 so in the result we have to store 77 and 77 lies at array of J so here you can see our assumption was correct here so 77 becomes our first Max in the sliding window moving ahead now we'll increment I so I will come here at index one now we suggest that our sliding window will shift by one position ahead so we are done with this value and sliding window will shift by one position ahead like this I + K minus 1 so 1 + 3 will give 4 - 1 will give index 3 so it will take three values index one index 2 and index 3 because the size of this sliding window is K which is three and now we'll apply the same logic we assume that the first value of this sliding window is maximum and J Will point to that value so I and J at the start are pointing to index one which is 77 so our assumption is 77 is Max in this sliding window now to confirm that what we do is next G element array of J J is pointing to one so it means we are going to this index now and here we are finding a value as 4 which means that at index 4 we have 88 which is the next letter element of 77 and here you can see 88 is next greater to 77 but 88 is not in the sliding window range it is just outside the sliding window range therefore we are 100% sure that whatever the elements are here which is 33 and 44 they will be 100% sure lesser than 77 which means for this window 77 will become our Max because the next greater element to 77 is 88 which is at index 4 and it is lying outside the boundaries of this sliding window so this condition this part will give four we check whether it is less than I + K which is 1 + 3 which is 4 so 4 is not less than four so this condition comes out to be false it means that our assumption at the start only that 77 is Max in this sliding window comes out to be true so in the result list we will simply add the value at J index so array of J is 77 so it becomes like this so we'll increment I I comes to index 2 so our sliding window is shift ahead from 2 + 3 - 1 which is from 2 to Fourth index and now our task is to find the max in this sliding window so now you will understand more about the problem in this step we assume that 33 is is our Max in this sliding window which is being pointed by I so J starts from I which is 33 so this is our assumption so now we will confirm this assumption based on this V Loop what we do is J is pointing to index 2 I is pointing to index 2 and we are assuming that 33 is Max in this sliding window so what we do is we just check that it index two in the next greater element array which index lies so we find three and if we go to index 3 you will find 44 which is actually lying in this sliding window so it means the next greater element to 33 is 44 and it is also lying in this sliding window therefore our assumption that 33 is Max in this sliding window comes out to be false and this condition comes out to be true because next greater element of array of J which gives gives us value three we are checking whether this three is actually lying in the sliding window or not via this comparison so we are checking whether it is less than I which is 2 + 3 so we are checking whether three is less than five or not so this condition comes out to be true which suggest that the next greater element to 33 which lies at index 3 is actually in the boundaries of this sliding window so this comes out to be true and in the while loop J simply shifts to 44 because our new assumption is 44 is Max in this sliding window so I remains here and J comes here like this and now again we need to confirm whether 44 is Max in this sliding window or not so what we do is J is pointing to third index so we simply go to the third index we find a value 4 we check whether the value of index 4 which is 88 does 88 lie in this sliding window or not so here if you see 88 is lying in this sliding window but this condition is actually helping us figure that out 4 should be less than value of I is 2 2 + 3 4 should be less than 5 so this condition comes out to be true it suggests that the next greater element to 44 which is that index 4 here is also part of this sliding window so the condition in while loop comes out to be true and our assumption that 44 is Max comes out to be false so now J will simply shift to 88 via this assignment and now once again we need to confirm whether 88 is Max in this sliding window or not if we go to this index you will see the value is six which suggest suest that for 8 there are no greater element towards its right because the last index is five and therefore we were storing array do length here which suggest that there are no elements greater than 88 so here this condition 6 should be less than 5 comes out to be false so this while loop will terminate and we will simply add 88 into the result list like this so for the third window 888 becomes the max we'll increment I and I is actually equal to ar. length minus K which is three so this Loop will run one more time because the sliding window will shift by one position and now it will cover all the elements of the array we assume 44 is Max so J is pointing to 44 we go to this index we see the next greater to 44 is lying at index 4 which is 88 here so we are simply checking whether 44 is Max in this sliding window or not so this will give us value four we are checking whether it is less than I + K which is 3 + 3 4 is less than 6 so this condition comes out to be true because 88 is next greater to 44 and it is lying in this range so therefore J is simply shift to 88 now via this assignment like this and now we'll again confirm whether 88 is Max in the sliding window or not so we go to this index we find six we check whether it is less than I + K which is 3 + 3 so this condition comes out to be false it suggests that the next letter element to 88 is beyond the boundaries of this this array and our sliding window is still the last index so our answer is 88 so this Val Loop will terminate and to the result list we will add array of J which is 88 so 88 comes here so we'll increment I so I will come here but here you can see this condition comes out to be false because there is no more window left of size three so therefore the for Loop will terminate and at the end we will return return our result list storing the max in the sliding window which is 77 77 88 88 so the first 77 is from here to here which is this value the second 77 is from here to here the 88 is from this window to this this window and the last 888 is for last window which is from here to here so friends this was all about the sliding window maximum problem I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem maximum sum sub array of size k now let's move ahead and see what this problem is and how to solve this so here in this problem we are given an array of integers like this and we are given a value of K which is a integer value now this K value you can treat it as a sliding window of size K now this sliding window is moving from very left of the array to very right and it is moving 1 one position in this direction so at the start if the value of K phase three it means the sliding window is taking in first three elements and these three elements also form a sub array of size K now our task is to find maximum sum of any contiguous subarray of size K now contiguous means that the element should be next to each other and we need to take a sub array of size K only we need to evaluate their sum and whichever sub array has the maximum sum we need to return that sum so let's say if we are given with this input array and sliding window is of size K which is three so our output would be 16 now how this 16 came is let's say our first contigous sub aray of size Cas is from zero index to Second index so it is 0 1 2 3 4 and 5 from 0 to two we have a window of size K this this is our sub array and the elements are continuous to each other now if we take the sum of these three elements we will get a value 12 now after that what we do is we move the sliding window to right by one position so two goes out of the sliding window and five comes into the sliding window so now our three elements are this 7 3 and 5 if we do the sum of this three elements we get the sum as 15 then we move the sliding window ahead by one position so s goes out of the sliding window and8 comes into the sliding window so now this is our sliding window if we do sum of this three elements we get sum as 16 and at the end the sliding window moves by one position and reaches to the end of the array and this is our sliding window if we do sum of the three elements the sum is 14 so here you can see we had six elements and if our sliding window is of size three we saw there were four sub array of size three from 0 to 2 from 1 to 3 from 2 to 4 and from 3 to 5 and their sums are 12 15 16 and 14 so among these four sums 16 is the max so our answer should be 16 it means we are telling that we have found one sub array having three elements three five and 8 if we do their sum we get a maximum sum of 16 and here window size is whatever the value of K so friends now let's move ahead and see that how we can solve this problem so let's suppose we take this array and value of K is three it means the sliding window size is three and it also means that at a time we can only see three elements in the array and for those three elements we do their sum and we we keep on doing their sum for all the sliding windows and whichever sum is the maximum we simply return that sum now here can see one way to solve this problem is let's say we take a for Loop and inside that we take another for Loop so the outer for Loop let's say it's point to Z index and the inner for Loop will take three elements because value of K is three so it takes 2 7 and three and do their sum so let's say J goes from 0 to two and do their sum so we get a value as 12 now after evaluating the first window I will simply travel to this index and J will take the next three elements so this this and this if we do that sum we get 15 and similarly it keeps on going till I reaches here for the last window and do the sum and as we are evaluating the sum for each window like this we compare that which is the maximum sum and at the end we simply return that sum so for 3 5 and 8 this window the sum would be maximum which is 16 so if we solve the algorithm using two for Loops this problem is very easy to solve so this solution is is roughly time complexity of O into n into K because we are traversing the each time we taking K elements so the time complexity is O of NK so this time complexity is not efficient we need to solve this problem in better time complexity let's say of O of n so if I remove everything so here with this approach I was here and then we picked three elements did their sum and then we moved I here and we then picked the three elements so here if you see that for the first sliding window 7 and three were part of the sum for next sliding window this sliding window 7 and three were part of the sum again and only five was included and two was excluded so we did the sum again for these two elements and similarly for the second window we took the sum of 7 3 and 5 like this but when we went to the third window we again took the sum of 3 five so this much part we are doing the sum again in the for Loop so this is actually increasing our time complexity now how to solve this problem in a better time complexity is here you can see what we do is as we need to take the sub array and it should be of size K so for the first window we take the sum directly we simply add 2 7 and 3 and we get sum as 12 so this is our first window where we do the sum directly now what happens is we shift the window to ride by one position because we need to take now the next sub array from index 1 to 3 so when we do this shifting what happens is the window in blue becomes our new window and the window in yellow was our old window but here you can see in both this window 7 and 3 were included in the sum so let's say if we do 2 + 7 + 3 we get 12 and then we shift the window ahead we do 7 + 3 + 5 and we get sum as 15 so here you can see with this nested for Loops we were evaluating this sum again which was in the middle of both the windows now if we stop calculating this sum again and again we will get a better time complexity here you can see when window was here we did a normal sum because we need at least K size window so at the start we are doing the sum normally 2 + 7 + 3 we got 12 now when this window shifted ahead for the next sum here you can see two goes out of the window so if you see the blue window two went out of the window and five comes into the window so five comes into the blue area and two went out of the blue area because our current window is from index 1 to 3 of size K now here you can see we know the sum of first three elements which is 12 now as we are moving window ahead two goes out of the window we know that sum is 12 and if we do minus 2 our sum will be 10 which is the sum of these two elements and if we add only file to it we get 15 which is the sum of our next three element which is in the blue area so using this property will reduce the time complexity of the algorithm so now what we do is we simply perform three steps First We Take sum of first Elements which is 2 + 7 + 3 so let's say it give value as 12 now as we are shifting the window to the next element so that we can evaluate the next window sum what we do is we don't have to recalculate 7 + 3 + 5 what we can do is we already know 7 + 3 is already in the sum in the 12 we just subtract the element going out of the sliding window so the element which is going out of the sliding window is two so we are subtracting two to get the sum of the remaining elements in the previous window which is 7 + 3 which is 10 and the third step is as 5 is getting into the window here we simply add the new element coming in the sliding window so we are simply adding five which is our new element to 10 to get 15 so if you see 7 + 3 + 5 will give 15 which is the sum of our next window which starts from 1 to 3 and similarly this window goes on like this one one element goes out of the window and new element comes into the window so the element which is going out of the window we simply subtract from the sum and the new element which is coming into the window we simply add that we also compare 12 with 15 then with 16 16 then with 14 and at the end we will figure out that 16 is the maximum sum in the sub array of size K so this would be our answer and also friends here you can see the value of case3 which is very small so here you can see these are only two elements coming let's say value is K is 100 so if one element goes out of the stack we don't have to calculate the 99 elements sum again and again we can simply subtract one element and add another element and we will get the sum of the next 100 elements so this makes our algorithm efficient now let's move ahead and see the demonstration of this algorithm step by step so before we start if you want to master data structures and algorithm then you can subscribe to my channel and click the Bell icon so that you never miss any update so here is the algorithm the method name is Max subarray sum which takes X in the array and a value K which is the size of our window so this is our array and value of K is three it means we are taking a sliding window of size three as we want to evaluate the maximum sum in a subarray of size K we create integer variable Max sum because we need to return a integer value from this method so here at the end we will return the max sum so we initialize a variable Max sum with zero then we create a variable window sum so as we want to take the sum of sliding window of size K so let's say this is a sliding window of sizec so for this three elements whatever their sum will be we store in the window sum and similarly for the next window sum we store in the window sum so we create a variable window sum having value zero at the start now we create integer value start which will start from the zero index so this value is basically an index value like this that the initial value is zero for start variable we will see its significance later that why we have created this start and now we provide a for Loop and inside this for Loop we will do the window sum we'll compare the window sum of different Windows of size K and whichever is the maximum sum we simply evaluate here so what we do is we take a integer variable end we initialize it with zero and this end will go till array dot length so array dot length will be six so end will go till the last index which is fifth index so here end will start from the zero index so in our previous slide we discussed the three steps the first step is we simply take the sum of first K elements because the first window is of size K so at the start we need to include the first K elements so that we can get a sum so here you can see the first window of size K will go from index 0 to 2 so it means for this window we will straight away calculate the sum because we need to return the maximum sum of a sub array of size K so we need at least K elements to evaluate the sum and then compare with the next windows so this if condition if you see here will help us achieving that so value of end which is 0 is less than 6 so this condition comes out to be true now to our window sum as we need to evaluate the sum of first three elements this will get stored in the window sum because this is our first window so what we do is to window sum we add array of end which is the first element which is two so here initially the value of window sum is zero plus we are doing array of end which is two we are adding the first element and assigning it to window sum so window sum will become two like this and here you can see that we need to evaluate the sum of first K elements so this condition if n is greater than or equal to K minus 1 it means we are saying K - 1 is 2 because value of K is three if n is equal to 2 or greater than 2 then this if condition will come out to be true so at the start value of end is zero so 0er is not greater than two or equal to two so it means this if condition comes out to be false and this if block won't get executed so here you can see if n comes to index 2 here at that moment 2 will be this condition will come out to be true so it means when end has reached here we have evaluated the sum of first K elements already here we added the first element then we will add seven and then we will add three so at that moment end will be at index 2 and when end will reach here then only our main algorithm will run and then it will keep on running for every window we will see that later so currently this condition comes out to be false because 0 is not greater than equal to 2 we will increment end so end comes to index one we take window sum 2 we add array of end which is 7 and we will assign it back to window sum so window sum will become 9 now this is the sum of first two elements we need at least first K elements to start comparing for the maximum sum so this condition 1 is greater than equal to 2 it still comes out to be false we will increment end and comes to index 2 we take window sum which is 9 we simply add three to it so it becomes 12 like this and now here you can see that our first sliding window is from index 0 to 2 it means we have taken the sum of first K Elements which is 2 + 7 + 3 which is 12 and now here you can see end is at index two so value of end is two and it is greater than or equal to K - 1 which is 3 - 1 which is 2 so this condition comes out to be true so now if blog gets executed so here as we have calculated the sum of first K elements it means we know the sum of first sliding window of size K which is 12 at the start Max sum is zero so now what we do is we simply compare Max sum and window sum and which is the maximum between these we simply assign to Max sum so here what we are doing is as we have calculated the sum of first element which is the first window initially Max sum is zero so you can think of this condition is like we are doing if window sum is greater than Max sum then to Max sum we are assigning window sum like this So currently Max sum is zero window sum is 12 so window sum is greater than Maxum so this tells us that we need to discard this Maxum and our new Maxum will become 12 so maximum value will become 12 like this so as we discussed in our previous slide that after evaluating the sum of first elements this sliding window will shift ahead to get the sum of next K elements so two will go out of the window and five will come into the window so we also know that the second step we discussed that we need to subtract the element which goes out of the window so here we are doing the same and here you can see this start is actually helping us to know which is that first element of that window we know that start we initialize with the the zero and end move till the index two so if you see our window is from start to end having three elements now when this window will shift ahead at whichever value start is pointing that will go out of the sliding window which means two will go out of the sliding window so what we are doing is we are not recalculating the sum now so here now what we are doing is we are simply subtracting the element which is going out of the sliding window so we are taking the window sum and we are simply subtracting the element which is at start index which is two so our window sum will become 12 - 2 which is 10 like this and this window sum will have the sum of these two elements so for the next window we don't have to calculate this window sum again we can simply reuse that so now as two went out of the sliding window so for the next sliding window it will start from index one so we simply increment start so start comes at index one we'll increment end end comes to index 3 with suggest that now our new window will be from start to end like this which means these three elements and we know that when we shifted this window here two went out of the window and five came into the window so here you can see five came into the window so our third step was we add the element which comes in so we are simply adding five to our previous evaluated window sum which is 10 so it becomes 15 it means with just one sum we now have the sum of these three elements we didn't evaluate 7 + 3 again we just added five to our previous calculated sum which give us 15 this condition comes out to be true because value of end is three 3 is greater than equal to 2 and here you can see our window sum is 15 Max sum is 12 we simply compare these two values and if window sum value is greater than Max Su we simply assign that value to maximum so here we are taking these two values which is 12 and 15 and which whichever is the max among this two we are assigning it to Maxum because we need to return the maximum sum of a sub array of size K so we just evaluated the sum of second sub array of size K and we simply compared it with the max sum so we got 15 from this a so our Max sum will become 15 from this statement like this and now after we did the sum of this sliding window from here to here we know that now this sliding window will move ahead and S will go out of the sliding window which is which is the element to which start is pointing so this will go out of the window and we know that we need to subtract the element which goes out of the sliding window so that for the next sliding window we can evaluate the sum easily so window sum is 15 we do minus 7 so it will give 8 and 1 7 will go out of the sliding window we know that now next sliding window will start from index 2 so we do start Plus+ so start will come at index 2 we will increment end end comes to index 4 which means now our window will start from index 2 to 4 like this now here seven was excluded from the sliding window and8 was included in the sliding window because this sliding window shifted by one position so three and five remained there and 8 was included we know that we need to add that value which comes in so here we are doing the same thing we are adding the value8 into the previous calculated sum so 8 + 8 will give 16 this condition is true because 4 is greater than equal to 2 the Maxum is 15 and this window has the sum of 16 8 + 5 + 3 will give 16 we know that we have found one window whose sum is 16 which is greater than the previous Max Su so whichever value is greater among these two values we simply assign to Maxum so max Su will become 16 now we are done with this window so now for the next window three will go out of the sliding window and one will come into the sliding window so if three is going out of the sliding window we are taking taking the sum which is 16 and we simply subtract 3 so it becomes 13 and as our new sliding window will start from index 3 we simply do start Plus+ so start comes at index 3 we'll increment end end comes to index 5 it means now our sliding window is from index 3 to 5 this is our last sliding window and one was added to the sliding window so we simply we do window sum which is 13 + 1 which gives 14 we assign this 14 back to window sum so window sum will become 14 this condition is true because value of end which is five is greater than equal to 2 now our Max sum is 16 and window sum is 14 so here you can see the max sum is 16 window sum is 14 so we already already have a maximum value in Maxum so Maxum will remain to the 16 only because 14 is less than Maxum and now for the next sliding window we simply remove five from the sum so it becomes 9 we do start Plus+ because next window will start from index 4 but here you can see if we do ++ so end will go out of the boundaries of this array which also suggests that there is no window left of size K now so therefore this for Loop will terminate and here you can see at the end we are returning the max sum is 16 so which is our answer so which came from this sub array of size K 3 + 5 8 8 + 8 16 so friends here you can see we used only one for Loop and we evaluated the maximum sum of a sub array of size K we need to keep these three steps in mind that at the start we do the sum of first elements and then based on this condition we do our rest of the steps that one element goes out of the window and one element comes into the window so the element which goes out of the window which is array of start we subtract from the window sum and in the next iteration of for Loop which is our next window we simply add the element which just comes into the sliding window and therefore this property help us in evaluating the sum in a very efficient way we don't have to recalculate the sum of every K elements so friends this was all about the problem I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem longest substring without repeating characters so let's move ahead and see what this problem is and how to solve this so in this problem we are given a string like this our task is to find the length of longest subring without repeating characters so first of all let's understand what is a substring so let's suppose if you given a string like this test so here a substring is a part of the string in which we will take out the sequence of characters and those sequence of characters should be contigous it means they should be next to each other so the property a sub string has is first it should lie within the string so it lies within the string second the sequence of characters which we are are taking those should be contiguous which means they should be next to each other so for example if you want to find that how many substrings are there in this string so if we start from t one substring would be T other would be te t s t s here you can see this substring should be within the string and it should be contigous it means they should lie next to each other so we can't take a substring like TT one t here and another T here we need to take a part of a string which is contigous so if we start from E it would be e e s EST EST if you take it from s it would be S St and if you take the last T it would be like this so if the length of the string is let's say n so the total number of substrings would be n into n + 1 by 2 so here n is 4 so if we put 4 here we will get 4 into 4 + 1 by 2 which is 4 into 5 by 2 which is 10 so here you can see 1 2 3 4 5 6 7 8 9 10 so we need to keep in mind a subring should lie within the string and the part of the string that we are taking it should be continuous so our task is to find the length of the longest substring in such a way that character should not be repeated so if you take this example here ABC is length three but as soon as a comes we get a repeating character so we discard this a and if we take b c a the length is three because after that we have found one B and B is repeating in B CA so we discard this B now we start from C so C A and B length is three we can't move ahead because we have found a repeating character C so we discard this C and then we find a b c and again we find a b so length remains three so after we find this B we can discard this A and B together because they won't contribute to the longest substring now so c and b we'll take two characters and then we find a repeating character so we discard this CNB and at the end we'll find one B so the length of the longest substring without repeating character is three it can be formed from a b c b c a c a b a b c that's it because after that we are getting a substring of length two like BC CB and at the end we are getting only one B similarly in the this example we have a string B B BB so the longest substring without repeating character would be one because all the characters are repeating here PW becomes two because we have found one W here which is repeating so we'll discard this p and w then we'll go here and then we will find one W so this length is three and as soon as we find w we discard this W and then we start our substring from K we will find K eew which is length three so the length of the longest substring without repeating character is three so let's move ahead and see the demonstration of this algorithm step by step so before we start in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update so here is the algorithm to find the length of the longest substring without repeating characters so method name is length of longest substring it takes in a string s and Returns the length of the longest substring without repeating characters so let's say when we call this method by passing this string so s will become like this P ww k e w so if we see this string internally it will be a character array like this so friends the basic idea behind this algorithm is we create a hashmap like this where key is the character and value is the integer so here as we need to find the length of the longest substring without repeating characters what we are doing is we will store the character along with its index into this map so that when we encounter a repeating character we simply look up into this hashmap and we simply figure out that when that repeating character last occurred so that we can start our new substring search from a index just after that so you will understand more later in the algorithm as we want to return the length of the longest substring without repeating characters we will be storing it in the max length so at the start max length will be zero like this so as we want to identify the length of the longest substring without repeating characters we will process each character one by one from left to right so let's say if we take these two characters p and w so the length of this substring is 2 so in this algorithm we will take the help of two variables start and end so this start and end will be actually referring to the indexes so let's say for p w let's say start is here and end is here so if you see closely start and end basically forms a window like this which has some characters so this window is starting with this start variable and ending with this end variable and those are pointing to the indexes so if you want to know the length of this substring we can use the formula as end minus start + 1 as these are pointing to the indexes it would be 1 - 0 + 1 so we'll get the answer is two which is the length of this substring so you can treat this as a window from start to end why we are using this two pointer is we need to identify the length of the longest substring without repeating characters so we need to put start at a point from where we are evaluating the length of the longest substring and we will move end in this direction so that as soon as we encounter a repeating character we stop and there itself and using start and and end we can figure out the length of that particular substring with this formula so we will understand more when we proceed ahead so as we haven't processed any of the node so start will point to zero index like this and as we discuss we will move end into this direction and starts from zero because now we are processing this first character and end will go till the last index which is five so in the string class we have a method car where if you pass any index it will return back the character at that particular index so if we call s. car at zero because end is at zero index we will get a value as P which we will be storing in the right care like this so here we are asking the string to return the character at this index which is zero index which is p and that P we are storing in the right care like this so as end is moving in this direction we have denoted it by right care so now the first thing we do is we simply find whether Right Care is present in our hashmap or not so we provide this if condition map do contains key where we pass the right care and if the map contains that key it will return true we will understand more about this part later so currently map. contains key will return false because this key is not present in the hashmap so here for the first care we know that it's a subring and it doesn't have any repeating character and we also know that in the hashmap we put the care along with its index so we are putting care along with its index so it would look something like this p and we are putting value as zero which is end so here you can see currently our window is here where start and end are pointing to only single character and our max length is zero because we haven't processed any character so with this formula we will identify the number of characters in this window so end minus start + 1 so it would be 0 - 0 + 1 so the length of the substring is one we are comparing it with max length that whichever is the max we will directly store in the max length because at the end we have to return the max length so for this small substring the max length will become one because here it is zero and this gives value as one so whichever is the max we are storing in the max length so we will increment end so why we are incrementing end because with the combination of p and w we can get a substring which is of l two and it doesn't have a repeating character so therefore start will remain at index zero only and we will move only end in this direction so first we'll get the character at index one now so right care will become w like this we will check whether W is present in this map or not so this condition comes out to be false and we will simply put W along with its index in the hash map so it would look something like this now here max length is one and if we use this Formula 1 - 0 + 1 it will give the value as 2 so here you can see that we have a window of Len two which is a substring PW which doesn't have repeating character so this will give value as two so now our max length will change it will become two we'll increment end so end will come to index two so first we will identify the character at index to which is W So Right Care will become W so friends here you can see that our hashmap actually contains W so when we will call map. contains key we'll pass the character as W it will return a value true so this if condition comes out to be true because we have W already in the hashmap it means we have found a repeating character and we can't include this W into this substring so here now now what we do is till this point we have found the length of the longest substring as 2 which is PW but as soon as we encounter w we can't include this W here because we will have a repeating character so we need to move this start after W so that we can discard one of the W and how we can do that is as W is present in this hashmap at index one we will first get that index it will be one so this index will be returned and we have to just start after this index so we will add + one and currently start is at zero index so we will take the max of start and this value so 2 is greater than zero so now our start will go to the index 2 like this we suggest that we have found W here so the next longest substring will include another W so we need to discard this W and start just after that so therefore we are looking up into the hashmap to see when this W occurred last and then we start finding a new substring from an index just after that which is 1 + 1 because W was found at index one so start comes here so it means we can simply discard these two characters and start finding the length of the longest substring from index 2 now so as we are starting from index 2 because start is pointing to index 2 we will put W along with its index in the hash map so this value will be overwritten to two and for this single substring we know that max length is two which we already found as PW so 2 end minus start + 1 so 2 - 2 + 1 will give one so one so the length of the longest substring without repeating character vors till this point will remain two we will increment and and comes to index 3 at index 3 we have a character K So Right Care will become k k is not present in this hash map so this condition comes out to be false so we will simply put k with index 3 into our hashmap like this the max length is two end is at index 3 and start is an index 2 so 3 - 2 + 1 it will give two so the max length will still remain two because this part is two and math. Max will return a maximum value between this two so two will be assigned to max length like this will increment end end becomes four the character at Fourth index is e So Right Care will become e e is not present in this hash map so this condition comes out to be false so we will put e into this hash mmap along with its index like this so here you can see max length is two n minus 2 + 1 it will give three so this part will give three so here you can see we have found one substring w k e without repeating characters which has a length of three so therefore now our max length will change because math. Max will return a value three when it's compared with two so max length will become three which suggest that we have found one substring of Len three without repeating characters will increment end and becomes five the character at fifth index is W so right car will become W so friends here you can see that W is present in this hashmap so This condition comes out to be true and here what we are doing is with this map. Get Right Care we are just figuring out that when this W occurred last in this character array so this hashmap will bring us that index the W occurred at index 2 so we suggest that whatever the substring we found till this point we can't include W because if we include W that will be repeating character so in order to include W for the rest of the string we have to discard this W so for that we need to know the index so when we identify that index we simply shift start to a character ahead then what we find from this map. Get Right Care so here it gives two so we simply just shift by one position by adding plus one start was at two so math. max among two and three will give value as three so start will now come to index 3 like this we suggest that our new substring should start from this index so now we simply put W into the hashmap along with its index so the index value will be updated here it will become five and here you can see max length is three end minus start + 1 so 5 - 3 + 1 will give 3 so this comes out to be three which suggest that one more substring is k e w which is longest and without any repeating character but among these two lengths both are same so the max length will still remain three only so now we increment and so end goes beyond the boundaries of this SC array so this for Loop will terminate because end should go till it is less than S do length so at the end we will simply return a value three so so friend let's suppose here if we had a value like a so this for Loop would have run one more time so here this a is not in this hashmap so we simply put a here like this a with the index 6 and here our max length would have changed initially it was three end minus start so 6 - 3 + 1 would have given four so this would have become four and our answer would have become four which would suggest that the longest substring without repeating character is k e w so friend this was all about this problem we can solve this problem by keeping a sliding window of variable size which has a range from start to end and whatever the characters are between start to end those number of characters will give the length of that particular window and we can use this hashmap to figure out the repeating characters so that we can start our new window from a different index by making a look up into the hashmap for the character which just got repeated so friends one important thing to discuss is that why we are using math. Max and we are taking whichever is the max from the start and from this statement so in order to understand this let's suppose we are given with this string P wwp so the example which we took was like this so in our previous example till this point everything Remains the Same the w we placed last in the hashmap at index to and after that we went to K so instead of K now we are going to P so we will see what the difference is so when we will increment end end will come to index 3 so here instead of K now we are taking the right car as P by this and here you can see that map actually contains P at index0 so this condition comes out to be true so friends here you can see that if you only provide this condition if we do map doget right care we'll get value as zero and if we add + one to it we'll get 1 so we can't discard this p and start from index one because then our substring will have wwp and here currently the max length is two so when we will do end minus start + 1 so end is three and this start will come here so Min -1 + 1 so our answer will be three so at the end we will return return max length as three so which is wrong because here we are playing with the indexes and this algorithm doesn't know that we have encountered a w here and this this is a substring with a repeated character so one thing to keep in mind is if our start is an index 2 and we have found one character which is our index 3 and when we look up this character in The Hash map if that character comes beyond our start which is the current case at zero so this P last occurred at index zero so we don't have to consider this P or this index X because currently we are processing this subring from start to end and this P has occurred in this region so therefore if we do map. get right care we get index zero if we add + one we get this index one but our start is already at index 2 here so therefore we are doing this math. Max because we have to assign the maximum value between these two statements to start so if start is already ahead of this statement then we don't shift start back we keep the start at that point only so this is the one important thing to consider for this algorithm now after this statement start remains at index 2 and we simply put three here and here the max length is two if we do end minus start + 1 we will get 3 - 2 + 1 which is equal to 2 so this is the length of that substring so when we will do math. Max our answer will be still two because here you can see the longest substring without repeating character is two this or this so therefore this is the important condition to keep in mind so friends I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and click the Bell icon so that you never miss any update thanks have a nice day hello everyone so in this video we are going to discuss a problem symmetric tree so let's move ahead and see what this problem is and how to solve this so in this problem we are given with a root of a binary tree like this which actually holds this complete tree now our task is to check that whether this binary tree is mirror of itself which means we need to check whether this binary tree is symmetric around It Center or not so let's suppose we are given with this binary tree and we need to check whether it's a symmetric tree or not so for this binary tree if we draw a line like this so this line is nothing but a line of symmetry so around this line if a binary tree is a mirror image of itself then we consider that binary tree as a symmetric binary tree so usually when we talk about symmetrical images let's say if I take a rectangle and if I want to find out whether it's a symmetrical image or not what we can do is we can create a line of symmetry and if we rotate the image like this around this line of symmetry let's say denote this as a b c and d so if we rotate this image around this line of symmetry you will see that a will come over b and c will come over D so if if that is the case then this shape is a symmetrical shape so if any shape is rotated around its line of symmetry if the left part superimposes the right part then that shape is a symmetrical shape so here can see for this binary tree the line of symmetry goes from the root and we have to determine whether this binary tree is a mirror of itself that is we need to check whether it's symmetric around its Center so this is the center so if you rotate this binary tree you will see that after the rotation two will come over this two this four will come over this four and this three will come over this three so we can come to know that this binary tree is symmetric around its Center because one will remain there itself and if we take this example here you can see that two will superimpose two but as we are rotating this binary tree around the line of symmetry when this two will superimpose this two this three will come like this it will not superimpose this three so therefore this is not a symmetric binary tree because as we are folding this binary tree around this line of symmetry when this two will superimpose this two this child at right will come towards the left of it and so this three is not superimposing this three so therefore we can consider that it's not a symmetrical shape also one thing to note here is the symmetrical shape is actually equidistant from the line of symmetry so this two and this two both are at a equal distance from the line of symmetry this four and this four both are equidistant from the line of symmetry and similarly this three and this three but here you can see this two and this two are equid distance from the line of symmetry this node three and this node three are not equidistant from the line of symmetry therefore it's not a symmetric binary tree so friends the basic idea behind this algorithm is if I remove this so let's say if we are on root and this root has only one tree note like this so therefore we can directly consider that it's a symmetric binary tree because we need to find whether the binary tree is symmetric around its Center so this is the center if this root is null then also we'll return true that it's a symmetric binary tree so here now if binary Tre is given like this so after the root if we are going on the left so we will reach to this node and if we look into the the mirror then this left should be equal to this right so that we can come to know that till this point the image is symmetric now when we reach here and here if we are going towards left then in the mirror it would look like we are going like this towards right so we land here we compare this values and we know that till this point also the tree is symmetric now if we go towards right so in the mirror it would look like we are going towards left and we reach to node four and we compare its values so those are same so 2 is equal 2 3 is equal to 3 and 4 is equal to 4 and after that there are no more nodes so we can consider that this is a symmetric binary tree so here let's say if you're going towards left then in the miror error we are going towards right so we reach here we compare those values they are equal so now here we have a null value if we are going towards left then in the mirror image we are going towards the right so here we have reached to the null value but here we have reached to a actual node having value as three so when we will compare them they won't be equal so we can directly come to know that this is not a symmetric binary tree so one property to remember is if we have mirror here and if you're are going towards left then in the mirror image you are going towards right and if we going towards right then in the mirror image we are going towards left so similar Technique we will apply over the binary tree to figure out whether it's a symmetric or not so now let's move ahead and see the demonstration of this algorithm step by step so let's say if we are given with this binary tree and we need to check whether it is symmetric or not so when we will call this method is symmetric by passing in the root it would look like this that root is pointing to this binary tree and this method will return a Boolean value stating that this binary tree is symmetric or not so here the first thing we check that whether root is equal to null or not so if root is equal to null then we can directly return true because there is no binary tree and there is no node so the binary tree is actually symmetric around its Center so we are returning true so this condition comes out to be false because root is pointing to a node having value as one so friends we will use Tag data structure to figure out whether this binary tree symmetric or not so here we will initialize a stack like this so stack is a Leo data structure where the element inserted last will be the first to be removed and we will use this property to figure out whether the binary tree is symmetric or not so we will see that later so here you can see if root is not equal to null it means there is one node till this point the tree is symmetric and let's say if I draw the line line of symmetry like this so we know one of the property of this line of symmetry is let's say on this side if we are going towards right then in the mirror image it would look like that we are going in this direction and similarly if you're going in this direction then in the mirror image it would look like we are going in this direction so therefore in the stack what we are doing is we are pushing root dot right which is two so it means if we look into it Mirror Image then we need to put this two into the stack as well because we know that on this side if we going towards right it means on this side we are going in this direction so therefore we need to compare this two with this two so if we going towards right on this side of mirror then we are going towards left on this side of mirror so we are putting both the twos into the stack so that we can pop them out in pair and compare them so this thing we will do in the while loop we will check whether stack is empty or Not So currently stack is not empty so the condition in while loop comes out to be true so here this two so here first we place the right one so this is the right one and this is the left one so we will create two notes N1 and N2 we will pop the notes from the stack and assign it to N1 and N2 so first we'll pop two out which is on the left side and assign it to N1 then we will pop the right one and assign it to N2 so after getting N1 and N2 we need to compare these two notes now so the first thing we are checking is whether N1 and N2 both are null at the same time or not so if both N1 and ns2 are null simultaneously then we will continue with the while loop so let's say this is our line of symmetry and let's say this is our node one and this is our node two so here both of them are null it means the symmetric property holds true for both of this node so we will simply continue but here you can see N1 is pointing to two N2 is pointing to two so both of this condition comes out to be false and then this condition is very important because it will directly return false that whether the tree is symmetric or not so here we check that whether N1 is equal to null and N2 is equal to null so if both of the conditions are true that N1 is null and N2 is null so we can continue so if this condition comes out to be false we suggest that there could be a chance that either N1 or N2 can be null so if N1 is null we directly return return false because here we have already checked whether N1 and N2 both are null simultaneously or not so if this condition came out to be false we are simply checking first that if N1 is equal to null then we can directly return false or if N2 is equal to null we can directly return false because this two cannot be null simultaneously based on this condition or if their values are not equal So currently N1 is not equal to null N2 is not equal to null N1 do well which is two is actually equal to n2. well so this condition also comes out to be false which proves that till this point the tree is symmetric and this two and this two are actually equidistant from the line of symmetry so we simply move ahead and now what we do is as we are on N1 and we are done checking these two notes N1 and N2 now what we do is if we want to proceed add in the B tree to figure out the rest of the elements are symmetric or not we know that if we are going towards left from this two to three then in the mirror image it would look like we are going towards right and if we are going towards right then in the mirror image it would look like we are going towards left so these two notes are symmetric so now we have to compare n1's left with n2s right and n1's right with n2s left and if those are equal then we keep on doing this thing till the complete binary Tre is empty so here in the stack what we are doing is we are pushing n1's left which is 3 so this is the first node like this and as we need to put them in pairs so that we can pop them out and compare with N1 left we need to put n2s right like this so n 2's right is three so this is second and then we will put n1's right which is null and along with we will push n2s left which is the mirror image of n1's right so null will come like this this is the fourth push stack is not empty so now we will pop in pairs and we will compare them so when we'll do stack. pop fourth node null will be popped out which is n2s left which is four so N1 will point to n 2's left like this and then we will pop one more element which is three which is n1's right so N2 will point to n1's right like this so here you can see that now we are actually comparing the mirror images nodes comparing N1 and N2 which are actually symmetric nodes across this line of symmetry so if N1 is null and N2 is null then we will simp simply continue So currently N1 is null and N2 is null so which proves that till this point the tree is symetric so we will continue stack is still not empty we will pop the node which is n 2's right so now N1 will point to n 2's right which is this node and then we'll pop one more node which is n1's left so N2 will point to n1's left and now we'll simply compare them so here you can see that we are using the stack data structure which is popping the elements in pairs and we have pushed in such a way that this is the line of symmetry that if you're pushing any node in the left side then in the mirror image we have to push the right side node so that we can compare them and come to know that whether they are symmetric or not so N1 is not equal to null and N2 is also not equal to null here you can see N1 is not equal to null or N2 is also not equal to null N1 do Val is 3 n2. Val is 3 so 3 not equal to 3 comes out to be false because 3 is equal to 3 so this condition comes out to be false so it means that till this point the three symmetric and now what we do is we perform the same steps on this node and this node so first we will push n1's left so n1's left like this so if we are pushing n1's left we are going to the left so on this side we have to take its corresponding node on the right side like this so we are putting n2s right which is also null then we'll push n1's right which is this null and correspondingly we have to push n2s left like this stack is not empty we will pop this null value which is n2s left and assign it to N1 so N1 will come to n2s left left like this we will pop this null which is n1's right so N2 will come to previous n1's right here so here you can see N1 is equal to null and N2 is equal to null at the same time so therefore we will simply continue stack is still not empty so now we'll pop both the nulls so first we'll pop n2s right so N1 will point to previous n2s right which is this and we will pop this null also which is n1's left so previous N1 was here its left is this so N2 will point to previous n1's left N1 is null and N2 is null simultan l so therefore this condition comes out to be true so we'll simply continue we suggest that this null and this null is symmetric this null and this null is symmetric stack is empty it means there are no more notes in the binary tree to be traversed so we'll simply return true stating that across this line of symmetry this binary tree is symmetric so friend let's suppose we are given with this binary tree now this is the line of symmetry and we need to check whether this binary tree is symmetric or not so we will perform the same steps till this V Loop root is not equal to null we will create a stack root is not equal to null so we will push Roots right on this side along with roots left which is a mirror image of this node in this side so two will come and this two will come stack is not empty we will pop two from the stack and assign to N1 like this we will pop another two and assign it to N2 like this N1 is not equal to null and n N2 is also not equal to null so this condition comes out to be false N1 is not equal to null N2 is not equal to null N1 well which is two is equal to n2. well so this condition also comes out to be false and then we will simply push n1's left which is null so till this point the tree is symmetric and for this node and this node we have to check whether it's child or symmetric or not so if you're putting the left part on the stack then on this side we are actually pushing n2s right which is three and then we are pushing n1's right which is three and its corresponding n2s left like this stack is not empty we will pop null n 2's left so N1 will come to n2s left here we will pop this three which is n1's right so N2 will go to n1's right like this so N1 is equal to null and N2 is not equ Al to null so one of them is null but other is not null so we can't continue so this condition comes out to be false now here you can see as we need to compare these two notes and they should be equal this condition proves that N1 and N2 both are not null but there could be a chance that N1 is null or N2 is null so if any of the node came out to be null we can directly return return false because instead of null we actually need a node three here so that this binary tree can be symmetric till this point but as it's a null value here so this condition comes out to be true and as it's the r operator here we can directly return return false so from here only we will return return false stating that this is not a symmetric binary tree so friend this was all about the symmetric binary tree I hope you must have liked this video in case if you're new to my channel then please subscribe to my channel and and click the Bell icon so that you never miss any update thanks have a nice day