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 appear in nums.

In other words, for each element nums[i], count it if there exists some element nums[j] where nums[j] < nums[i] and some element nums[k] where nums[k] > nums[i].

Input & Output

Example 1 — Basic Case
$ Input: nums = [11,7,2,15]
Output: 2
💡 Note: Element 11: has smaller (7,2) and greater (15) ✓. Element 7: has smaller (2) and greater (11,15) ✓. Element 2: has greater (7,11,15) but no smaller ✗. Element 15: has smaller (11,7,2) but no greater ✗. Count = 2
Example 2 — No Valid Elements
$ Input: nums = [6,2,6,5,10,5]
Output: 4
💡 Note: Min=2, Max=10. Elements between: first 6 (2<6<10), second 6 (2<6<10), first 5 (2<5<10), second 5 (2<5<10). Count = 4
Example 3 — Minimum Size
$ Input: nums = [1,2]
Output: 0
💡 Note: With only 2 elements, neither can have both smaller and greater elements. Count = 0

Constraints

  • 1 ≤ nums.length ≤ 100
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Count Elements With Strictly Smaller and Greater INPUT nums = [11, 7, 2, 15] 11 i=0 7 i=1 2 i=2 15 i=3 Number Line: 2 MIN 7 11 15 MAX Elements to check: - 11: has smaller(2,7) has greater(15) - 7: has smaller(2) has greater(11,15) ALGORITHM STEPS 1 Find MIN and MAX min=2, max=15 2 Check each element Is it != min AND != max? 3 Count valid elements Elements between min/max 4 Return count Elements with both Verification Table Val Smaller? Greater? Valid? 2 NO YES NO 7 YES YES OK 11 YES YES OK 15 YES NO NO FINAL RESULT Valid elements found: 7 11 Both have smaller AND greater Invalid elements: 2 MIN 15 MAX Output: 2 Key Insight: An element has both a strictly smaller and strictly greater element if and only if it is NOT the minimum and NOT the maximum of the array. Simply count elements where min < nums[i] < max. Time: O(n), Space: O(1) TutorialsPoint - Count Elements With Strictly Smaller and Greater Elements | Optimal Solution
Asked in
Amazon 15 Microsoft 8
15.0K Views
Medium Frequency
~15 min Avg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen