Count Elements With Strictly Smaller and Greater Elements Problem
#2148
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2148.
Given an integer array nums, return the number of elements that have both a strictly smaller and a strictly greater element appear in nums.
Example 1:
Input: nums = [11,7,2,15]
Output: 2
Explanation: The element 7 has the element 2 strictly smaller than it and the element 11 strictly greater than it.
Element 11 has element 7 strictly smaller than it and element 15 strictly greater than it.
In total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.
Example 2:
Input: nums = [-3,3,3,90]
Output: 2
Explanation: The element 3 has the element -3 strictly smaller than it and the element 90 strictly greater than it.
Since there are two elements with the value 3, in total there are 2 elements having both a strictly smaller and a strictly greater element appear in nums.
Constraints:
1 <= nums.length <= 100-10^5 <= nums[i] <= 10^5
Solution
Approach: Minimum and Maximum
An element has both a strictly smaller and a strictly greater element exactly when it is neither the minimum nor the maximum. Find the minimum mi and the maximum mx of nums, then count the elements x with mi < x < mx.
Complexity: O(n) time and O(1) extra space.
class Solution:
def countElements(self, nums: List[int]) -> int:
mi, mx = min(nums), max(nums)
return sum(mi < x < mx for x in nums)