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:

  • 11 has 7, 2 (smaller) and 15 (greater)
  • 7 has 2 (smaller) and 11, 15 (greater)
  • 2 has no smaller element
  • 15 has 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
๐Ÿ€ Basketball Team Height Analogy2SHORTEST7โœ“ VALID11โœ“ VALID15TALLESTPlayers with both shorter and taller teammatesAnswer: 2 players (heights 7 and 11)
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only storing min, max, and count variables

n
2n
โœ“ Linear Space

Constraints

  • 3 โ‰ค nums.length โ‰ค 100
  • -100 โ‰ค nums[i] โ‰ค 100
  • The array must contain at least 3 elements for any valid answers
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 5
28.6K Views
Medium Frequency
~12 min Avg. Time
892 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