A reader asked us the following:

Just a recommendation: Add a “length” attribute to the linked list that updates every time a node is added or removed instead of going through the entire linked list just to return the length. It’s more efficient to keep track of the length than to go through the entire linked list to calculate the length. Keeping track of the length is O(1) vs going through it, which is O(n). Thank you for this amazing course.

The author of the course Vincent Russo replied:

Sure, one could do this. How/why one implements the length function will differ based on one’s use cases and requirements. Doing what the student suggested does allow one to obtain the length of the list in constant time with the (small) drawback of keeping track of the length. This may be disadvantageous in the event where the list rarely changes and the cost of calculating the list offsets the space cost of keeping the variable. These are arbitrary requirements and not exclusive to being the only ones, but they could exist.

But sure, if the user was optimizing for time vs. space in this case, they could simply make this a class variable and update every time a node is removed/added.