FastPrepClosest Vehicle and Charger in a Line

Closest Vehicle and Charger in a Line

Spotify logoSpotify● EasyFULLTIMEPHONE SCREEN

Problem statement

A line of cells is given as an array cells. Each value means:

  • 0: an empty cell
  • 1: a vehicle
  • 2: a charger

The distance between two cells is the absolute difference of their indices. Return the smallest distance between any vehicle and any charger. If the line has no vehicle or no charger, return -1.

Function

closestVehicleChargerDistance(cells: int[]) → int

Examples

Example 1

cells = [0,1,0,0,2,0,1]return = 2

The vehicles are at indices 1 and 6, and the charger is at index 4. The distances are 3 and 2, so the answer is 2, from the vehicle at index 6.

Example 2

cells = [2,1]return = 1

The charger at index 0 and the vehicle at index 1 are next to each other.

Example 3

cells = [1,0,1]return = -1

The line has vehicles but no charger, so the answer is -1.

Constraints

  • 1 <= cells.length <= 10^5
  • 0 <= cells[i] <= 2

More Spotify problems

See Spotify hiring insights
Saved
public int closestVehicleChargerDistance(int[] cells) {
    // Write your code here.
}
Checking account…