All challenges
Easy 0 solved 0% acceptance

Min and Max Together

Find the smallest and largest value in one pass.

What you'll learn

  • Track the minimum and maximum together
  • Return two values at once
  • Visit each element only once

Problem

Walk through the list once and track both the smallest and the largest value.

Implement min_and_max(numbers).

Input

numbers: A non-empty list of integers.

Output

Return [smallest, largest].

Constraints

1 ≤ length ≤ 100,000

Examples

Example 1
Input:
numbers = [4, -2, 9, 0]

Expected output:
expected = [-2, 9]
Input:
std::vector<long long> numbers = {4, -2, 9, 0};

Expected output:
std::vector<long long> expected = {-2, 9};
Input:
long[] numbers = new long[] {4, -2, 9, 0};

Expected output:
long[] expected = new long[] {-2, 9};

Explanation

The smallest value is -2 and the largest is 9: [-2, 9].

Example 2
Input:
numbers = [7]

Expected output:
expected = [7, 7]
Input:
std::vector<long long> numbers = {7};

Expected output:
std::vector<long long> expected = {7, 7};
Input:
long[] numbers = new long[] {7};

Expected output:
long[] expected = new long[] {7, 7};

Explanation

With one value it is both the smallest and largest: [7, 7].

How to approach it

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

Hint 1

Track the smallest and largest values as you move through the list once.

Hint 2

Update your running minimum and maximum whenever you see a new extreme.

Hint 3

Since the list is guaranteed non-empty, you can start from its first element.

Expected complexity

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

References

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

Learn from others

Community solutions

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