Start learning free

LESSON 116 OF 505 · ARRAYS - CHALLENGES

Middle Element in Kotlin

Practice

Given an ArrayList of integers nums with an odd number of items, return the item in the middle.

The middle index is the length of nums divided by 2, rounded down. For example, 5 items have the indexes 0 to 4, and 5 divided by 2, rounded down, is 2: two items come before index 2 and two come after it.

 

Example 1:

Input: nums = [1, 2, 3]
Output: 2
Explanation: The length is 3, and 3 divided by 2, rounded down, is 1. The item at index 1 is 2.

Example 2:

Input: nums = [5, 9, 1, 8, 4]
Output: 1
Explanation: The middle index is 2, and the item there is 1. The middle is about the position, not the size of the number.

Example 3:

Input: nums = [7]
Output: 7
Explanation: 1 divided by 2, rounded down, is 0: the only item is the middle one.

 

Constraints:

  • nums has an odd number of items: 1, 3, 5 and so on.
  • Every number is an integer between -1000 and 1000.
STEP 1 OF 2
    Ctrl + Enter to check

    Middle Element in Kotlin

    Keep going with Kotlin500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free