Code Lab

Swap two numbers without a third variable

EasyBasics5 min

Write a function swapPair(pair) that swaps two numbers without a third variable.

A function cannot change the variables of the code that called it, so the two numbers come in an array: pair is [a, b].

  • Change pair itself so that it becomes [b, a], then return that same array, not a new one.
  • a and b are integers from -1000000000000 to 1000000000000. They can be negative, zero or equal.
  • No third variable: inside the function do not write let, const or var, do not add a second parameter, and do not write another function in it (its parameters would be variables too).
  • Keep values only in the two items of pair: do not add items or properties to the array or to the function, and do not create a global variable (temp = pair[0] without let creates one).

Examples

swapPair([1, 2])

Returns [ 2, 1 ]

The result is the same array that was passed in, now changed.
swapPair([-5, 0])

Returns [ 0, -5 ]

Check yourself

  • No helper variable outside the function either: only the two items of the array are used.

Asked at ServiceNow · Source

Loading the editor...
  1. InputswapPair([ 1, 2 ])
    Expected[ 2, 1 ]
  2. Returns the same array, now swapped
  3. No let, const or var inside the function
  4. swapPair has only one parameter
  5. No global variable is created

Hidden tests run on Submit.