Count Elements With Strictly Smaller and Greater Elements
Problem
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appearing in nums.
nums = [11,7,2,15]2def count_elements(nums):
lo, hi = min(nums), max(nums)
count = 0
for x in nums:
if lo < x < hi:
count += 1
return count
function countElements(nums) {
const lo = Math.min(...nums);
const hi = Math.max(...nums);
let count = 0;
for (const x of nums) {
if (x > lo && x < hi) count++;
}
return count;
}
class Solution {
public int countElements(int[] nums) {
int lo = Integer.MAX_VALUE, hi = Integer.MIN_VALUE;
for (int x : nums) { lo = Math.min(lo, x); hi = Math.max(hi, x); }
int count = 0;
for (int x : nums) if (x > lo && x < hi) count++;
return count;
}
}
int countElements(vector<int>& nums) {
int lo = *min_element(nums.begin(), nums.end());
int hi = *max_element(nums.begin(), nums.end());
int count = 0;
for (int x : nums) if (x > lo && x < hi) count++;
return count;
}
Explanation
An element qualifies only if something smaller and something larger both exist in the array. The smallest possible "something smaller" is the array's minimum, and the largest possible "something larger" is its maximum.
So an element x has a strictly smaller partner exactly when x > min, and a strictly greater partner exactly when x < max. Both conditions together mean min < x < max.
The algorithm is two quick scans: first find lo = min and hi = max, then count how many elements fall strictly between them.
Notice elements equal to the min or max are excluded — they lack a smaller or larger partner respectively — which is why the comparisons are strict.
Example: [11,7,2,15]. Here lo = 2, hi = 15. Checking each: 11 and 7 satisfy 2 < x < 15, while 2 (the min) and 15 (the max) do not. Count = 2.