EasyNo. 2148

Count Elements With Strictly Smaller and Greater Elements — LeetCode 2148 Python Solution

Pattern
Sorting
Topics
Array, Counting, Sorting
Reading time
2 min

The problem

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

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.

Python solution

PythonSolution
class Solution:
    def countElements(self, nums: List[int]) -> int:
        mi, mx = min(nums), max(nums)
        return sum(mi < x < mx for x in nums)

Complexity

Time
O(n)where n is the length of the array nums
Space · auxiliary
O(1)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0056Merge IntervalsMedium
0164Maximum GapMedium
0274H-IndexMedium
0406Queue Reconstruction by HeightMedium
0414Third Maximum NumberEasy
0462Minimum Moves to Equal Array Elements IIMedium

Frequently asked questions

How hard is LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements?

LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements is rated Easy on LeetCode.

What is the time complexity of LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements?

The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.

What is the space complexity of LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements cover?

LeetCode 2148. Count Elements With Strictly Smaller and Greater Elements is tagged Array, Counting and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.