Skip to content

Avoid Obstacles

You are given an array of integers representing coordinates of obstacles situated on a straight line.

Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.

Find the minimal length of the jump enough to avoid all the obstacles.

Example

For inputArray = [5, 3, 6, 7, 9], the output should be

avoid_obstacles(inputArray) = 4

Check out the image below for better understanding:

Image Credit: CodeSignal

Solution

py
def avoid_obstacles(inputArray):
    inputArray.sort()
    jump = 0
    for i in range(2, max(inputArray) + 2):
        found = False
        for j in inputArray:
            if j % i == 0:
                found = True
                break
        if not found:
            jump = i
            break
    return jump


print(avoid_obstacles([1000, 999]))
js
function avoidObstacles(inputArray) {
  let i = 1;
  while (inputArray.some((n) => n % i === 0)) {
    i++;
  }
  return i;
}

console.log(avoidObstacles([1000, 999]));

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