Question
Write a function that returns the smallest number in an array.
Approach
- Initialize a variable
smallesttoInfinity. - Loop through the array.
- If the current element is less than
smallest, updatesmallest. - Return
smallestafter the loop ends.
Example
Input: arr = [2, -6, 4, 8, 1, -9]
Output: -9
Time & Space Complexity
- Time Complexity:
O(n)– wherenis the number of elements in the array. - Space Complexity:
O(1)– only one variable is used.
function findSmallest(arr) {
let smallest = Infinity;
for (let i = 0; i < arr.length; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
return smallest;
}
let arr = [2, -6, 4, 8, 1, -9];
let result = findSmallest(arr);
console.log("Result:", result); // Output: -9
#include <stdio.h>
int findSmallest(int arr[], int n) {
int smallest = 2147483647; // INT_MAX
for (int i = 0; i < n; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
return smallest;
}
int main() {
int arr[] = {2, -6, 4, 8, 1, -9};
int result = findSmallest(arr, 6);
printf("Result: %d\n", result); // Output: -9
return 0;
}
#include <iostream>
#include <climits>
using namespace std;
int findSmallest(int arr[], int n) {
int smallest = INT_MAX;
for (int i = 0; i < n; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}
return smallest;
}
int main() {
int arr[] = {2, -6, 4, 8, 1, -9};
int result = findSmallest(arr, 6);
cout << "Result: " << result << endl; // Output: -9
return 0;
}
public class Main {
public static int findSmallest(int[] arr) {
int smallest = Integer.MAX_VALUE;
for (int num : arr) {
if (num < smallest) {
smallest = num;
}
}
return smallest;
}
public static void main(String[] args) {
int[] arr = {2, -6, 4, 8, 1, -9};
int result = findSmallest(arr);
System.out.println("Result: " + result); // Output: -9
}
}
def find_smallest(arr):
smallest = float('inf')
for num in arr:
if num < smallest:
smallest = num
return smallest
arr = [2, -6, 4, 8, 1, -9]
result = find_smallest(arr)
print("Result:", result) # Output: -9
