MuhammadTausif / gfg-excercises

This repo is about exercises at GFG
Apache License 2.0
0 stars 0 forks source link

Occurence of an integer in a Linked Lists - POTD | 26-Oct-2024 #57

Closed MuhammadTausif closed 4 hours ago

MuhammadTausif commented 4 hours ago

Occurence of an integer in a Linked List

Link

Difficulty: Easy

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

Examples:

Input: Linked List: 1->2->1->2->1->3->1, key = 1

Output: 4
Explanation: 1 appears 4 times. 
Input: Linked List: 1->2->1->2->1, key = 3

Output: 0

Explanation: 3 appears 0 times. Expected Time Complexity: O(n) Expected Auxiliary Space: O(1)

Constraints:

MuhammadTausif commented 4 hours ago

Solved

class Solution:
    def count(self, head, key):
        current = head
        ans = 0

        while current is not None:
            if current.data == key:
                ans += 1
            current = current.next

        return ans