Skip to content

Array Replace

Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.

Example

For inputArray = [1, 2, 1], elemToReplace = 1, and substitutionElem = 3, the output should be

array_replace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3]

Solution

py
def array_replace(input_array, element_to_replace, substitution_element):
    return [substitution_element if x == element_to_replace else x for x in input_array]


print(
    array_replace(
        [1, 2, 1], 1, 3
    )
)
js
function array_replace(inputArray, elemToReplace, substitutionElem) {
  return inputArray.map((element) => {
    if (element === elemToReplace) {
      return substitutionElem;
    }
    return element;
  });
}

console.log(array_replace([1, 2, 1], 1, 3));

my thoughts are neither my employer's nor my wife's