Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if the array has an element which is equal to sum of all the remaining elements in Python
Sometimes we need to check if an array contains an element whose value equals the sum of all other elements. This problem can be solved efficiently by calculating the total sum and using a frequency map.
For example, in the array [3, 2, 10, 4, 1], the element 10 equals the sum of remaining elements: 3 + 2 + 4 + 1 = 10.
Algorithm Approach
The key insight is that if an element equals the sum of all other elements, then that element must be exactly half of the total array sum ?
- Calculate the total sum of all elements
- Store frequency of each element using a dictionary
- If total sum is even, check if
total/2exists in the array - Return
Trueif found, otherwiseFalse
Example Implementation
from collections import defaultdict
def solve(nums):
freq = defaultdict(int)
total = 0
# Calculate total sum and frequency of each element
for i in range(len(nums)):
freq[nums[i]] += 1
total += nums[i]
# Check if total is even and half exists in array
if total % 2 == 0:
if freq[total // 2]:
return True
return False
# Test the function
nums = [3, 2, 10, 4, 1]
result = solve(nums)
print(f"Array: {nums}")
print(f"Has element equal to sum of others: {result}")
Array: [3, 2, 10, 4, 1] Has element equal to sum of others: True
How It Works
Let's trace through the example [3, 2, 10, 4, 1] ?
def solve_with_trace(nums):
freq = defaultdict(int)
total = 0
print(f"Processing array: {nums}")
for num in nums:
freq[num] += 1
total += num
print(f"Total sum: {total}")
print(f"Frequency map: {dict(freq)}")
if total % 2 == 0:
target = total // 2
print(f"Target value (total/2): {target}")
if freq[target]:
print(f"Element {target} found in array!")
return True
else:
print(f"Element {target} not found in array")
else:
print("Total sum is odd, no solution possible")
return False
# Test with example
nums = [3, 2, 10, 4, 1]
result = solve_with_trace(nums)
Processing array: [3, 2, 10, 4, 1]
Total sum: 20
Frequency map: {3: 1, 2: 1, 10: 1, 4: 1, 1: 1}
Target value (total/2): 10
Element 10 found in array!
Additional Test Cases
# Test multiple cases
test_cases = [
[3, 2, 10, 4, 1], # True: 10 = 3+2+4+1
[1, 2, 3, 6], # True: 6 = 1+2+3
[1, 2, 3, 4], # False: no element equals sum of others
[5, 5], # True: 5 = 5
[1, 1, 1, 3] # True: 3 = 1+1+1
]
for i, nums in enumerate(test_cases, 1):
result = solve(nums)
print(f"Test {i}: {nums} ? {result}")
Test 1: [3, 2, 10, 4, 1] ? True Test 2: [1, 2, 3, 6] ? True Test 3: [1, 2, 3, 4] ? False Test 4: [5, 5] ? True Test 5: [1, 1, 1, 3] ? True
Time and Space Complexity
Time Complexity: O(n) where n is the length of the array. We iterate through the array once.
Space Complexity: O(n) for storing the frequency map in the worst case when all elements are unique.
Conclusion
This approach efficiently solves the problem by recognizing that the target element must be exactly half of the total sum. Using a frequency map allows us to check existence in constant time.
---