Leetcode 2148. Count Elements With Strictly Smaller and Greater Elements
Given an integer array nums
, return the number of elements in the array that have both a strictly smaller and a strictly greater element.
Before we start with the solution, let’s clarify a few points about the problem:
1 <= nums.length <= 1000
)-10^5 <= nums[i] <= 10^5
)Let’s move forward with the understanding that the array can have any length, the values can be any integer, and the array can contain duplicates.
To solve this problem, we need to:
Here is the implementation in Java:
public class ElementCounter {
public int countElements(int[] nums) {
if (nums == null || nums.length < 3) {
return 0;
}
int min = nums[0];
int max = nums[0];
// Find the min and max values in the array
for (int num : nums) {
if (num < min) {
min = num;
} else if (num > max) {
max = num;
}
}
int count = 0;
// Count elements that are strictly greater than min and strictly less than max
for (int num : nums) {
if (num > min && num < max) {
count++;
}
}
return count;
}
public static void main(String[] args) {
ElementCounter counter = new ElementCounter();
int[] nums = {11, 7, 2, 15}; // Example input
System.out.println(counter.countElements(nums)); // Expected output: 2
}
}
Overall, the time complexity of this solution is O(n), where n
is the number of elements in the input array. This is efficient and expected for this type of problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?