Back to Interview Prep

Warm Up · Loops 02

Find Largest Number in an Array

Problem Statement

Write a function that returns the largest number in an array.

Example

Input: arr = [2, -6, 4, 8, 1, -9]

Process: largest goes 2 → 4 → 8

Output: 8

Approach

  • Initialize a variable largest to -Infinity.
  • Loop through the array.
  • If the current element is greater than largest, update largest.
  • Return largest after the loop ends.

Time & Space Complexity

Time Complexity: O(n) - where n is the number of elements in the array.

Space Complexity: O(1) - only a single variable is used.

Visualisation

1Start with the array[2, -6, 4, 8, 1, -9]
2Assume nothing is larger yetlet largest = -Infinity;
3Larger than current largest? Replace itarr[i] > largest
4Largest number8

Explanation

  • Starting at -Infinity guarantees the first element always becomes the new largest, even if every number is negative.
  • Each time a bigger value appears, largest is updated: 2, then 4, then 8.
  • After one pass through the array, largest holds the maximum value.

Your solution

Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.

// Write your solution in JavaScript
// Print the answer with console.log()


Console

No output yet. Use console.log() to print values here.

Write your own solution and press Submit once to unlock the answer.

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in