Hackerland Radio Transmitters

  • + 0 comments

    Python 3 with greedy algorithm: O(n) time and space complexity.

    from collections import defaultdict
    def hackerlandRadioTransmitters(x, k):
        # Write your code here
        is_house = defaultdict(bool)
        last_house = 0
        first_house = float('inf')
        for house in x:
            is_house[house] = True
            last_house = max(last_house, house)
            first_house = min(first_house, house)
        curr = first_house
        ans = 0
        while curr <= last_house:
            transmitter_here = curr
            for cand in range(curr, curr+k+1):
                if is_house[cand]:
                    transmitter_here = cand
            ans += 1
            curr = transmitter_here + k + 1
            while curr <= last_house and not is_house[curr]:
                curr += 1
        return ans