![]() |
VOOZH | about |
Given an array or a list of elements. The task is to find the middle element of given array or list of elements. If the array size is odd, return the single middle element. If the array size is even, return the two middle elements.
Input: arr = {1, 2, 3, 4, 5}
Output: 3Input: arr = {7, 8, 9, 10, 11, 12}
Output: 9 10
Check the length of array is even or odd. For odd array length the middle element would be arr[length/2]. Otherwise, two middle element that is: arr[length/2] and arr[length/2 -1]
Below is the implementation of the above approach:
Middle Element(s): 3
Time Complexity: O(1)
Auxiliary Space: O(1)
We use the concept of slow and fast pointer to find the middle element of array or list. We declare two pointers slow and fast for linked list and two variables slow and fast for arrays. Initially both slow and fast points to starting element of array or list. Increase slow pointer by 1 and increase fast pointer by 2. Traverse until fast reaches to end of array or list. then traverse again fast pointing to start and Return the slow pointer node as middle element of list or array.
Below is the Implementation of the above approach:
Middle element of array: 3 Middle element of linked list: 3
This approach of finding middle element is contributed by Ayush Mishra.