Swap two numbers without a third variable
Coding problemEasyAsked in: Accenture, Capgemini, Infosys, TCS
Given two integers a and b, swap them and return the pair as a list: the new a first, then the new b.
The interview rule: swap the two values without using a third variable to hold one of them. The tests check the result; keeping the rule is up to you, as it is in the interview.
Examples
Example 1
Input: a = 3, b = 5
Output: [5,3]
Example 2
Input: a = -1, b = 1
Output: [1,-1]
Example 3
Input: a = 4, b = 4
Output: [4,4]
Constraints
- a and b are between -2,147,483,648 and 2,147,483,647
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.