Code Lab

Modo entrevista. Temporizador de 5 min, sin pistas y sin autocompletado

Swap two numbers without a third variable

FácilBasics5 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).

Ejemplos

swapPair([1, 2])

Devuelve [ 2, 1 ]

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

Devuelve [ 0, -5 ]

Compruébate

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

Preguntada en ServiceNow · Fuente

Cargando el editor…
  1. EntradaswapPair([ 1, 2 ])
    Esperado[ 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

Las pruebas ocultas se ejecutan al enviar