Day 3 - Linked Lists
Practice Questions
Middle of the Linked List

Middle of the Linked List

Description

  • Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.

Constraints

  • The number of nodes in the list is in the range [1, 100].
  • 1 <= Node.val <= 100

Test Cases

  • Input: head = [1,2,3,4,5,6]
    Output: [4,5,6]

  • Input: head = [1,2,3,4,5]
    Output: [3,4,5]

Code

Approach 1: Using length of the list

Explanation

  1. Find the length of the list.
  2. Traverse the list till the middle of the list. (length/2)
  3. Return the node at the middle of the list.

Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Approach 2: Using slow and fast pointer

Explanation

  1. Initialize two pointers slow and fast to the head of the list.
  2. Traverse the list with fast pointer moving two nodes at a time and slow pointer moving one node at a time.
  3. When fast pointer reaches the end of the list, slow pointer will be at the middle of the list.
  4. Return the node at the middle of the list.

Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)