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:

  1. Take two integer values a and b.
  2. Create two pointers, p1 and p2, which point to a and b respectively.
  3. Swap the values at the memory locations pointed by p1 and p2.

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++

View on GeeksforGeeks
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]);
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.