Skip to the code
cf.
+10 XP

#225 Collapse Repeated Log Codes

easy

A log viewer stores error codes in a linked list sorted from smallest to largest. Many lines share the same code, and the summary panel should show each code only once.

Write collapseCodes(head) that removes repeated nodes so each value appears exactly once, and returns the head. The list stays sorted. Reuse the existing nodes.

Example 1

Input: head = [1,1,2]
Output: [1,2]

The second 1 is a repeat, so it goes.

Example 2

Input: head = [1,1,2,3,3]
Output: [1,2,3]

One 1 and one 3 are removed.

Constraints

  • The list has 0 to 300 nodes.
  • -100 <= node.val <= 100
  • The list is sorted ascending.

Lists are written as arrays here, like [1, 2, 3]. Your function works with ListNode objects, each with val and next.

Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).