Largest Element

Pattern: Traversal and in-place tricks

easy

Find the largest element with one pass, starting the best-so-far at the first element so negative arrays work too.

The problem

You are given an array of between 1 and 100,000 whole numbers, each fitting in 32 bits. Return the largest. For example, the largest of [3, 9, 2] is 9, and the largest of [-5, -2, -9] is -2.

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name largestElement and the limits are this guide's own.

Think first

  • What do you need to remember while walking through the array?
  • What should it start as? Try your idea on [-5, -2, -9].
  • Would sorting help, and what would it cost?

Hints

    Brute force, and why it fails

    Sort the array and take the last element: correct, but O(n log n) to answer a question that needs one look at each element. Comparing every element with every other one is O(n²).

    The key insight

    You never need all the values at once. The largest so far, updated on every bigger value, is the largest overall when the pass ends.

    Dry run

    -50 
    -21 
    -92 
    largest-5

    nums = [-5, -2, -9]. Start largest at the first element, -5. Starting at 0 would be wrong here, because 0 is not in the array.

    Step 1 of 3

    The plan

    largest = nums[0]
    for i from 1 to n - 1:
        if nums[i] > largest:
            largest = nums[i]
    return largest
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One comparison per element and one variable.

    Edge cases

    • One element: it is the answer.
    • All negative: starting at nums[0] keeps the answer correct.
    • The extremes -2147483648 and 2147483647 are handled without overflow.
    I've built my logic, show the code

    Java

    class Solution {
        public int largestElement(int[] nums) {
            int largest = nums[0];
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] > largest) {
                    largest = nums[i];
                }
            }
            return largest;
        }
    }

    C++

    class Solution {
    public:
        int largestElement(vector<int>& nums) {
            int largest = nums[0];
            for (int i = 1; i < static_cast<int>(nums.size()); i++) {
                if (nums[i] > largest) {
                    largest = nums[i];
                }
            }
            return largest;
        }
    };

    Python

    class Solution:
        def largestElement(self, nums):
            largest = nums[0]
            for i in range(1, len(nums)):
                if nums[i] > largest:
                    largest = nums[i]
            return largest

    Common mistakes

    • Starting at 0 (or -1), which is wrong for all-negative arrays.
    • Returning the index instead of the value, or the other way round, when the problem asks for one of them.

    Similar problems