Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Get Length of Linked List in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Get Length of Linked List
What is it?
A linked list is a chain of connected nodes where each node holds data and a link to the next node. Getting the length of a linked list means counting how many nodes it contains. This helps us understand the size of the list without changing it. It is a basic operation used in many programs that work with linked lists.
Why it matters
Without knowing the length of a linked list, it is hard to manage or use it effectively. For example, you cannot easily check if the list is empty or find the middle element. If we had no way to count nodes, many tasks like searching or inserting at a specific position would be difficult or slow. Knowing the length helps programs run correctly and efficiently.
Where it fits
Before learning this, you should understand what a linked list is and how nodes connect. After this, you can learn about more complex linked list operations like insertion, deletion, or reversing the list. Counting length is a stepping stone to mastering linked list manipulation.
Mental Model
Core Idea
Counting the length of a linked list means visiting each node one by one and adding one until you reach the end.
Think of it like...
Imagine walking down a line of people holding hands. To know how many people are in the line, you count each person as you walk from the first to the last.
Head -> [Node1] -> [Node2] -> [Node3] -> null
Count: 1       2       3       End
Build-Up - 6 Steps
1
FoundationUnderstanding Linked List Structure
šŸ¤”
Concept: Learn what a linked list node is and how nodes connect.
A linked list node has two parts: data and a pointer to the next node. The list starts at a head node. If the next pointer is null, it means the list ends there.
Result
You can visualize a chain of nodes connected by pointers, ending with null.
Understanding the node structure is essential because counting length means moving through these connections.
2
FoundationWhat Does Length Mean Here?
šŸ¤”
Concept: Length is the total number of nodes in the list.
Length counts every node starting from the head until the last node that points to null. It does not count null itself.
Result
If the list has three nodes, length is 3; if empty (head is null), length is 0.
Knowing exactly what length counts prevents confusion between nodes and pointers.
3
IntermediateIterative Counting Method
šŸ¤”Before reading on: Do you think counting nodes requires recursion or can it be done with a simple loop? Commit to your answer.
Concept: Use a loop to visit each node and count them.
Start at the head node. Initialize count to 0. While the current node is not null, increase count by 1 and move to the next node. When you reach null, stop and return count.
Result
For a list with nodes 1 -> 2 -> 3 -> null, the count is 3.
Using a loop is simple and efficient for counting nodes without extra memory.
4
IntermediateRecursive Counting Method
šŸ¤”Before reading on: Will recursion use more memory than iteration for counting length? Commit to your answer.
Concept: Count nodes by calling the same function on the next node until the end.
If the current node is null, return 0. Otherwise, return 1 plus the length of the rest of the list (recursive call on next node).
Result
For list 1 -> 2 -> 3 -> null, recursion returns 3 by adding 1 at each step back.
Recursion is elegant but uses call stack memory, which can be costly for long lists.
5
AdvancedHandling Edge Cases in Length Calculation
šŸ¤”Before reading on: What should the length be if the list is empty? Commit to your answer.
Concept: Ensure the function correctly returns 0 for an empty list and handles single-node lists.
Check if head is null at the start. If yes, return 0 immediately. For one node, the loop or recursion counts exactly one.
Result
Empty list length is 0; single node list length is 1.
Handling edge cases prevents bugs and crashes in real programs.
6
ExpertOptimizing Length Storage for Frequent Access
šŸ¤”Before reading on: Is it always best to count nodes every time we want length? Commit to your answer.
Concept: Store length as a property updated during insertions/deletions to avoid repeated counting.
Instead of counting nodes each time, keep a length variable updated whenever nodes are added or removed. This makes length retrieval O(1) but requires careful updates.
Result
Length queries become instant, improving performance in large or frequently accessed lists.
Knowing when to trade computation for storage is key in designing efficient data structures.
Under the Hood
The length function traverses the linked list by following the next pointers from the head node. Each step moves to the next node in memory until it finds a null pointer, which marks the end. The count increments at each step, reflecting the number of nodes visited.
Why designed this way?
Linked lists do not store their length inherently because nodes are dynamically allocated and can be inserted or removed anywhere. Storing length separately risks inconsistency unless carefully maintained. Counting by traversal is simple and always accurate.
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Head  │ -> │ Node1 │ -> │ Node2 │ -> │ null  │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
Count: 1        2           3          End
Myth Busters - 3 Common Misconceptions
Quick: Does the length of a linked list include the null pointer at the end? Commit to yes or no.
Common Belief:Length counts all elements including the null pointer at the end.
Tap to reveal reality
Reality:Length counts only the nodes, not the null pointer which marks the end.
Why it matters:Counting null as a node would give wrong length, causing errors in list operations.
Quick: Is it faster to count length by recursion or iteration? Commit to your answer.
Common Belief:Recursion is always faster and better for counting length.
Tap to reveal reality
Reality:Iteration is usually faster and uses less memory; recursion adds call stack overhead.
Why it matters:Using recursion on very long lists can cause stack overflow errors.
Quick: If you store length as a variable, can it get out of sync with the actual list? Commit to yes or no.
Common Belief:Stored length always matches the actual number of nodes automatically.
Tap to reveal reality
Reality:Stored length can become incorrect if not updated properly during insertions or deletions.
Why it matters:Incorrect length leads to bugs like wrong indexing or failed boundary checks.
Expert Zone
1
Counting length by traversal is O(n), but storing length trades space for time with O(1) access.
2
Recursive length counting can cause stack overflow on very large lists, so iteration is safer in production.
3
In concurrent environments, length can change during counting, so synchronization or atomic operations may be needed.
When NOT to use
Do not count length by traversal if you need frequent length queries on large lists; instead, maintain a length property updated on every change. For immutable lists, counting once is fine. Avoid recursion for very long lists to prevent stack overflow.
Production Patterns
In real systems, linked lists often keep a length field updated during insertions and deletions for fast length access. Iterative counting is used for debugging or when length is rarely needed. Recursive methods appear in functional programming but are avoided in performance-critical code.
Connections
Array Length Property
Similar concept but different implementation
Arrays store length directly, allowing instant access, unlike linked lists which require traversal or extra bookkeeping.
Tree Size Calculation
Builds on the same counting principle
Counting nodes in a tree uses recursion similar to linked list length but with multiple branches instead of a single next pointer.
Inventory Counting in Warehouses
Analogous real-world counting process
Just like counting items in a warehouse aisle one by one, counting linked list nodes requires visiting each element sequentially.
Common Pitfalls
#1Forgetting to check if the list is empty before counting.
Wrong approach:function getLength(head: Node | null): number { let count = 0; let current = head!; while (current !== null) { count++; current = current.next; } return count; }
Correct approach:function getLength(head: Node | null): number { let count = 0; let current = head; while (current !== null) { count++; current = current.next; } return count; }
Root cause:Using non-null assertion (!) assumes head is never null, causing runtime errors if list is empty.
#2Using recursion without base case leading to infinite calls.
Wrong approach:function getLength(node: Node | null): number { return 1 + getLength(node.next); }
Correct approach:function getLength(node: Node | null): number { if (node === null) return 0; return 1 + getLength(node.next); }
Root cause:Missing base case causes infinite recursion and stack overflow.
#3Updating length variable incorrectly during insertions.
Wrong approach:function insertNode(head: Node | null, data: number): Node { const newNode = new Node(data); newNode.next = head; head = newNode; length = length; // forgot to increment return head; }
Correct approach:function insertNode(head: Node | null, data: number): Node { const newNode = new Node(data); newNode.next = head; head = newNode; length++; return head; }
Root cause:Forgetting to update length causes length to become inaccurate.
Key Takeaways
A linked list's length is the count of its nodes, found by visiting each node from head to end.
Iterative counting is simple and efficient; recursion is elegant but can cause stack overflow on large lists.
Always handle empty lists and single-node lists carefully to avoid errors.
Storing length as a variable speeds up access but requires careful updates to stay accurate.
Understanding length counting is foundational for mastering linked list operations and designing efficient data structures.

Practice

(1/5)
1. What does the function getLength(head: ListNode | null): number typically return when given the head of a linked list?
easy
A. The last node in the linked list
B. The number of nodes in the linked list
C. The value of the first node
D. The sum of all node values

Solution

  1. Step 1: Understand the function purpose

    The function named getLength is designed to count nodes, so it returns the number of nodes in the list.
  2. Step 2: Confirm what is returned

    Since it counts nodes, it returns the total count, not values or nodes themselves.
  3. Final Answer:

    The number of nodes in the linked list -> Option B
  4. Quick Check:

    Function name and return type indicate count [OK]
Hint: Function named getLength returns count of nodes [OK]
Common Mistakes:
  • Confusing length with node value
  • Thinking it returns the last node
  • Assuming it sums node values
2. Which of the following TypeScript code snippets correctly initializes a variable count to start counting nodes in a linked list?
easy
A. let count = 0;
B. let count = null;
C. let count = head;
D. let count = undefined;

Solution

  1. Step 1: Identify the correct initial value for counting

    Counting nodes requires a number starting at zero, so count should be initialized to 0.
  2. Step 2: Check other options

    Initializing to null, head, or undefined is incorrect for counting.
  3. Final Answer:

    let count = 0; -> Option A
  4. Quick Check:

    Counting starts at zero [OK]
Hint: Start counting nodes from zero [OK]
Common Mistakes:
  • Initializing count to null or undefined
  • Using head node as count
  • Not initializing count at all
3. What will be the output of the following TypeScript code?
class ListNode {
  val: number;
  next: ListNode | null;
  constructor(val: number) {
    this.val = val;
    this.next = null;
  }
}

function getLength(head: ListNode | null): number {
  let count = 0;
  let current = head;
  while (current !== null) {
    count++;
    current = current.next;
  }
  return count;
}

const node1 = new ListNode(10);
const node2 = new ListNode(20);
const node3 = new ListNode(30);
node1.next = node2;
node2.next = node3;

console.log(getLength(node1));
medium
A. 3
B. 2
C. 0
D. Error

Solution

  1. Step 1: Trace the linked list nodes

    There are three nodes linked: node1 -> node2 -> node3 -> null.
  2. Step 2: Count nodes in the while loop

    The loop increments count for each node until current is null, so count becomes 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    3 nodes counted [OK]
Hint: Count increments once per node until null [OK]
Common Mistakes:
  • Counting only 2 nodes by missing last
  • Returning zero if loop not entered
  • Syntax errors causing runtime error
4. Identify the error in this TypeScript function to get linked list length:
function getLength(head: ListNode | null): number {
  let count = 0;
  let current = head;
  while (current.next !== null) {
    count++;
    current = current.next;
  }
  return count;
}
medium
A. It counts nodes twice
B. It will cause an infinite loop
C. It throws a syntax error
D. It misses counting the last node

Solution

  1. Step 1: Analyze the while loop condition

    The loop runs while current.next !== null, so it stops before the last node.
  2. Step 2: Understand counting effect

    Because the last node's next is null, it is not counted, so length is one less than actual.
  3. Final Answer:

    It misses counting the last node -> Option D
  4. Quick Check:

    Loop condition excludes last node [OK]
Hint: Loop until current is null, not current.next [OK]
Common Mistakes:
  • Using current.next in loop condition
  • Not counting last node
  • Assuming loop counts all nodes
5. Given a linked list where each node has a val and next, how would you modify the getLength function to return 0 if the list is empty and the correct length otherwise?
hard
A. Return length as 1 if head is null
B. Start count at 1 and loop while current is not null
C. Check if head is null before loop; return 0 if true, else count nodes
D. Use a for loop from 0 to head.val

Solution

  1. Step 1: Handle empty list case

    Check if head is null before counting; if yes, return 0 immediately.
  2. Step 2: Count nodes if list is not empty

    If head is not null, loop through nodes incrementing count until current is null.
  3. Final Answer:

    Check if head is null before loop; return 0 if true, else count nodes -> Option C
  4. Quick Check:

    Empty list returns 0, else counts nodes [OK]
Hint: Return 0 if head is null before counting [OK]
Common Mistakes:
  • Starting count at 1 incorrectly
  • Returning 1 for empty list
  • Using node value instead of node presence
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard