Introduction
Counting nodes in a Linked List means finding the total number of nodes present in the list.
The task is to:
- traverse the linked list
- visit every node
- increment count variable
Example:
Input:
1 -> 2 -> 3 -> 4
Output:4
Explanation:
There are:1
2
3
4
Total nodes:
4
This problem is one of the most important basics of:
Linked List Data StructureConstraints
1 <= Number of Nodes <= 10^5-10^9 <= Node Value <= 10^9Approach 1 : Brute Force (Using Extra Array)
Explanations:
Explanation:
The idea is:
- traverse linked list
- store nodes into array
- return array size
Steps:
- Traverse linked list.
- Store node values.
- Return array length.
This approach works but:
- uses unnecessary extra space
So direct traversal counting is preferred.
Dry Run
Input:
1 -> 2 -> 3 -> 4
Step 1:
Visit 1
Array:
[1]
Step 2:
Visit 2
Array:
[1,2]
Step 3:
Visit 3
Array:
[1,2,3]
Step 4:
Visit 4
Array:
[1,2,3,4]
Count:4
Practice :
Complexity Analysis :
Time Complexity:- O(n)Explanation :
Each node is visited once.
Space Complexity:- O(n)
Explanation :
Extra array is used.
Approach 2 : Optimal Solution(Direct Traversal Counting)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- traverse linked list directly
- increment count variable
- return total count
This avoids extra space usage.
Dry Run
Input:1 -> 2 -> 3 -> 4
Count:
0
Visit 1
Count = 1
Visit 2
Count = 2
Visit 3
Count = 3
Visit 4
Count = 4
Traversal Ends
Final Output:
4
Practice :