878682. Swap The Numbers

School

Swap The Numbers

Summary

The "Swap The Numbers" problem involves swapping two specific numbers in an array. Given a sorted array and two indices, you need to swap the elements at those positions while maintaining the array's sorted order.

Detailed Explanation

To solve this problem, we'll use a simple algorithm that takes advantage of the fact that the array is already sorted. We'll iterate through the array, comparing each pair of adjacent elements until we find the target indices. Once found, we'll swap the elements and continue iterating to ensure the rest of the array remains sorted.

Here's a step-by-step breakdown:

  1. Initialize two pointers, i and j, to the start and end of the array, respectively.
  2. Compare the elements at indices i and j. If i is less than or equal to j, increment i.
  3. If i is greater than j, decrement j.
  4. Once i equals j, swap the elements at those positions (since we've found the target indices).
  5. Continue iterating through the array, updating i and j as needed to maintain the sorted order.

Time complexity: O(n), where n is the length of the array. Space complexity: O(1), since we're not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public void swap(int[] arr, int i, int j) {
    while (i <= j) {
        if (arr[i] <= arr[j]) {
            i++;
        } else {
            j--;
        }
    }
    // Now i == j, so we can swap the elements
    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.