VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-a-function-that-counts-the-number-of-times-a-given-int-occurs-in-a-linked-list/

⇱ Count Occurrences in a Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count Occurrences in a Linked List

Last Updated : 27 Feb, 2026

Given a singly linked list and a key, the task is to count the number of occurrences of the given key in the linked list.

Example :

Input : head: 1->2->1->2->1->3->1 , key = 1
Output : 4

👁 Count-Occurrences-in-a-Linked-List_1

Explanation: key equals 1 has 4 occurrences.

Input : head: 1->2->1->2->1, key = 3
Output : 0
Explanation: key equals to 3 has 0 occurrences.

[Naive Approach] By Recursion – O(n) time and O(n) space

The idea is to recursively traverse the linked list from the head. At each node, check if its value matches the given key; if it does, increment the count by 1. Then recursively call the function on the next node. When the pointer reaches NULL, return 0. The total count is obtained by summing the matches from all recursive calls.


Output
3

[Expected Approach] By Traversing each node – O(n) time and O(1) space

The idea is to traverse the linked list iteratively from the head, maintaining a counter. For each node, check if its value matches the key; if it does, increment the counter. Continue until the end of the list and return the final count.


Output
3
Comment
Article Tags: