Filter Linked-List Nodes and Keep Top K
Problem statement
Traverse a finite singly linked list and consider only nodes whose value is at least minimum. Among those matching nodes, select the k greatest values and return a new linked list containing their values in original input order. The input list is not modified.
- Duplicate nodes count separately. If equal values lie at the selection cutoff, choose earlier matching nodes first.
- If fewer than
knodes match, return every matching node. If none match orkis zero, return an empty list.
Function
extractTopKMatching(head: ListNode, minimum: int, k: int) → ListNodeExamples
Example 1
head = [4, 9, 4, 8, 4]minimum = 4k = 3return = [4, 9, 8]The two larger values are 9 and 8. The earliest of three tied 4-valued nodes fills the third slot, and selected values keep list order.
Example 2
head = [2, -1, 7, 7, 5]minimum = 3k = 2return = [7, 7]Only 7, 7 and 5 pass the threshold; the top two are the two 7-valued nodes.
Example 3
head = [1, 2, 3]minimum = 10k = 2return = []No node reaches the minimum, so the extracted list is empty.
Example 4
head = []minimum = 0k = 2return = []An empty input list has no matching nodes.
Constraints
- The input list is acyclic and has
0through20000nodes. - Node values and
minimumare integers in[-10^9, 10^9]. 0 <= k <= 20000.