Leetcode 1612 Solution

This article provides solution to leetcode question 1612 (avoid-flood-in-the-city)

https://leetcode.com/problems/avoid-flood-in-the-city

Solution

class Solution {
public:
    vector<int> avoidFlood(vector<int>& rains) {
        int n = rains.size();
        vector<int> res(n, -1);

        unordered_map<int, int> m;
        set<int> s;

        for (int i = 0; i < rains.size(); i ++)
        {
            int rain = rains[i];

            if (rain == 0)
                s.insert(i);
            else
            {
                if (m.find(rain) != m.end())
                {
                    int j = m[rain];
                    auto it = s.upper_bound(j);

                    if (it == s.end())
                        return vector<int>();

                    res[*it] = rain;

                    s.erase(it);
                }

                m[rain] = i;
            }
        }

        for (auto it = s.begin(); it != s.end(); it++)
            res[*it] = 1;

        return res;
    }
};