Problem Statement
Find the smallest element in an unsorted array. The goal is to identify the minimum value efficiently without traversing the entire array multiple times.
Algorithmic Approach / Logic
To find the smallest number, you can iterate through the array once and keep track of the current minimum value encountered. This approach ensures that you only need to traverse the array once, resulting in an overall time complexity of O(n), where n is the number of elements in the array.
Code Implementation
def find_smallest_number(arr):
# Initialize the smallest number with the first element
smallest = arr[0]
# Iterate through the array starting from the second element
for num in arr[1:]:
# Update smallest if a smaller number is found
if num < smallest:
smallest = num
return smallest
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
This algorithm efficiently finds the smallest number in an array with constant space usage, making it suitable for large datasets.