clueless coding // TODO: be smarter

LeetCode Kill Process: CPP Solution



TL;DR Code Solution


vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {
    unordered_map<int, vector<int>> mapToChildren;

    for(int i = 0; i < pid.size(); i++) {
        if (mapToChildren.find(ppid[i]) != mapToChildren.end()) {
            mapToChildren[ppid[i]].push_back(pid[i]);
        }
        else {
            vector<int> parent = { pid[i] };
            mapToChildren[ppid[i]] = parent;
        }
    }

    stack<int> toBeProcessed;
    toBeProcessed.push(kill);

    vector<int> result;

    while (!toBeProcessed.empty()) {
        int current = toBeProcessed.top();
        toBeProcessed.pop();
        result.push_back(current);
        if (mapToChildren.find(current) != mapToChildren.end()) {
            for (int i = 0; i < mapToChildren[current].size(); i++) {
                toBeProcessed.push(mapToChildren[current][i]);
            }
        }
    }

    return result;


}