Skip to content

Instantly share code, notes, and snippets.

@Shaddyjr
Created May 12, 2023 02:03
Show Gist options
  • Save Shaddyjr/483740869337f8d2dcff5c44550bcaf4 to your computer and use it in GitHub Desktop.
Save Shaddyjr/483740869337f8d2dcff5c44550bcaf4 to your computer and use it in GitHub Desktop.
// Source: https://www.hackerrank.com/challenges/flatland-space-stations/problem
// video: https://youtu.be/zCCz59gT9Rs
// Complete the flatlandSpaceStations function below.
function flatlandSpaceStations(n, c) {
// c = cities with space stations is NOT ordered
c.sort((a,b) => a - b) // O(clogc)
let maxDist = 0
let lastCity = 0
// consider very first city
const firstCityDist = c[0]
maxDist = Math.max(firstCityDist, maxDist)
// going left to right, assume midpoint distance for max
for (const city of c){ // O(c)
const midCityDist = Math.floor((city - lastCity) / 2)
maxDist = Math.max(midCityDist, maxDist)
lastCity = city
}
// consider very last city
const lastCityDist = n - lastCity - 1
maxDist = Math.max(lastCityDist, maxDist)
return maxDist
// Time complexity: O(clogc) + O(c) = O(clogc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment