Skip to the code
cf.
+25 XP

#231 Drop the Kth Latest Event

medium

An analytics client buffers tracked events in a linked list, oldest first. A privacy rule says the event that is k-th from the end (the newest event is 1st from the end) must be removed before sending.

Write dropFromEnd(head, k) that removes that node and returns the head of the list. Try to do it in one walk of the list.

Example 1

Input: head = [1,2,3,4,5], k = 2
Output: [1,2,3,5]

Counting from the end, 5 is 1st and 4 is 2nd, so 4 is removed.

Example 2

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

The only event is removed, so the list is empty.

Constraints

  • The list has 1 to 30 nodes.
  • 1 <= k <= the number of nodes
  • 0 <= node.val <= 100

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).