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: 3
💡 Note: Min=2, Max=10. Elements between: first 6 (2<6<10), 5 (2<5<10), second 5 (2<5<10). Count = 3
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: [11,7,2,15] → Which have both smaller and greater?117215✓ Valid✓ Valid✗ No smaller✗ No greatersmaller: 7,2smaller: 2greater: 7,11,15smaller: 11,7,2greater: 15greater: 11,15Elements 11 and 7 have both smaller and greater elementsResult: Count = 2
Understanding the Visualization
1
Input Array
Given array [11,7,2,15] with various values
2
Check Conditions
For each element, verify both smaller and greater exist
3
Count Valid
Count elements satisfying both conditions = 2
Key Takeaway
🎯 Key Insight: Only elements that are neither minimum nor maximum can have both smaller and greater neighbors
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