FastPrepFilter Linked-List Nodes and Keep Top K

Filter Linked-List Nodes and Keep Top K

Google logoGoogle● MediumFULLTIMEPHONE SCREEN
Learn

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 k nodes match, return every matching node. If none match or k is zero, return an empty list.

Function

extractTopKMatching(head: ListNode, minimum: int, k: int) → ListNode

Examples

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 0 through 20000 nodes.
  • Node values and minimum are integers in [-10^9, 10^9].
  • 0 <= k <= 20000.

More Google problems

See Google hiring insights
public ListNode extractTopKMatching(ListNode head, int minimum, int k) {
    // Write your code here.
}
head[4, 9, 4, 8, 4]
minimum4
k3
expected[4, 9, 8]
Checking account…