875836. Two Swaps

Easy

Two Swaps

Summary

The Two Swaps problem involves given an array of integers and a target sum. The goal is to find two elements in the array that add up to the target sum by performing at most two swaps.

Detailed Explanation

To solve this problem, we can start by sorting the array in ascending order. This will ensure that adjacent elements are either equal or have a difference of 1. Then, we iterate through the sorted array and check for pairs of elements that add up to the target sum. If such a pair is found, we return their indices as the solution.

Here's a step-by-step breakdown:

  1. Sort the given array in ascending order.
  2. Initialize two pointers, i and j, to the start and end of the array respectively.
  3. Iterate through the array until i meets or crosses j.
  4. Check if the sum of the elements at indices i and j equals the target sum.
  5. If a pair is found that adds up to the target sum, return their indices as the solution.

Time Complexity: O(n log n) due to sorting Space Complexity: O(1) since we only use a constant amount of space

Optimized Solutions

Java

View on GeeksforGeeks
public class TwoSwaps {
    public static int[] findTwoSwaps(int[] arr, int targetSum) {
        Arrays.sort(arr);
        int i = 0;
        int j = arr.length - 1;
        while (i < j) {
            int sum = arr[i] + arr[j];
            if (sum == targetSum) {
                return new int[]{i, j};
            } else if (sum < targetSum) {
                i++;
            } else {
                j--;
            }
        }
        return null;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.