Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Middle Element of Linked List

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Middle Element of Linked List. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Cyient embedded diagnostics may represent a sequence of events as a singly linked list. Given the head of the list, return the value stored in its middle node.

Use the fast and slow pointer technique. The slow pointer advances one node at a time, while the fast pointer advances two nodes at a time. If the list contains an even number of nodes, return the second of the two middle nodes.

Formal Specification

The input is head, either None or a reference to the first ListNode. Each node has an integer value field and a next field pointing to the next node or None. Return the integer value of the middle node. The test cases represent linked lists as arrays, which the test harness converts into ListNode objects before calling the function.

Constraints

  • 0 <= n <= 10^5
  • -10^9 <= node.value <= 10^9
  • The list is singly linked and acyclic
  • Return None for an empty list

Function Signature

def middle_element(head):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output