find the kth largest node in a linked list in typescript

To find the kth largest node in a linked list, we can first traverse the linked list and push all the nodes into an array. Then we can sort the array in descending order and return the node at position k-1.

Here's the TypeScript code to implement this approach:

index.ts
class Node {
  value: number
  next: Node | null
  
  constructor(value: number) {
    this.value = value
    this.next = null
  }
}

function findKthLargestNode(head: Node, k: number): Node | null {
  let currentNode = head
  const nodes: Node[] = []
  
  // push all the nodes to an array
  while(currentNode !== null) {
    nodes.push(currentNode)
    currentNode = currentNode.next
  }
  
  // sort the nodes in descending order
  nodes.sort((a, b) => b.value - a.value)
  
  // return the kth largest node
  return nodes[k-1] || null
}
541 chars
27 lines

In this code, we create a Node class to represent the nodes in the linked list. Then, we define a function findKthLargestNode that takes the head of the linked list and the value of k. We declare a variable called currentNode that starts at the head of the linked list and an empty array called nodes.

We then traverse the linked list by repeatedly setting currentNode to its next node and pushing the current node onto the nodes array until currentNode is null.

After we have all the nodes in the array, we sort them in descending order using Array.prototype.sort() with a custom compare function that compares the value property of the nodes.

We then return the k-1th element of the sorted nodes array, or null if the array has less than k elements.

gistlibby LogSnag