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:
- Initialize two pointers,
iandj, to the start and end of the array, respectively. - Compare the elements at indices
iandj. Ifiis less than or equal toj, incrementi. - If
iis greater thanj, decrementj. - Once
iequalsj, swap the elements at those positions (since we've found the target indices). - Continue iterating through the array, updating
iandjas 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
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;
}