Linked List Frequency - Problem

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.

The frequency of an element is the number of times it appears in the linked list.

Example: If the linked list is [1→2→1→3→2→2], the frequencies are: 1 appears 2 times, 2 appears 3 times, 3 appears 1 time. Return a linked list containing [2→3→1] (frequencies in any order).

Input & Output

Example 1 — Basic Case
$ Input: head = [1,2,1,3,2,2]
Output: [2,3,1]
💡 Note: Element 1 appears 2 times, element 2 appears 3 times, element 3 appears 1 time. Return frequencies in any order.
Example 2 — All Unique
$ Input: head = [1,2,3]
Output: [1,1,1]
💡 Note: Each element appears exactly once, so all frequencies are 1.
Example 3 — All Same
$ Input: head = [5,5,5,5]
Output: [4]
💡 Note: Only one distinct element (5) appears 4 times, so return [4].

Constraints

  • 1 ≤ length of linked list ≤ 105
  • -105 ≤ Node.val ≤ 105
  • The linked list contains exactly k distinct elements

Visualization

Tap to expand
Linked List Frequency INPUT Linked List: 1 2 1 3 2 2 NULL Input Array: [1, 2, 1, 3, 2, 2] k = 3 distinct elements (values: 1, 2, 3) ALGORITHM STEPS 1 Create Hash Map Initialize empty map 2 Traverse List Count each element 3 Build Frequency Map Store val:count pairs 4 Create Result List Return frequencies Hash Map State: 1: 2 2: 3 3: 1 1 appears 2 times 2 appears 3 times 3 appears 1 time FINAL RESULT Result Linked List: 2 3 1 NULL Output: [2, 3, 1] Frequency Mapping: 2 = freq of element 1 3 = freq of element 2 1 = freq of element 3 OK - Verified! Key Insight: Using a hash map allows O(n) time complexity to count frequencies. We traverse the list once to build the frequency map, then create a new linked list with k nodes containing the counts. Space complexity is O(k) for storing k distinct elements in the hash map. TutorialsPoint - Linked List Frequency | Hash Map Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen