Problem · Bit Manipulation
Swap Two Numbers Without a Third Variable
Learn this problemProblem statement
Given two signed integers, first and second, swap their values without using a third variable to store either original value.
Return a two-element array containing the swapped values in the order [second, first]. The returned array is the output container; it is not a temporary variable for performing the swap.
Function
swapNumbers(first: int, second: int) → int[]Examples
Example 1
first = 5second = -2return = [-2,5]After the swap, first holds -2 and second holds 5, so the returned array is [-2, 5].
Example 2
first = 9second = 9return = [9,9]The two input values are equal, so swapping them leaves the ordered pair unchanged.
Constraints
-2^31 <= first <= 2^31 - 1-2^31 <= second <= 2^31 - 1- Do not use an additional variable to store either original value while performing the swap.
More infosys problems
- Count Valid A-B-C Sequences Under a Modulo-Four RuleOA · Seen Aug 2026
- Maximum Product of a Strictly Increasing Contiguous SubarrayOA · Seen Aug 2026
- Minimum Cost to Assign Candidates to Two CitiesOA · Seen Aug 2026
- Merge Two Sorted Arrays In PlaceONSITE INTERVIEW · Seen Jul 2026
- Minimum Coins for a TargetONSITE INTERVIEW · Seen Jul 2026
- Sort Sentence WordsONSITE INTERVIEW · Seen Jul 2026
- Minimum Path Sum With Grid SwitchesONSITE INTERVIEW · Seen May 2026
- Maximum Subarray Sum After SwapsOA · Seen Feb 2026