Skip to content

3063. Linked List Frequency

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  ListNode* frequenciesOfElements(ListNode* head) {
    unordered_map<int, int> count;
    ListNode* curr = head;

    while (curr != nullptr) {
      ++count[curr->val];
      curr = curr->next;
    }

    ListNode dummy(0);
    ListNode* tail = &dummy;

    for (const auto& [_, freq] : count) {
      tail->next = new ListNode(freq);
      tail = tail->next;
    }

    return dummy.next;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public ListNode frequenciesOfElements(ListNode head) {
    HashMap<Integer, Integer> count = new HashMap<>();
    ListNode curr = head;

    while (curr != null) {
      count.merge(curr.val, 1, Integer::sum);
      curr = curr.next;
    }

    ListNode dummy = new ListNode(0);
    ListNode tail = dummy;

    for (final int freq : count.values()) {
      tail.next = new ListNode(freq);
      tail = tail.next;
    }

    return dummy.next;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def frequenciesOfElements(self, head: ListNode | None) -> ListNode | None:
    count = collections.Counter()
    curr = head

    while curr:
      count[curr.val] += 1
      curr = curr.next

    dummy = ListNode(0)
    tail = dummy

    for freq in count.values():
      tail.next = ListNode(freq)
      tail = tail.next

    return dummy.next