We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Elements With Strictly Smaller and Greater Elements

Number: 2269

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer array, return the number of elements that have both a strictly smaller and a strictly greater element present in the array.


Key Insights

  • The smallest and largest elements of the array cannot have both a strictly smaller and a strictly greater element.
  • If the smallest and largest values are equal, no element qualifies.
  • The solution focuses on counting elements that lie strictly between the minimum and maximum values.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the array, since we traverse the array a few times. Space Complexity: O(1), as we only use a fixed amount of extra space.


Solution

The solution involves the following steps:

  1. Identify the minimum and maximum values in the array.
  2. Traverse the array and count elements that are strictly greater than the minimum and strictly less than the maximum.
  3. Return the count.

We use simple comparisons and count variables to solve the problem in a single pass (after determining the min and max). This approach leverages constant space and linear time.


Code Solutions

# Define the function count_elements that takes the list of integers as input.
def count_elements(nums):
    # Step 1: Find the minimum and maximum values in the array.
    min_val = min(nums)
    max_val = max(nums)
    
    # Initialize a count variable.
    count = 0
    
    # Step 2: Iterate over the list and count elements that are strictly between min_val and max_val.
    for num in nums:
        # If the number is greater than the minimum and less than the maximum, update count.
        if min_val < num < max_val:
            count += 1
            
    # Step 3: Return the final count.
    return count

# Example usage:
nums = [11, 7, 2, 15]
print(count_elements(nums))  # Expected output: 2
← Back to All Questions