Linked List Frequency Problem
#3063
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3063.
Given the head of a linked list containing k distinct elements, return the head to a linked list of length k containing the frequency of each distinct element in the given linked list in any order.
Example 1:
Input: head = [1,1,2,1,2,3]
Output: [3,2,1]
Explanation: There are 3 distinct elements in the list. The frequency of 1 is 3, the frequency of 2 is 2 and the frequency of 3 is 1. Hence, we return 3 -> 2 -> 1.
Note that 1 -> 2 -> 3, 1 -> 3 -> 2, 2 -> 1 -> 3, 2 -> 3 -> 1, and 3 -> 1 -> 2 are also valid answers.
Example 2:
Input: head = [1,1,2,2,2]
Output: [2,3]
Explanation: There are 2 distinct elements in the list. The frequency of 1 is 2 and the frequency of 2 is 3. Hence, we return 2 -> 3.
Example 3:
Input: head = [6,5,4,3,2,1]
Output: [1,1,1,1,1,1]
Explanation: There are 6 distinct elements in the list. The frequency of each of them is 1. Hence, we return 1 -> 1 -> 1 -> 1 -> 1 -> 1.
Constraints:
- The number of nodes in the list is in the range
[1, 10^5]. 1 <= Node.val <= 10^5
Solution
Approach: Hash Table
Count how many times each value appears in the list with a hash table cnt. Then walk over the counts and build the answer list by prepending a new node for each count; any order is accepted.
Complexity: O(n) time and O(n) extra space, where n is the length of the list.
from collections import Counter
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def frequenciesOfElements(self, head: Optional[ListNode]) -> Optional[ListNode]:
cnt = Counter()
while head:
cnt[head.val] += 1
head = head.next
dummy = ListNode()
for val in cnt.values():
dummy.next = ListNode(val, dummy.next)
return dummy.next