Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Why do we need to cast the currentPath list to a list if it's already a list? If...

Dylan Asoh

Aug 24, 2022

Why do we need to cast the currentPath list to a list if it's already a list? If we don't cast it the list is empty for some reason.

1

0

Comments
Comments
Design Gurus
Design Gurus3 years ago

We are not casting. We are cloning, i.e., making a copy of the list.

We need to clone the list, and save it as a new path.

If we don't clone, the original list will be empty at the end of the function because of the last statement:

del currentPath[-1]

A
Alfonso Vieyra3 years ago

Hi systemdesign,

I just want to clarify regarding Dylans question above, when we append currentpath to allPaths, we cast it because currentpath is being passed by reference. Therefore, when we change currentpath i.e. delete its elements, that too, modifies the list we ...

A
Alfonso Vieyra3 years ago

I notice the c++ code is a little more readable( i was doing the problem in python) and i noticed it was being passed by reference. I never knew casting the object creates a shallow copy! Thats good to know haha

On this page