703141. A guy with a mental problem

Basic

A Guy with a Mental Problem

Summary

This problem is about finding all the positions where a given array has a pair of elements that sum up to a target value. The key concept involved here is arrays and data structures.

Detailed Explanation

The problem statement can be interpreted as follows: Given an array arr[] and an integer k, find all indices (i, j) such that arr[i] + arr[j] = k. This problem is a classic example of a two-pointer technique commonly used in array problems. The idea is to sort the array first, then initialize two pointers, one at the start and one at the end of the sorted array. We keep moving the pointers towards each other until we find a pair that sums up to k. If we don't find such a pair, it means there are no such indices in the array.

Here is the step-by-step breakdown of the solution:

  1. Sort the given array arr[] in ascending order.
  2. Initialize two pointers, left and right, at the start and end of the sorted array respectively.
  3. While left < right:
    • Calculate the sum of elements at indices left and right.
    • If the calculated sum is equal to k, then we have found a pair that sums up to k. Print or store these indices (i, j) where arr[i] + arr[j] = k.
    • If the calculated sum is less than k, increment left (move the left pointer towards the right).
    • If the calculated sum is greater than k, decrement right (move the right pointer towards the left).
  4. Return or print all found indices.

Time complexity: O(n log n) due to sorting, where n is the size of the array. Space complexity: O(1), as we are not using any extra space that scales with the input size.

Optimized Solutions

Here are the optimized solutions in Java, Python, C++, and JavaScript:

Java

View on GeeksforGeeks
import java.util.Arrays;

public class Solution {
    public static void findPairs(int[] arr, int k) {
        Arrays.sort(arr);
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int sum = arr[left] + arr[right];
            if (sum == k) {
                System.out.println("Pair found at indices " + left + " and " + right);
                left++;
                right--;
            } else if (sum < k) {
                left++;
            } else {
                right--;
            }
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.