878200. Swap Values using pointers
Easy
Swap Values using pointers
Summary
The problem is about swapping two values in C++ using pointers. The goal is to swap the values without using the built-in swap function or temporary variables.
Detailed Explanation
In this problem, we are given two integer values and asked to swap them without using any extra space. We can achieve this by using pointers in C++. This approach takes advantage of pointer arithmetic to swap the values.
Here's a step-by-step breakdown of the solution:
- Take two integer values
aandb. - Create two pointers,
p1andp2, which point toaandbrespectively. - Swap the values at the memory locations pointed by
p1andp2.
Here's an ASCII art diagram of the step:
a (int) | p1
---------
b (int) | p2
Swap:
b (int) | p1
---------
a (int) | p2
The time complexity of this solution is O(1), as it only involves swapping two values. The space complexity is also O(1), as we don't use any extra space.
Optimized Solutions
C++
public class Main {
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void main(String[] args) {
int[] arr = {5, 10};
System.out.println("Before swapping: a = " + arr[0] + ", b = " + arr[1]);
swap(arr, 0, 1);
System.out.println("After swapping: a = " + arr[0] + ", b = " + arr[1]);
}
}