Insertion at the Kth position of LL

Linked-List Fundamentals (Single LL) Easy

Given the head of a singly linked list and two integers X and K, insert a node with value X as the kth node of the linked list and return the head of the modified list.

Examples:

Input: head -> 1 -> 2 -> 3, X = 5, K = 2

Output: head -> 1 -> 5 -> 2 -> 3

Input: head, X = 7, K = 1

Output: head -> 7

Explanation: Note that the value of the head was changed.

Input: head -> 1 -> 2, X = 15, K = 3

Constraints

  • n == number of nodes in the Linked List
  • 0 <= n <= 1000
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • 1 <= K <= n+1

Hints

  • Traverse the list to find the (K−1)-th node (the node just before the desired position). Create a new node with value X.
  • Use a pointer to traverse the list, keeping track of the current position. Stop when you reach the (K−1)-th node or when the list ends.

Company Tags

Splunk Instacart NVIDIA Robinhood Twilio Roblox Etsy Docker Wayfair AMD McKinsey & Company Philips Healthcare HashiCorp Chewy Pinterest MongoDB Flipkart Ubisoft Western Digital Bungie Riot Games Goldman Sachs Lyft eBay Stripe TCS Cognizant Accenture Infosys Capgemini Wipro