702711. Equal Sum

Medium

Equal Sum

Slug: equal-sum0810 Difficulty: Medium Id: 702711 Topic Tags: Arrays, Data Structures Company Tags: None

Summary

The Equal Sum problem requires you to find two non-identical elements in a given array that have the same sum. This is a classic problem that involves arrays and data structures. The key concept involved here is the concept of pairing.

Detailed Explanation

To solve this problem, we will use a simple algorithm that iterates over the array once. We keep track of the elements we've seen so far and their corresponding sums. If we find two non-identical elements with the same sum, we return them as our result.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty hashmap to store the elements and their corresponding sums.
  2. Iterate over the array:
    • For each element, calculate its sum by adding it to all previously seen elements.
    • Check if this sum is already present in the hashmap. If yes, then we have found two non-identical elements with the same sum.
  3. Return the pair of elements (or null if no such pair exists).

Time complexity: O(n), where n is the size of the array. We only need to iterate over the array once.

Space complexity: O(n), as in the worst case, we might end up storing all elements and their sums in the hashmap.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class EqualSum {
    public static int[] equalSum(int[] arr) {
        Map<Integer, Integer> sumMap = new HashMap<>();
        for (int num : arr) {
            int totalSum = 0;
            for (int i = 0; i < arr.length; i++) {
                if (i != arr.indexOf(num)) {
                    totalSum += arr[i];
                }
            }
            if (!sumMap.containsKey(totalSum)) {
                sumMap.put(totalSum, num);
            } else {
                return new int[]{num, sumMap.get(totalSum)};
            }
        }
        return null;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.