Last Updated: 10 Oct, 2025

Middle Element via Tortoise and Hare

Easy
Asked in company
Expedia Group

Problem statement

You are tasked with finding the middle element of an array by implementing a specific traversal algorithm known as Floyd's Cycle-Finding Algorithm, commonly called the "Tortoise and Hare" or two-pointer approach.


The algorithm must be implemented as follows:


1) Initialize two pointers, slow and fast, both pointing to the start of the array (index 0).


2) Iteratively move the pointers through the array: the slow pointer advances by one step (+1), and the fast pointer advances by two steps (+2).


3) The process stops when the fast pointer can no longer make a full two-step jump without going out of the array's bounds.


4) When the loop terminates, the slow pointer will be positioned at the middle element of the array.


Your function should return the value of the element at the slow pointer's final position.


Input Format:
The first line contains a single integer N, the size of the array.

The second line contains N space-separated integers, representing the elements of the array.


Output Format:
Print a single integer, which is the value of the middle element found by the algorithm.


Note:
While the middle element of an array can be found in O(1) time with arr[n/2], the purpose of this problem is to practice the specific two-pointer "Tortoise and Hare" traversal technique.