Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the middle of an array without knowing the length

Tags:

c++

arrays

c

string

Find the middle of the string or array with an unknown length. You may not traverse the list to find the length. You may not use anything to help you find the length - as it is "unknown." (ie. no sizeof (C) or count(C#) etc...)

I had this question as an interview question. I'm just wondering what the answer is. I did ask if i could use sizeof, he said "no, the size of the string or array is unknown - you just need to get to the middle."

BTW, i'm not sure if this is actually possible to solve with no traversing. I almost felt as though he may have wanted to see how confident i am in my answer :S not sure...

His English was bad - also not sure if this contributed to misunderstandings. He directly told me that i do not need to traverse the list to get to the middle :S :S I'm assuming he meant no traversing at all..... :S

like image 698
BigBug Avatar asked Dec 02 '22 00:12

BigBug


1 Answers

Have two counters, c1 and c2. Begin traversing the list, incrementing c1 every time and c2 every other time. By the time c1 gets to the end, c2 will be in the middle.

You haven't "traversed the list to find the length" and then divided it by two, you've just gone through once.

The only other way I can think of would be to keep taking off the first and last item of the list until you are left with the one(s) in the middle.

like image 101
Nick Brunt Avatar answered Dec 21 '22 23:12

Nick Brunt