
Problem
Solution
Submissions
Swap Two Variables Without a Temporary Variable
Certification: Basic Level
Accuracy: 78.26%
Submissions: 184
Points: 5
Write a Python program that swaps the values of two variables without using a temporary variable.
Example 1
- Input: a = 5, b = 10
- Output: a = 10, b = 5
- Explanation:
- Step 1: Add the values of both variables: a = a + b = 5 + 10 = 15.
- Step 2: Set b equal to a minus b: b = a - b = 15 - 10 = 5.
- Step 3: Set a equal to a minus b: a = a - b = 15 - 5 = 10.
- Step 4: Now, a = 10 and b = 5, successfully swapped without using a temporary variable.
Example 2
- Input: a = "hello", b = "world"
- Output: a = "world", b = "hello"
- Explanation:
- Step 1: Using Python's multiple assignment feature: a, b = b, a.
- Step 2: This assigns b's value ("world") to a, and a's value ("hello") to b simultaneously.
- Step 3: Now, a = "world" and b = "hello", successfully swapped without a temporary variable.
Constraints
- -10^6 ≤ integer values ≤ 10^6
- 1 ≤ len(string) ≤ 100 characters
- Time Complexity: O(1)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use arithmetic operations (for numbers): a = a + b; b = a - b; a = a - b
- Use XOR operation (for integers): a = a ^ b; b = a ^ b; a = a ^ b
- Use tuple unpacking: a, b = b, a
- Use array/list assignment: [a, b] = [b, a]