Identify the Largest Outlier in an Array Problem
Description
LeetCode Problem 3371.
You are given an integer array nums. This array contains n elements, where exactly n - 2 elements are special numbers. One of the remaining two elements is the sum of these special numbers, and the other is an outlier.
An outlier is defined as a number that is neither one of the original special numbers nor the element representing the sum of those numbers.
Note that special numbers, the sum element, and the outlier must have distinct indices, but may share the same value.
Return the largest potential outlier in nums.
Example 1:
Input: nums = [2,3,5,10]
Output: 10
Explanation:
The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.
Example 2:
Input: nums = [-2,-1,-3,-6,4]
Output: 4
Explanation:
The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.
Example 3:
Input: nums = [1,1,1,1,1,5,5]
Output: 5
Explanation:
The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.
Constraints:
3 <= nums.length <= 10^5-1000 <= nums[i] <= 1000- The input is generated such that at least one potential outlier exists in
nums.
Solution
Approach: Hash Table + Enumeration
Let S be the sum of the whole array. If x is the outlier, the remaining numbers are the special numbers plus their sum, and that sum equals the total of the special numbers, so S - x = 2 * sumElement. Hence t = S - x must be even and t / 2 must be present in the array.
Count every value in a hash table cnt. Try each distinct value x as the outlier: skip it if S - x is odd or (S - x) / 2 does not occur. Also, if (S - x) / 2 == x, the value x is needed twice (once as outlier, once as the sum element), so it must occur at least twice. Keep the largest x that passes.
Complexity: time O(n), space O(n), where n is the length of nums.
from collections import Counter
from math import inf
class Solution:
def getLargestOutlier(self, nums: List[int]) -> int:
s = sum(nums)
cnt = Counter(nums)
ans = -inf
for x, v in cnt.items():
t = s - x
if t % 2 or cnt[t // 2] == 0:
continue
if x != t // 2 or v > 1:
ans = max(ans, x)
return ans