Count Elements With Strictly Smaller and Greater Elements

The problem asks us to find the number of elements in the given array that have both a strictly smaller and a strictly greater element within the array.

We’ll iterate through the array and for each element, we’ll check if there’s a strictly smaller and a strictly greater element in the array.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def countElements(self, nums: List[int]) -> int:
        # Initialize a counter for the number of elements satisfying the condition
        count = 0

        # Iterate through the elements in the array
        for num in nums:
            # Check if there's a strictly smaller and a strictly greater element in the array
            if any(x < num for x in nums) and any(x > num for x in nums):
                count += 1

        # Return the final count
        return count

Explanation

  • For each element num in the array, we’re using the any function along with a generator expression to check if there’s a strictly smaller and a strictly greater element in the array.
  • If both conditions are met, we increment the count.
  • We return the final count as the result.

Example

For the input nums = [11,7,2,15], the method would return 2, since the elements 7 and 11 have both strictly smaller and strictly greater elements within the array.