I am just working on Flatland Space Stations problem, and it is not seeming to be a tough question, but my algorithm lags in some aspects, since it solves majority of the test cases but fails for some. Which is causing me not to move forward.
The cause of the failure is timeout only, no wrong output.
My Algo:
- To loop through the number of cities
- Loop through the cities which has the space stations
- Store the minimum distance in the array or dict for that particular city
- Find out the maximum distance stores in the array of difference between n cities
I have written two codes based upon the following Algo:
1. With the use of Dictionary: Time out for three cases
def flatlandSpaceStations(n, c):
# n is the number of cities
# c is the array of space station exists in the city(s)
cityDiff = {}
maxDiff = 0
if n == len(c):
return 0
else:
for i in range(n):
lst = []
for j in c:
lst.append(abs(i-j))
cityDiff[i] = min(lst)
for key, value in cityDiff.items():
if value > maxDiff: maxDiff = value
return maxDiff
2. Using lists in Python: Failed two cases in Timeout only
def flatlandSpaceStations(n, c):
# n is the number of cities
# c is the array of space station exists in the city(s)
maxDiff = []
if n == len(c):
return 0
else:
for i in range(n):
minDis = []
for j in c:
minDis.append(abs(i-j))
maxDiff.append(min(minDis))
return max(maxDiff)
I want to find some optimum solution, which I can understand. The above programs have a very bad time complexity I know, but this is only solution I can think of right now. Any help would be appreciated.
As per vnp's suggestion, I have made another attempt, and made the solution optimized, but it is not working out for the Two test cases due to timeout issue.
Solution \$O(n^2)\$:
def flatlandSpaceStations(n, c):
# n is the number of cities
# c is the array of space station exists in the city(s)
maxDiff = []
if n == len(c):
return 0
else:
for i in range(n):
minVal = float('inf')
for j in c:
if abs(i-j) < minVal: minVal = abs(i-j)
maxDiff.append(minVal)
return max(maxDiff)
I am attaching one of the two time out failure test case here for more insight.