Recursion in One Shot | 9 Best Problems
ฝัง
- เผยแพร่เมื่อ 7 ก.พ. 2025
- Problems :
00:05 - Tower of Hanoi
26:40 - Print string in reverse
32:06 - Find first & last occurrence of element
41:11 - Check if the array is sorted (strictly increasing)
48:59 - Move all 'x' to the end
56:52 - Remove all duplicates in String
01:05:50 - Print all subsequences
01:21:31 - Print all unique subsequences
01:26:28 - Print Keypad Combinations
Codes in the Video : drive.google.c...
Complete C++ Placement Course (Data Structures+Algorithm) : • C++ Full Course | C++...
Telegram: t.me/apnikaksh...
Instagram: / dhattarwalaman
My TH-cam Gear 😉: docs.google.co...
Notes of this Lecture:
The title of the video is so aptly named and the instructor is very clear on the fundamentals and doesn't shy away from enumerating all the possibilities to help the student visualize the problem. Hats off to the effort you have put in making such an obscure topic so tangible. Looking forward to more videos on this series.
Can you provide me with the 1st part of this video plz.
Placement kaisa rha fir???
😂😂😂@@minaalkhajuria8681
# TOWER OF Hanoi
# Python Version
def tower_of_hanoi(n,src,helper,dest):
if (n==1):
print("Transfer Disk {0} from {1} to {2}".format(n,src,dest))
return
tower_of_hanoi(n-1,src,dest,helper)
print("Transfer Disk {0} from {1} to {2}".format(n,src,dest))
tower_of_hanoi(n-1,helper,src,dest)
tower_of_hanoi(3,"S","H","D")
Thanks for nice explaination.
thnks
looked 4 different videos then came here for the tower of hanoi problem and understood it in one go amazing...just amazing
if you understand can you explain me this one please
@@anwarbasha5073 watch the vedio of tap academy on tower of hanoi.They explained it very well graphically.
Same man really clear here
i think there is some sort of mistake in problem no. 3, let's assume we had passed string as "bab" here when it check for first it will only modify first, because you have give last as the else statement... Even though it's output should be first - "1 index" and last- "1 index", it will be first -"1 index" and last as "-1 index ( initialised value )"
solution - you can just add last=first in the if loop, i think that solves it
aapke saari videos mere future mai most probably help karne wali hai..so thanks in advance.....ab coder banna hai and mba grad se jyaada paise kamane hai
Such an interesting and easy method of teaching the hard topic with ease.Great !
Amazing ... just amazing 🔥🔥
got each bit of it... the most important problems of recursion... widened my view over recursion...
Thank u soooOoo muchhh for such an amazing lecture.... love from Kashmir ❤️
Thanx a lot , the lecture from c++ course was very difficult to cope up with👍👍😊
There is an error for the question - First and Last Occurrence using Recursion, the method you stated is suitable when the first and last occurence is different but if there is only one occurence then it fails to give the right answer as it gives -1 for the last occurrence. Here is the corrected code:
if (str.charAt(index) == c)
{
if (first == -1 && last == -1){
first = index;
last = index;
}
else
last = index;
}
my mind suffered in pain after listing to the first explaination of tower of hanoi
Can't thank you enough for this video , this video made me get less anxious about recursion . thank you so much!!
Dii, you are so great teacher.. i saw java placement playlist and i understand java very well thank you very much.😇
I am an it professional and still I watch your videos... They are helpful to relearning things
You should not call urself a professional then😂
33:06 (logic of initializing idx=-1 ), 47:46(array sorting code can be optimized)
Really nice explanation of tower of Hanoi problem 👍👍
nhi aya bhai
The way aman bhaiya response to feed backs is awesome like recursion part was not so well explained in the cpp course but here we are
yeah definately, i was really stucked at cpp playlist after recursion . But here it is.....
Thank you Microsoft wali didi & also OP🙏🙏😊😊😊
Thankyou for building logic and intution for such an difficult topic.VERY MUCH CLEAR AND ABLE TO SOLVE QUESTIONS ALSO.. You are amazing❤️❤️❤️
Thanks for such great explanation. Now I am pretty much comfortable in recursion. You are doing a great job.
Are you a school student?
This is the best way to explain which builds intuition and logic...thank u so much for your efforts 😇😇
th-cam.com/video/tPaj5kF4l3I/w-d-xo.html
The way of teaching is incredible 🎉
Such a good explanation ever seen this youth really need teacher like u🎉🎉🎉🎉
Wow I didn't know it before that god "Brahma Ji" himself created tower of Hanoi algorithm ! 🙄 1:04
Didi what an explaination !!! amazed
but first question concepts is not mythology we are proud to be Hindu jai shree Ram
MY APPROCH FOR MOVING ALL "X" TO END OF THE STRING:
public static void shiftExToEnd(StringBuilder str, int i){
if(i==str.length()-1){
System.out.print(str);
return;
}
if(str.charAt(i)=='x'){
str.delete(i, i+1);
str.append("x");
}
shiftExToEnd(str, i+1);
}
Delete ki jagah substring bhi use kar sakte ho
this code is give wrong output in some cases
19:43 __ I appreciate your effort but you did some mistakes 1. Base case - why for 1 disk it will for zero our program can run for 1 disk also so base case will be -> if(n == 0) {
return; }
2. Parameters - Passing parameter will be S D H instead of S H D like -> towerOfHanoi(n, "S", "D", "H");
now, this is the right sequence (*You can visualize and relate with lecture also)->
transfer disk 1 from S to D
transfer disk 2 from S to H
transfer disk 1 from D to H
transfer disk 3 from S to D
transfer disk 1 from H to S
transfer disk 2 from H to D
transfer disk 1 from S to D
@peanutButter if I pass S H D in this program
This will return
transfer disk 1 from S to D
transfer disk 2 from S to D
transfer disk 1 from D to H
transfer disk 3 from S to H
transfer disk 1 from H to S
transfer disk 2 from H to S
transfer disk 1 from S to D
Where S is src and H is helper nd D is Destination
I said to visualize the output: disk 1 first goes from S (source) to D (destination), and then disk 2 will go from S (source) to H (helper), and then again disk 1 will go from D(destination) to H(helper)...nd so on this is the correct sequence... When S H D is passed as it is, the output format changes also sequence and you can see that the new output is disk 2 transfer S(source) to D(destination) where this will be the output disk 2 transfer S(source) to H (helper).
Ma'am sacchi aap bhut accha pdati hooo mja aa jata hai ek baar mai h topic clr hoo jate hai bs aap ds algo using java ki classes or lelijye
Didi please make a full course on android devlopment begeniers to advance with real life project 🔥🔥🔥
Exactly bro.
Haa really we need this
Go find some other courses ... Don't wait for them to do ..
Yes we need such courses
I want also bro
My fear for recursion all gone . thank you.i am literally enjoying it now 😊❤
as alpha student this video still helps alot
Thanks Shraddha mam
This video helped me understand Tower of Hanoi clearly, thanks for the tutorial
New Approch or My Approch : first of all mam u r an awesome teacher . Please let me know what i m thinking us better or not.
Ques. Remove duplicate string.
My perception-> In this as per your code every time we have to check every element for atleast 26 times. But we can get new array string[e.g->New_array] which is empty and then we compare it from out input char one by one if the char is not available we will add it and then again we compare next char from New_array and add if its already not availabe. In this method we don't have to compare it 26 time for every elements until we got last 26th element (for which also we have to compare it for once only because we out New_array length got length of 26 we will return and close the program ).And you told its time complexity is O(n) but its comparing every element atleast for 26 time so its complexity should be O(n square ) or something else which i don't know (as i have started this topic today only ). Please let me know i m correct or not.
Also we doesn't require bool array. #memorysave #issue #complexity #tle #timelimitexced #AmanBhaiyaop #AmanBhaiyaThankYou #thankyoudi
Can you provide me with the 1st part of this video plz.
Thanks so much. I learned so much about recursion through this and the previous video.
This video problem should be seen by those who are coding basic level. I just learn recursive
My Fav Question Was TowerOfHanoi, Find Occurance & Print Keypad Combination 😊
41:11 - Check if the array is sorted (strictly increasing)
public class arr_sorted {
public static boolean arr_sort(int arr[], int ind){
if (ind == arr.length) {
return true;
}
if (arr[ind]==ind+1) {
return arr_sort(arr, ind+1);
}else{
return false;
}
}
public static void main(String[] args) {
int arr[]= {1,2,3,4,5,5};
System.out.println(arr_sort(arr, 1));
}
}
Best Recursive Explanation is at 56:55 "in the bottom right corner". xdxd
th-cam.com/video/tPaj5kF4l3I/w-d-xo.html
loved this video ! cleared all doubts on recursion.
! Cleared or its cleared 😂
This is a much better code to reverse a string. Taken from - A Common Sense Guide to DSA
public class chk
{
public static String reverse(String s)
{
if(s.length()==1)
{
return s;
}
return reverse(s.substring(1,s.length()))+s.charAt(0);
}
public static void main(String[] args)
{
String s="hanuman";
System.out.println(reverse(s));
}
}
Same code is given in the notes of this lecture
Thanks ma'am,❤
I am very grateful to you, for you making me understand complex programs and also making me do the hardwork.willingly, due to your quality of teaching.
54:47 That reaction when you are exited because you think your code is done and something goes wrong😂🤣
Last one was tough to understand without getting the concept of oops first. this video is sure tough for beginners who's giving efforts but still not in right order
Excellent teaching on recursion mam
54:00 short and better approach. This code will work for any input character
public static void transferCharacters(String str, char ch, int index, String helperString, String moveAllchars){
// helperString will store all the cahracters other than ch
// moveAllchars will store all the occurances of that particular character
if(index < str.length()){
if(str.charAt(index) == ch) transferCharacters(str, ch, index+1, helperString, moveAllchars + ch);
else transferCharacters(str, ch, index+1, helperString + str.charAt(index), moveAllchars);
}
else{
System.out.println("new string of all transferred " + ch + " " +(helperString + moveAllchars));
return;
}
PS : also, time complexity is minimum in this code O(n) without roundoff or ignoring some integer
Yaar kitna achaa padhaati hai didi 😍
Buckup Girl, you are the combined force of Goddess Parvati-Laxmi-Saraswati👍👍👍
Thanku sister free me coding shikhane ke liye
First que kitna easy hai par uska itna easy tarike se samjaya ki aisa laga 2 no. Ko plus krna hai bohot ache se explain krti hai didi or aman bhaiya is course mai jlde video apload kro daily ek
Thank u so much mam
i had to clear the phone combination problem which i was stuck at from a long time....
and now it is clear to me by your valuable way of teaching....😊
Can you explain me the dry run of keypad combination
You take index of string from 0 to string.length()
But I think it should be from 0 to String.legth -1 and we cover every char of string
right
@@felix_72 i had the same doubt as she took array.length-1 in the next problem
How to calculate the number of steps needed for n disk in Tower of Hanoi
n = 1 then step = 1
+ 2 = 1(1 is from above step) + 2 (2 is the number needed to add with 1 to get 3) = 3
the above step can also be written as 2 ^ n-1
n = 2 then step = 3
+ 4 = 3(3 is from above step) + 4 (4 is the number needed to add with 3 to get 7) = 7
the above step can also be written as 2 ^ n-1 + 2 ^ n-2
n = 3 then step = 7
+ 8
n = 4 then step = 15
+ 16
n = 5 then step = ?
n = 1 then step = 1 = 2 ^ n-1
= 2 ^ 1-1
= 2 ^ 0
= 1 steps
n = 2 then step = 3 = 2 ^ n-1 + 2 ^ n-2
= 2 ^ 2-1 + 2 ^ 2-2
= 2 ^ 1 + 2 ^ 0
= 2 + 1
= 3 steps
n = 3 then step = 7
+ 8
n = 4 then step = 15
n = 5 then step = ?
when n = 4
= 2 ^ 3 + 2 ^ 2 + 2 ^ 1 + 2 ^ 0
= 8 + 4 + 2 + 1
= 15 step when n = 4
if you didn't understand then
docs.google.com/document/d/1Jr0ai4ADbLVvi4-FVURU5qsilL4zybOiAPT14PgyASA/edit?usp=sharing
Hope you understand now ^_^
Didi is the best 😊 I means 'ek number' 👍
Great explaination!!!
Good teacher you all 👌👌👌
54:50--Didi's reaction 😂😂😂
59:20 you can also use java builtin String method .replaceAll() to replace all the occurances of a character with a new character
public static void removeDuplicates(String str, String newStr, int index){
// newStr will only store unique characters
if(index < str.length()){
if(str.charAt(index) != '#'){
newStr += str.charAt(index);
/* before replacing, first of all we will convert that particular character into string
* (as replaceAll will only accept (String, String) as arguments */
str = str.replaceAll(String.valueOf(str.charAt(index)), "#");
removeDuplicates(str, newStr, index+1);
}
else
removeDuplicates(str, newStr, index+1);
}
else{
System.out.println("new String : "+newStr);
return;
}
}
PS : for someone who have question that what if string contains '#' as character. As per question and solution which she has written String only contain alphabets
we can also do the program at 48:50 by this code
public class program15 {
public static void move(StringBuilder str, int idx){
if(idx==str.length()){
System.out.println(str);
return;
}
if(str.charAt(idx)=='x'){
str.deleteCharAt(idx);
str.append('x');
move(str, idx+1);
}
else{
move(str, idx+1);
}
}
public static void main(String[] args) {
StringBuilder str = new StringBuilder("abcdxxx");
move(str, 0);
}
there can be multiple ways to solve a problem, since it is a recursion class and your code does not contain any recursive method, so it is wrong from the recursion prespective
what a blunder in notes of the tower of hanoi !
At 20:00 didi ne to waqt badal diye, jazbbat badal diye, halat badal diye 🤣.....
Didn't expect that.....🥲🥲🥲
Exactly bro, output thik nhi aaye hat is code k?
@@dheeraj7908 wahi muje bhi lag rha hai
Python recursive code for reversing string:
string = input("enter string: ")
index = len(string)-1
def rev_str(index, string):
if index==0:
print(string[index])
return
else:
print(string[index], end="--->")
rev_str(index-1,string)
# calling the function
rev_str(index,string)
30:00 For a better understanding of how stacks are implemented while using recursion, use this:
public class Main
{
public static void printRev(String s, int x=0){
if(x==s.length()){
return;
}
printRev(s, x+1);
System.out.print(s.charAt(x));
}
public static void main(String[] args) {
String s="abcd";
printRev(s, 0);
}
}
Tqs bruh
Your videos are truly wonderful, but could you kindly assist us by including English subtitles? It would greatly benefit those who may not understand Hindi.
"Subsequences of a string" can be also called as "Subsets of a set", as per the set theory, we can calculate the time complexity by 2^(the cardinality of the set)
Like A={a,b,c} then the number of all elements of the set A is 3, then all possible subsets of the set A will 2³=8.
at 56:52 we can solve this using loop
public class Test{
public static void main(String[] args){
String str = "abbccda";
String newStr = "";
for(int i=0; i
Thanks very much for your efforts.🙂
I can't believe it...........never saw any teacher teaching programming feeling like NV SIR teach physics right now 😯✅😍
Can you provide me with the 1st part of this video plz.
@@shashwatsingh479 of course
lots of love ❤... #best coder
great video ,explanation is neat and understandable
I love this channel....❤️
this is called premium course
I think at 39:12 its
if(idx == str.length() -1)
because we idx starting from 0 so we need to go till last index that is str.length()-1
1:06:21 Subsequence of string
Didi pls take live class for C++ programming pls didi😊😊😍😍😍
54:45 that look though "ye code kaise work nahi hua?!??!!" 😂😂😁😁
You explain in super way. Thanks a lot for the explaining this complex problem in very easy way.
In occurrrance of the element in the string problem ,I think the code will not work properly in some cases where a element has occurred only once in the String.
Add last=idx also in the first ==-1 if
how many got to know that tower of hanoi problem is different in lecture and notes provided by mam . by the way thank you mam for this much detail on tower of hanoi . the code in notes is incorrect instead of dest it is helper.
for tower of hanoi while listening to half of the explanation i figured that it forms a series such that t(n+1)=2t{n) + 1 and t(1)=1. so on solving it you will get t(n)=2^n - 1; i know this video is about recursions but just mentioning it if someone try to find solution by series approach.
Another way for question 6 without use of boolean array Hope it helps
import java.util.*;
public class MBrenXI10 {
static Scanner sc = new Scanner(System.in);
public static void convert (String blank, String d, int n, int x){
int count = 0;
if (n==x){
System.out.println(blank);
return;
}
else {
for (int i = 0; i
mam great explaination of recursion ...................you didn't describe recursion so well in c++ placement course.......................
Awesome teacher plzz use this potential of urs..... it feels so bad by seeing this channel is doing nothing....where others are taking the first mover advantage
45:54 why are putting return after calling the isSorted function again??
ty mam u r awesome
If input string is "abcd" , your code will print first as 0 and last as -1 So, you need to assign first and last both with idx value inside if condition. And later last variable will be updated inside else if more occurances are there of the character 'a'.
True that. Nice observation. Thanks.
In first and last occurence,
if(first== -1) {
first = index;
last = index;
} else
last = index;
Otherwise if a string has target char once it'll show -1 for last occurence which is not true
if(first== -1) {
first = index;
}
last = index;
else is not required only.
REcursion is hard to learn it messes with your mind on whole other level
Thnx didi for this amazing lecture
Plz make a videos on C for beginners in CSE
In the remove duplicate question if we use indexOf method of string the problem will much easier...😊
21:30 mam thought she is oversmart
who faced the problem?
yess broo, there's no logic for SMALLER DISKS ALWAYS ON THE TOP
@@sumit2306 that is the demand of the question
38:34 Please don't put the "else" here because if the element is occurring only once in the entire string, for example: if the string is "tabcdfghijakkkx" and we are searching for 'x', the output in this case (with the else) will be 14 and -1 but it should be 14 and 14 instead. So, we can basically just write last = idx without any if or else.
why it is happening ,can u explain bro
Sach me maja aa gya... !!!
For unique subsequences, arrayList is enough as arrayList has contains method (hashSet wasn't required)
40:05 What if there is only 1 element present in the string what we are searching for ,then first and last indexes should be same ,but form this code we get first index value correct but last index value as -1.
So update last index value in both if and else condition then we ill get correct ans.
Nice catch @Balasagar Goud
In question first and last occurence it is failing for the input abbbccc for element a the correct code will be:
public static void findOccurence(String s,int idx,char element)
{
if(idx==s.length())
{
System.out.println(first);
System.out.println(last);
return;
}
if(s.charAt(idx)==element)
{
if(first==-1){
first=idx;
last=idx;
}
else
last=idx;
}
findOccurence(s,idx+1,element);
}
for removing duplicate we can use string builder as well
Is there a predefined function for that?
56:08 by the folllowing code we don't have to use the loop at the end, will this result in a better time complexity?
public static String elString = "";
public static String newString = "";
public static void moveAtEnd( String str , int idx, char el){
if(idx == str.length()){
newString = newString + elString;
System.out.println(newString);
return;
}
if(str.charAt(idx) == el){
elString = elString + el;
}
else{
newString = newString + str.charAt(idx);
}
moveAtEnd(str, idx + 1 , el);
}
Still the time complexity would be the same i think
@@kamaleshwaran5802 but still better than using for loop
import java.util.Scanner;
public class RecursionProblem3 {
public static void FindChar(String str, int start, int end, String c) {
if (start > end) {
return;
}
if (str.charAt(start) == c.charAt(0)) {
System.out.println("This is the index of a: " + start);
}
FindChar(str, start + 1, end, c);
}
public static void main(String[] args) {
System.out.println("If Nothing is print so no char in your string");
Scanner sc = new Scanner(System.in);
String s = "abanasaskandka";
int n = s.length();
System.out.print("Enter Char that you want to know: ");
String c = sc.nextLine();
FindChar(s, 0, n - 1, c);
sc.close();
}
}
in 3rd Q. This code is best and this is fast and take small amout of time and memory.
Thank you so much for your efforts ❤
There is some mistake in FirstAndLast Occurrence Question:
Here is the correct code ->
static int first = -1;
static int last = -1;
public static void firstAndLast(String str, int index, char element) {
if(index == str.length() ){
System.out.println("First: "+first + " Last: "+last);
return ;
}
if(str.charAt(index)==element && first==-1){
first = index;
last = index;
}else if(str.charAt(index)==element){
last = index;
}
firstAndLast(str, index+1, element);
}