717670. Two Swaps

Easy

Two Swaps

Summary

Given an array of integers, we need to swap exactly two elements such that the resulting array is sorted in ascending order. This problem involves manipulating arrays and data structures.

Detailed Explanation

The given array can be sorted by swapping any two elements, but only if they are out of order. We will start from the beginning of the array and iterate through it until we find a pair of elements that are not in ascending order. Once found, we will swap these two elements and continue our iteration.

Here's a step-by-step breakdown:

  1. Initialize two pointers, i and j, to the first element of the array.
  2. Compare the elements at indices i and j. If they are not in ascending order (i.e., arr[j] < arr[i]), then we have found a pair that needs to be swapped.
  3. Swap the elements at indices i and j.
  4. Increment i by 1, as we have already processed the current element.
  5. Repeat steps 2-4 until i reaches the end of the array.

This algorithm ensures that the array is sorted in ascending order after exactly two swaps. The time complexity of this algorithm is O(n), where n is the size of the input array. The space complexity is O(1), as we only use a constant amount of space to store our pointers and variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] twoSwaps(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i] > arr[i + 1]) {
            swap(arr, i, i + 1);
        }
    }
    return arr;
}

private void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

DevExCode

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

© 2026 DevExCode. All rights reserved.