Leetcode 2148. Count Elements With Strictly Smaller and Greater Elements
Given an integer array nums
, return the number of elements that have both a strictly smaller and a strictly greater element.
nums
contain negative numbers?
nums
can contain both positive and negative integers.nums
to contain duplicates?
nums
can have duplicate values.nums
can have?
Here’s the C++ implementation:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
int countElements(vector<int>& nums) {
if (nums.size() < 3) return 0; // If less than 3 elements, not possible to have both smaller and greater elements
sort(nums.begin(), nums.end()); // Sort the array
int smallest = nums.front(); // Smallest element
int largest = nums.back(); // Largest element
int count = 0;
// Count elements strictly between smallest and largest
for (int num : nums) {
if (num > smallest && num < largest) {
++count;
}
}
return count;
}
int main() {
vector<int> nums = {11, 7, 2, 15};
cout << "Count of elements with both strictly smaller and greater elements: " << countElements(nums) << endl;
return 0;
}
Thus, the overall time complexity is (O(n \log n)) where (n) is the number of elements in the array.
The space complexity is (O(1)) if we disregard the space used by the sorting function (which typically uses (O(\log n)) space). Therefore, the main space usage is constant, independent of the input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?