Wednesday, April 17, 2019

ow do you find the middle element of LinkedList in one pass is a programming question often asked Java and non-Java programmers in telephonic Interview. This question is similar to checking palindrome or calculating the factorial, where Interviewer sometimes also ask to write code. In order to answer this question candidate must be familiar with LinkedList data structure i.e. In the case of singly LinkedList, each node of Linked List contains data and pointer, which is the address of next Linked List and the last element of Singly Linked List points towards the null. Since in order to find middle element of Linked List you need to find the length of linked list, which is counting elements till end i.e. until you find the last element of Linked List.
What makes this data structure Interview question interesting is that you need to find the middle element of LinkedList in one pass and you don’t know the length of LinkedList.

This is where candidates logical ability puts into the test,whether he is familiar with space and time trade-off or not etc.

By using two pointers, incrementing one at each iteration and other at every second iteration. When the first pointer will point at end of Linked List, the second pointer will be pointing at a middle node of Linked List.

In fact, this two pointer approach can solve multiple similar problems like how to find the third node from last in a Linked List in one Iteration or how to find an Nth element from last in a Linked List. In this Java programming tutorial, we will see a Java program which finds the middle element of Linked List in one Iteration.

Btw, if you are new to Algorithms and Data Structure and not familiar with essential data structure like linked list, array or binary tree then I suggest you go through a good, comprehensive online course like Data Structures and Algorithms: Deep Dive Using Java to learn the basics and brush up the fundamentals.

How to Find Middle Element of LinkedList in One Pass

Here is a complete Java program to find the middle node of Linked List in Java. Remember LinkedList class here is our custom class and don’t confuse this class with java.util.LinkedList which is a popular Collection class in Java.

In this Java program, our class LinkedList represent a linked list data structure which contains a collection of the node and has head and tail.

Each node contains data and addresses part. The main method of LinkedListTest class is used to simulate the problem, where we created Linked List and added few elements on it and then iterate over them to find middle element of linked list in one pass in Java.

If you want to learn more about linked list data structure and different types of linked lists like a singly linked list, doubly linked list, circularly linked list et all then you can also check the Algorithms and Data Structures - Part 1 and 2 courses on Pluralsight. One of the better courese to learn data structure and algorithms.

Btw, you would need a Pluralsight membership to access this course. If you are not a member, you can still access this course by using the 10-day free pass provided by Pluralsight to explorer its portal and online courses.

Java Program to Find the Middle Node of a Linked list in a Single-pass

importtest.LinkedList.Node;

/** * Java program to find middle element of linked list in one pass. * In order to find middle element of a linked list * we need to find the length first but since we can only * traverse linked list one time, we will have to use two pointers * one which we will increment on each iteration while * other which will be incremented every second iteration. * So when the first pointer will point to the end of a * linked list, second will be pointing to the middle * element of a linked list * * @author Javin Paul */publicclass LinkedListTest {

That’s all on How to find middle element of LinkedList in one pass. As I said this is a good interview question to separate programmers from non-programmers. Also, the technique mentioned here to find middle node of LinkedList can be used to find the 3rd element from Last or nth element from last in a LinkedList as well.

Write a Program to Check if a number is Power of Two or not? (program)

Thanks for reading this coding interview question so far. If you like this String interview question then please share with your friends and colleagues. If you have any question or feedback then please drop a comment.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check this list of Free Data Structure and Algorithms Courses for Programmers.

47 comments
:

Maybe my mind is still not awaken after Christmas laziness, but... does this code really return middle element? I think it returns last element with even index. In this code it is solved like you were incrementing index every second time. If you update reference to current every second time, nothing good will come out of this. I'd set middle = middle.next() in loop and also ... initialize length as 0 (I don't consider head element as real element of the list (length should return number of elements carrying data). Greetings!

@Pio Jac, you are right if we don't consider head as real element. In that case initialing length with 0 make sense. Also In order to handle odd length e.g. 3, 5 or 7 where middle element is not updated, we need to handle once loop finished. I have updated code. Thanks for pointing out, it seems, its me, who has Christmas laziness :)

Can you please write code for How to find 3rd element from last in Singular Linked List, I didn't get your point on saying that same technique can be used to find Nth element from last in singly linked list. Sorry.

I was asked to find middle item in a linked list in single pass and when I asked what is length of linked list they say, you need to find that as well. I didn't thought that I can use two pointers or two variables to keep track of middle and last item, something I missed. By the way What is big O for best case and worst case for this solution ?

@Anonymous, aspect here is coding, converting logic to code. algorithm here is simple where one pointer is incremented on each iteration, while other is incremented in every second iteration. let me know which part you didn't understand.

Ken is correct. Unless I am missing something, this isn't one pass, it is 1.5. If you demand an answer for a single pass, a student should respond that it isn't possible and that only 1.5 is possible. The idea that answering this 'incorrectly' could have cost someone a job is slightly disconcerting.

The solution presented here obviously does more than one pass and hence isn't valid. It doesn't matter if all you do is chasing the pointers. You are still traversing 1.5 times and could just as well do a count run and then stop in the middle for the next one with the same effort.

A java LinkedList is a doubly linked list (http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html) so the whole premise that you would be working on a singly linked list is wrong too. The correct solution would be to advance from both sides (front and back) of the doubly linked list simultaneously until you meet in the middle element (happens for uneven list length) or the next element matches the current element of the other (happens for even list lengths).

@pavan, linked list doesn't allow random access. You can cannot get element by calling get(index). This is true for our own linked list implementation and also for java.util.LinkedList, which is a doubly linked list.

@Huy, Thanks for your code, but I think I suggested to write JUnit tests for your code to verify if the solution works for a linked list with even number of elements and a list with odd number of elements e.g. linked list with 5 elements.

I have to be honest.... this is a nice solution and all but...the real answer is there is no way of completing this with a single pass. Two pointers means you are making two passes. This is the same for all of the implementations I have seen. I think others have echoed the same sentimate and I realize that at some point this could come down to a wording issue. This is not a slight against the author of it - it is more of an annoyance with these types of questions meant to "weed out programmers from none" because we are fabricating solutions that aren't really solutions. Words mean something, one pass is one pass and the first pass is done by the time the second pointer ever has a chance.

@Joshua, you may be right. I guess the pass initially refer to how many loop you use to find the middle element of linked list, but you are right, it's not the correct word. A pass can also means accessing the linked list twice.

I am bit puzzled about this problem and solution. Why did you create your own implementation of LinkedList? I would assume that the question was about java.util.LinkedList. If memory is not an issue than creating an Array from LinkedList would be one pass and much simpler.

while(fast&&fast->next){ slow=slow->next; fast=fast->next->next; } *val = slow->data;}I am just returning the value of the middle node. We could return the node itself. Only catch, need to ask interviewer what if the list is of even number. In that case, there will two middle nodes :-) !!

Perhaps another way of solving this would be using Floyd's slow and fast pointer's concept. Increment the fast pointer by two at each incremental stage until the next of it is not null and increment the slow pointer by one and you shall find the middle element.