Interview Question

Front End Software Engineer Interview San Jose, CA

How would you pick the middle element of a list

Answer

Interview Answer

3 Answers

1

I said by dividing the length with 2. He said there would be two passes involved with that (?). He wanted some way with one pass.

Interview Candidate on Sep 25, 2012
0

int[] intArray = {12,34,56,78,98,31,47};

int startIndex=0;
int endIndex=intArray.length -1 ;

while(startIndex<endIndex) {
startIndex++;
endIndex--;
}

if(startIndex == endIndex)
int middleElement = intArray[startIndex];
//you will have only one middle element

else {

int middleElement1 = intArray[startIndex];
int middleElement2 = intArray[endIndex];
//you will have two middle elements.
}

Sudha on Oct 29, 2012
5

its a list (assuming not an array)....
Take two pointer....increment 1st pointer by 2 everytime & second by 1 [Rabbit & tortoise problem]
if 1st pointer(rabbit) reaches the end of the list....
the position of the tortoise is the location of the middle element of the list.

Jayanth on Nov 5, 2012

Add Answers or Comments

To comment on this Question, Sign In with Facebook or Sign Up