Given an array of integers, your task is to find the smallest and second smallest element in the array. If smallest and second smallest do not exist, print -1.
Question
Given an array of integers, your task is to find the smallest and second smallest element in the array. If smallest and second smallest do not exist, print -1.
Solution
To find the smallest and second smallest elements in an array of integers, follow these steps:
-
Initialize two variables,
smallest
andsecond_smallest
, with values that are greater than any possible element in the array. For example, you can setsmallest
to infinity andsecond_smallest
to infinity + 1. -
Iterate through each element in the array.
-
Compare the current element with the value of
smallest
. If the current element is smaller thansmallest
, updatesmallest
with the value of the current element. -
If the current element is not smaller than
smallest
but smaller thansecond_smallest
, updatesecond_smallest
with the value of the current element. -
After iterating through all the elements, check if
second_smallest
is still greater thansmallest
. If it is, it means that there is no second smallest element in the array. In this case, print -1. -
Otherwise, print the values of
smallest
andsecond_smallest
.
Here is an example implementation in Python:
def find_smallest_and_second_smallest(arr):
smallest = float('inf')
second_smallest = float('inf') + 1
for num in arr:
if num < smallest:
second_smallest = smallest
smallest = num
elif num < second_smallest and num != smallest:
second_smallest = num
if second_smallest == float('inf') + 1:
print(-1)
else:
print(smallest, second_smallest)
You can call this function with your array as an argument to find the smallest and second smallest elements.
Similar Questions
Write a C function, which returns the smallest odd number in a given array, and 0 if no such number is found.int smallest_odd(int a[] , int len);
In Selection Sort, what is the minimum number of comparisons required to find the smallest element and place it in the first position of the array?
Which function is used to calculate the smallest integer greater than or equal to a number?
ct answerWhat will be the output of the following Python function?min(max(False,-3,-4), 2,7)Options-42-3
Write a Python program to find the Index position of a specified element and print it. And if the specified element is not present then print -1 as
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.