Leetcode 2733. Neither Minimum nor Maximum
Given an integer array nums
containing distinct positive integers, we need to return any number from the array that is neither the minimum value nor the maximum value in the array. If there are no such numbers, we should return -1
.
The constraints are:
1 <= nums.length <= 100
1 <= nums[i] <= 1000
-1
since it is not possible to have an element that is neither the minimum nor the maximum.-1
.Here’s a possible implementation in C++:
#include <iostream>
#include <vector>
#include <algorithm> // For std::min_element and std::max_element
int neitherMinNorMax(const std::vector<int>& nums) {
if (nums.size() < 3) {
return -1; // Not enough elements to satisfy the condition
}
// Find the minimum and maximum elements in the array
int minElem = *std::min_element(nums.begin(), nums.end());
int maxElem = *std::max_element(nums.begin(), nums.end());
// Find any element that is neither the minimum nor the maximum
for (const int& num : nums) {
if (num != minElem && num != maxElem) {
return num;
}
}
// If every element is either the minimum or the maximum (special case)
return -1;
}
int main() {
std::vector<int> nums = {3, 1, 2, 4};
int result = neitherMinNorMax(nums);
std::cout << "Result: " << result << std::endl;
return 0;
}
O(n)
where n
is the number of elements in the array.O(n)
traversal to find an element that is between min and max.Thus, the overall time complexity is O(n)
, making the solution efficient given the constraints.
O(1)
since we are using a constant amount of extra space irrespective of the input size.The provided code effectively and efficiently finds an element that is neither the minimum nor the maximum from a given list of distinct positive integers.
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?