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

Popular Posts

Most Featured Post

GitHub: Squash all commits in PR

  Command Meaning git fetch origin Get the latest origin/master . git reset --soft origin/master Move your branch to match origin/master , b...