Delete the middle node in LL

Linked-List FAQs (Medium) Medium
  • The underlying concept of this problem can be found in applications such as music streaming apps like Spotify or Apple Music, where a linked list data structure can be used to organise songs in a playlist
  • Performing operations such as deleting a song, or in this case a "middle node," is a common task in managing these playlists

Given the head of a non-empty singly linked list containing integers, delete the middle node of the linked list. Return the head of the modified linked list.


The middle node of a linked list of size n is the (⌊n / 2⌋ + 1)th node from the start using 1-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.

Examples:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5

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

Explanation: n = 5.

⌊n / 2⌋ + 1 = 3, therefore middle node has index 3 and so the node with value 3 was deleted.

Input: head -> 7 -> 6 -> 5 -> 4

Output: head -> 7 -> 6 -> 4

Explanation: n = 4.

⌊n / 2⌋ + 1 = 3, therefore middle node has index 3 and so the node with value 5 was deleted.

Input: head -> 7

Constraints

  • 1 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104

Hints

  • A brute-force approach would: Find the length n of the list (O(n)). Traverse again to the (⌊n/2⌋)th node and delete it (O(n)). Drawback: Requires two passes (O(n) time).
  • To delete the middle node in a single pass: Use two pointers (slow and fast). Move slow one step at a time and fast two steps at a time. When fast reaches the end, slow will be at the middle node. Delete the middle node by skipping it.

Company Tags

Johnson & Johnson Electronic Arts Instacart JPMorgan Chase IBM Etsy Bungie Reddit HCL Technologies Square Alibaba Dropbox Snowflake Ubisoft PayPal ARM Western Digital Stripe Rakuten Rockstar Games Teladoc Health Cerner Optum Uber Pinterest Google Microsoft Amazon Meta Apple Netflix Adobe