VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-middle-element-of-an-array-or-list/

⇱ Find the Middle Element of an Array or List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Middle Element of an Array or List

Last Updated : 18 Apr, 2024

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.

Example

Input: arr = {1, 2, 3, 4, 5}
Output: 3

Input: arr = {7, 8, 9, 10, 11, 12}
Output: 9 10

Approach:

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:


Output
Middle Element(s): 3 

Time Complexity: O(1)
Auxiliary Space: O(1)

Approach 2 (Slow and fast pointer approach)

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.

Example

Below is the Implementation of the above approach:


Output
Middle element of array: 3
Middle element of linked list: 3

This approach of finding middle element is contributed by Ayush Mishra.

Comment
Article Tags: