Friday, March 11, 2022

Passing Array vs String vs Integer variable in Recursion



String are immutable in nature, which means, when we pass any String variable in recursive methods as parameters each method will have its own existing value not update one.




Arrays are mutable in nature, which means, its value will remain updated even after the fallback. 
eg. In Print all paths question, we need to set visited boolean array value to false during fallback.
Also, each recursive call will get updated visited boolean array.



Integer variables, when passed in recursion calls, in each call each value will be stored in different memory address.
Let, 
In Call 1, -> int i =10
Now, when i variable is passed in recursion, deep copy takes place, and i will have different memory address.
while backtracking, call 1 will still have its own value not updated one.


Deep:

Before Copy Deep Copying Deep Done

The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...