Open In App

How to Find the Third Smallest Number in an Array in C++?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is the collection of similar data elements that are stored in the contiguous memory location and we can access these elements directly by their index value. In this article, we will learn how to find the third smallest element in an array in C++. If there is no third smallest element, return -1.

Example

Input:
myArray = {1, 45, 54, 71, 76, 17}
Output: 45
Explanation: The third smallest element in the array is 45, hence the output is 45.

Input:
myArray = {10, 20, 10, 20}
Output: -1
Explanation: The array has less than three distinct elements, hence the output is -1.

Find the Third Smallest Number in an Array in C++

To find the third smallest number in an array in C++, we can use the priority_queue container in the following way:

Approach

  1. First, create the priority_queue container.
  2. Then, start pushing elements into the priority queue.
  3. If the size of the priority queue is greater than 3, pop the top element.
  4. Keep doing it till all the array elements are pushed.
  5. Now, if the priority_queue contains three elements, the top element is the third smallest element.
  6. If the priority_queue does not contain three elements, return -1 as there is no third smallest element.

C++ Program to Find the Third Smallest Number in an Array

C++




// C++ program to find the third smallest number in an array
#include <iostream>
#include <queue>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> vec = { 7, 4, 6, 3, 9, 1 };
  
    // Create a max heap
    priority_queue<int> maxHeap;
  
    for (int num : vec) {
        maxHeap.push(num);
        if (maxHeap.size() > 3) {
            maxHeap.pop();
        }
    }
  
    if (maxHeap.size() == 3) {
        cout << "The third smallest number is: "
             << maxHeap.top() << "\n";
    }
    else {
        cout << "The array does not have a third smallest "
                "number.\n";
    }
  
    return 0;
}


Output

The third smallest number is: 4

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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads