Python O(NlogN) using heap
Fill the 0s from left to right. For each 0, it can only be filled from values to the left nonzero values. For each of the non-zero values to the left of current
Fill the 0s from left to right. For each 0, it can only be filled from values to the left nonzero values. For each of the non-zero values to the left of current 0 use heap to maintain the next occurrence of the same value (greedily pick the next earliest occurrence). If the next occurrence occurs before the current 0 position then we cannot avoid a flood else we fill the zero with the value.\n\n```\nclass Solution(object):\n    def avoidFlood(self, rains):\n        positions = {}\n        \n        for i in range(len(rains)):\n            if rains[i] not in positions:\n                positions[rains[i]] = collections.deque([])\n            positions[rains[i]].append(i)\n            \n        heap, out = [], [-1]*len(rains)\n        \n        for i in range(len(rains)):\n            if rains[i] == 0:\n                if len(heap) > 0:\n                    x, y = heapq.heappop(heap)\n                    if x > i:\n                        out[i] = y\n                    else:\n                        return []\n            else:\n                if len(positions[rains[i]]) > 1:\n                    positions[rains[i]].popleft()\n                    j = positions[rains[i]][0]\n                    heapq.heappush(heap, (j, rains[i]))\n                    \n        if len(heap) > 0:\n            return []\n        \n        for i in range(len(out)):\n            if rains[i] == 0 and out[i] == -1:\n                out[i] = 1\n                \n        return out
[]