Skip to content

← Back to Overview

Swap Two Numbers (Without Temporary Variable)

Learning Objectives

By the end of this tutorial, you will be able to: - Understand arithmetic swapping techniques without temporary variables - Master bitwise XOR swapping method for optimization - Analyze memory optimization benefits and trade-offs - Apply optimization techniques in real-world programming scenarios - Compare different swapping approaches and their performance - Identify potential overflow issues and solutions


Concept Explanation

What is it?

Swapping two numbers without using a third temporary variable is an optimization technique that reduces memory usage. This is typically achieved using arithmetic operations (addition and subtraction) or bitwise XOR operations.

Why is it important?

While memory is abundant in modern systems, avoiding temporary variables can be beneficial in highly optimized or memory-constrained environments. It also demonstrates a deeper understanding of mathematical properties or bitwise operations.

Where is it used?

  • Optimized Algorithms: In competitive programming or scenarios where every byte counts.
  • Embedded Systems: Where RAM is severely limited.
  • Interview Questions: A classic question to test a candidate's problem-solving skills and understanding of fundamental operations.

Real-world example

Imagine two water tanks. You want to exchange the water between them without using a third container. You could pour the first tank's water into the second, making it overflow. Then, you mark the level of the first tank's original volume in the second tank, empty the first tank, pour the water from the second tank up to the mark into the first, and finally pour the remaining water from the second tank into the now empty first tank. (This analogy is a bit stretched but illustrates the idea of using existing "space" creatively).


Algorithm (using Arithmetic Operations)

  1. Start.
  2. Get two numbers, num1 and num2, from the user.
  3. Add num1 and num2, store the result in num1 (num1 = num1 + num2).
  4. Subtract num2 from the new num1, store the result in num2 (num2 = num1 - num2). (Now num2 holds the original value of num1).
  5. Subtract the new num2 (which is original num1) from the new num1 (which is original_num1 + original_num2), store the result in num1 (num1 = num1 - num2). (Now num1 holds the original value of num2).
  6. Display the swapped values of num1 and num2.
  7. End.

Edge Cases: - Inputting non-numeric values (handled by language-specific error mechanisms or explicit validation). - Potential for overflow if the sum of num1 and num2 exceeds the maximum value of the data type (especially with arithmetic operations). This is less of an issue with modern arbitrary-precision integers in Python or double in Java/C.


Implementations

import java.util.Scanner;

public class SwapNumbersWithoutTemp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first number (num1): ");
        int num1 = scanner.nextInt();

        System.out.print("Enter the second number (num2): ");
        int num2 = scanner.nextInt();

        System.out.println("Before swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);

        // Swapping logic using arithmetic operations
        // Example: num1 = 5, num2 = 10
        num1 = num1 + num2; // num1 becomes 15 (5 + 10)
        num2 = num1 - num2; // num2 becomes 5 (15 - 10)
        num1 = num1 - num2; // num1 becomes 10 (15 - 5)

        System.out.println("\nAfter swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);

        scanner.close();
    }
}
# Get two numbers from the user
num1_str = input("Enter the first number (num1): ")
num1 = float(num1_str)

num2_str = input("Enter the second number (num2): ")
num2 = float(num2_str)

print(f"Before swapping (Arithmetic):")
print(f"num1 = {num1}")
print(f"num2 = {num2}")

# Swapping logic using arithmetic operations
# Example: num1 = 5, num2 = 10
num1 = num1 + num2 # num1 becomes 15 (5 + 10)
num2 = num1 - num2 # num2 becomes 5 (15 - 10)
num1 = num1 - num2 # num1 becomes 10 (15 - 5)

print(f"\nAfter swapping (Arithmetic):")
print(f"num1 = {num1}")
print(f"num2 = {num2}")

print("\n--- Pythonic Swap (Tuple Assignment) ---")
num1_py_str = input("\nEnter the first number (Pythonic swap): ")
num1_py = float(num1_py_str)

num2_py_str = input("Enter the second number (Pythonic swap): ")
num2_py = float(num2_py_str)

print(f"Before swapping (Pythonic):")
print(f"num1_py = {num1_py}")
print(f"num2_py = {num2_py}")

# Swapping logic using tuple assignment
num1_py, num2_py = num2_py, num1_py

print(f"\nAfter swapping (Pythonic):")
print(f"num1_py = {num1_py}")
print(f"num2_py = {num2_py}")
#include <stdio.h>

