Easy 0 solved 0% acceptance

Middle Item

Read numbers up to a negative sentinel and return the middle one.

What you'll learn

  • Stop reading input at a sentinel value
  • Find the middle index of a list
  • Handle an empty input

Problem

A teacher types quiz scores into a program and ends the list with any negative number, which is a stop signal and not a score. The program should report the middle score in the order the scores were typed (they are not sorted). With k scores the middle one is at position k / 2 counting from 0 and rounding down, so for an even count it is the second of the two middle scores.

Implement middle_item(values).

Input

values: The numbers as typed. Reading stops at the first negative number; it and everything after it are ignored. If there is no negative number, every value is a score.

Output

Return the middle score. If there are no scores before the stop signal, return -1.

Constraints

0 ≤ length of values ≤ 1000

−1000 ≤ each value ≤ 1000

Examples

Example 1
Input:
values = [88, 72, 95, 60, 81, -1]

Expected output:
expected = 95
Input:
std::vector<long long> values = {88, 72, 95, 60, 81, -1};

Expected output:
long long expected = 95;
Input:
long[] values = new long[] {88, 72, 95, 60, 81, -1};

Expected output:
long expected = 95;

Explanation

The scores are 88, 72, 95, 60, 81; there are 5, so the middle is position 2, which is 95.

Example 2
Input:
values = [10, 20, 30, 40, -5, 50]

Expected output:
expected = 30
Input:
std::vector<long long> values = {10, 20, 30, 40, -5, 50};

Expected output:
long long expected = 30;
Input:
long[] values = new long[] {10, 20, 30, 40, -5, 50};

Expected output:
long expected = 30;

Explanation

Reading stops at −5, leaving 4 scores; position 2 holds 30.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Copy values into a new list until you meet the first negative number.

Hint 2

With k items the middle index is k / 2 using integer division.

Hint 3

If nothing was copied, there is no middle item.

Expected complexity

O(n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

The best passing solution of each coder. Faster, smaller and better-reviewed solutions rank higher.

No passing solutions yet. Solve it to take first place.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.