1/20/2024
Number of Unique Categories #2 attempt
This is my second attempt at Number of Unique Categories problem. Some lessons learned today:
- The
roots
property has its name for a reason. It is not an array of parents but an array ofroots
. This is why onfindRoot
, on the way back from the root, we need to mark each element's root to be the real root. If we useparents
instead ofroots
, each time we find the root, we need to perform multiple recursive calls to traverse to the root. When usingroots
, we only callfindRoot
at most twice. Ifx
is the root, we call it once. Ifx
is not the root, we call it twice because the second call will reach the root. - When the job of finding or getting something expensive or complicated, the best way is to use some variable to store the result when it just appears. It makes our lives much easier.