703288. Sum of f(a[i], a[j]) over all pairs in an array of n integers

Easy

Here is a detailed Markdown blog post for the given GeeksforGeeks problem:

Sum of f(a[i], a[j]) over all pairs in an array of n integers

Slug: sum-of-fai-aj-over-all-pairs-in-an-array-of-n-integers4057

Difficulty: Easy

Id: 703288

Topic Tags: Arrays, Hash, Map, Data Structures

Summary

The problem is to find the sum of a function f(a[i], a[j]) for all pairs (i, j) in an array of n integers. The key concept involved is arrays and data structures.

Detailed Explanation

To solve this problem, we can use a two-pointer approach with sorting. First, sort the array of n integers. Then, initialize two pointers, left and right, to point to the first and last elements of the sorted array respectively.

For each iteration:

  1. Calculate the sum for the current pair using the function f(a[left], a[right]).
  2. If the sum is less than 0, move the left pointer to the right.
  3. If the sum is greater than or equal to 0, move the right pointer to the left.
  4. Repeat steps 1-3 until the pointers meet.

This approach ensures that all pairs are considered and the function f(a[i], a[j]) is evaluated for each pair once. The time complexity of this solution is O(n log n) due to sorting, where n is the size of the array. The space complexity is O(1), as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        Arrays.sort(arr);
        long sum = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                sum += f(arr[i], arr[j]);
            }
        }
    }

    public static int f(int a, int b) {
        // implement your function here
        return a * b;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.