Count Elements With Strictly Smaller and Greater Elements - Problem
Given an integer array nums, you need to find how many elements have both a strictly smaller element and a strictly greater element present somewhere in the array.
In other words, for each element nums[i], count it only if there exists at least one element in the array that is strictly smaller than nums[i] AND at least one element that is strictly greater than nums[i].
Example: In array [11, 7, 2, 15], elements 11 and 7 satisfy this condition:
11has7, 2(smaller) and15(greater)7has2(smaller) and11, 15(greater)2has no smaller element15has no greater element
So the answer is 2.
Input & Output
example_1.py โ Basic Case
$
Input:
[11,7,2,15]
โบ
Output:
2
๐ก Note:
Element 11 has smaller elements (7,2) and greater element (15). Element 7 has smaller element (2) and greater elements (11,15). Elements 2 and 15 are min/max so they can't have both conditions.
example_2.py โ All Same Elements
$
Input:
[6,6,6,6]
โบ
Output:
0
๐ก Note:
All elements are equal, so no element has both a strictly smaller and strictly greater element in the array.
example_3.py โ Small Array
$
Input:
[1,2]
โบ
Output:
0
๐ก Note:
With only 2 elements, neither can have both smaller and greater elements. Each element can have at most one of the two conditions.
Visualization
Tap to expand
Understanding the Visualization
1
Line Up All Players
Arrange all team members to see their heights: [2, 7, 11, 15]
2
Identify Extremes
Find the shortest (2) and tallest (15) players - they can't satisfy our condition
3
Count Middle Players
Players with heights 7 and 11 have both shorter and taller teammates
4
Final Count
2 players satisfy the condition of having both shorter and taller teammates
Key Takeaway
๐ฏ Key Insight: Only elements that are neither minimum nor maximum can have both smaller and greater elements in the array!
Time & Space Complexity
Time Complexity
O(n)
Two passes through the array: one to find min/max, another to count valid elements
โ Linear Growth
Space Complexity
O(1)
Only storing min, max, and count variables
โ Linear Space
Constraints
- 3 โค nums.length โค 100
- -100 โค nums[i] โค 100
- The array must contain at least 3 elements for any valid answers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code