#2148

Count Elements With Strictly Smaller and Greater Elements

Easy
ArraySortingCountingArrayCounting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking each element against all others, we can find the minimum and maximum values in the array. All elements except these two will have both smaller and greater elements.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the minimum and maximum values in the array.
  2. 2Step 2: Count how many times the minimum and maximum appear in the array.
  3. 3Step 3: Calculate the result as total elements minus the counts of min and max.
solution.py11 lines
1# Full working Python code
2
3def count_elements(nums):
4    min_val = min(nums)
5    max_val = max(nums)
6    count_min = nums.count(min_val)
7    count_max = nums.count(max_val)
8    return len(nums) - count_min - count_max
9
10# Example usage
11print(count_elements([11, 7, 2, 15]))  # Output: 2

Complexity note: The time complexity is O(n) because we traverse the array a constant number of times (once for min/max and once for counting).

  • 1Elements must be strictly smaller and greater, so we exclude min and max.
  • 2Counting occurrences of min and max helps in calculating the result efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.