Knowee
Questions
Features
Study Tools

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.

🧐 Not the exact question you are looking for?Go ask a question

Solution

To find the smallest and second smallest elements in an array of integers, follow these steps:

  1. Initialize two variables, smallest and second_smallest, with values that are greater than any possible element in the array. For example, you can set smallest to infinity and second_smallest to infinity + 1.

  2. Iterate through each element in the array.

  3. Compare the current element with the value of smallest. If the current element is smaller than smallest, update smallest with the value of the current element.

  4. If the current element is not smaller than smallest but smaller than second_smallest, update second_smallest with the value of the current element.

  5. After iterating through all the elements, check if second_smallest is still greater than smallest. If it is, it means that there is no second smallest element in the array. In this case, print -1.

  6. Otherwise, print the values of smallest and second_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.

This problem has been solved

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

1/1

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.