int main() {
    int num1, num2;

    printf("Enter the first number (num1): ");
    scanf("%d", &num1);

    printf("Enter the second number (num2): ");
    scanf("%d", &num2);

    printf("Before swapping:\n");
    printf("num1 = %d\n", num1);
    printf("num2 = %d\n", num2);

    // Swapping logic
    num1 = num1 + num2; // num1 becomes 15 (5 + 10)
    num2 = num1 - num2; // num2 becomes 5 (15 - 10)
    num1 = num1 - num2; // num1 becomes 10 (15 - 5)

    printf("\nAfter swapping:\n");
    printf("num1 = %d\n", num1);
    printf("num2 = %d\n", num2);

    return 0;
}
SET SERVEROUTPUT ON;
DECLARE
  num1        NUMBER := &Enter_First_Number;
  num2        NUMBER := &Enter_Second_Number;
BEGIN
  DBMS_OUTPUT.PUT_LINE('Before swapping:');
  DBMS_OUTPUT.PUT_LINE('Num1: ' || num1);
  DBMS_OUTPUT.PUT_LINE('Num2: ' || num2);

  -- Swapping logic using arithmetic operations
  num1 := num1 + num2;
  num2 := num1 - num2;
  num1 := num1 - num2;

  DBMS_OUTPUT.PUT_LINE('After swapping:');
  DBMS_OUTPUT.PUT_LINE('Num1: ' || num1);
  DBMS_OUTPUT.PUT_LINE('Num2: ' || num2);
END;
/

Explanation

  • Java: Achieves swapping using arithmetic operations (+, -) without an auxiliary variable. This approach can lead to overflow if the sum of numbers exceeds Integer.MAX_VALUE.
  • Python: Can swap using arithmetic operations similar to C/Java, but also provides a more "Pythonic" and safer way using tuple assignment (num1, num2 = num2, num1), which handles values internally without needing a temporary variable or risking overflow from intermediate sums.
  • C: Swapping via arithmetic operations. This method is susceptible to integer overflow if num1 + num2 exceeds the maximum value an int can hold.
  • Oracle: Swapping is done in PL/SQL using arithmetic operations. Similar to C/Java, this method is also prone to overflow with large NUMBER values, though Oracle's NUMBER type has very high precision.

Complexity Analysis

  • Time Complexity: O(1) - Constant number of arithmetic operations.
  • Space Complexity: O(1) - No additional variables are used for swapping itself (apart from the original two).

Flowchart

graph TD
    A[Start] --> B[Get num1]
    B --> C[Get num2]
    C --> D[num1 = num1 + num2]
    D --> E[num2 = num1 - num2]
    E --> F[num1 = num1 - num2]
    F --> G[Display num1, num2]
    G --> H[End]

Sample Dry Run

Step num1 num2 Description
Initial 5 10 Variables initialized
num1 = num1 + num2 15 10 num1 becomes 5 + 10 = 15
num2 = num1 - num2 15 5 num2 becomes 15 - 10 = 5 (original num1)
num1 = num1 - num2 10 5 num1 becomes 15 - 5 = 10 (original num2)
Final 10 5 Values are swapped

Practice Problems

Easy

  • Implement swapping using the bitwise XOR operator in C/Java.
  • Discuss the pros and cons of swapping with vs. without a temporary variable.

Medium

  • Write a program that swaps two adjacent elements in an array without using a temporary variable.
  • Handle potential overflow issues for the arithmetic swap method by using larger data types or appropriate error handling.

Hard

  • Implement a function/method that reverses an array or list in-place (without creating a new one) using a swap function without a temporary variable.

Interactive Elements

Try It Yourself

Quick Test

  1. What will be the output if we swap 7 and 12 using arithmetic operations?
  2. Compare performance between temporary variable and arithmetic swapping
  3. Implement XOR swapping and verify it works with different data types

Code Challenge

Write a program that: - Implements all three swapping methods (temp variable, arithmetic, XOR) - Measures execution time for each method - Handles overflow scenarios gracefully - Provides performance comparison results


Learning Path

Before This Tutorial

After This Tutorial


Interview Tips

  • Explain the Logic: Clearly describe how arithmetic operations achieve swapping without extra space
  • Mention Complexity: State that it's O(1) time and O(1) space, but note potential overflow risks
  • Discuss Trade-offs: Compare memory savings vs. potential overflow issues
  • Real-world Applications: Mention embedded systems and competitive programming
  • Alternative Methods: Discuss bitwise XOR swapping as another optimization technique

Best Practices & Common Mistakes

General Programming Principles

Language-Specific Guidance

Concept-Specific Considerations


  • Arithmetic Operations: Addition and subtraction for value manipulation
  • Bitwise Operations: XOR swapping as an alternative method
  • Memory Optimization: Techniques to reduce memory usage
  • Integer Overflow: Understanding limitations of arithmetic operations
  • Algorithm Efficiency: Space vs. time complexity trade-offs
  • Competitive Programming: Where optimization techniques are crucial
  • Embedded Systems: Memory-constrained environments

"Any sufficiently advanced technology is indistinguishable from magic." - Arthur C. Clarke