700019. Frequency in a Linked List

Easy

Occurrence of an Integer in a Linked List

Slug: occurence-of-an-integer-in-a-linked-list Difficulty: Easy Id: 700019 Topic Tags: Linked List, Data Structures Company Tags: None

Summary

Given a linked list and an integer, this problem requires you to find the frequency of that integer in the linked list. The key concept involved is traversing the linked list.

Detailed Explanation

To solve this problem, we will traverse the linked list once and keep track of the count of the given integer.

Here's a step-by-step breakdown:

  1. Start at the head of the linked list.
  2. Iterate through the linked list until you reach the end (i.e., NULL or None).
  3. For each node, check if the value is equal to the target integer.
  4. If it is, increment a counter variable.
  5. Return the count.

Here's an ASCII art diagram of the linked list:

 1 -> 2 -> 3 -> 4 -> 5
  ^
 head

Time complexity: O(n), where n is the number of nodes in the linked list. Space complexity: O(1), as we are not using any extra space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int findFrequency(Node head, int target) {
        int count = 0;
        Node current = head;
        while (current != null) {
            if (current.data == target) {
                count++;
            }
            current = current.next;
        }
        return count;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.