Full explanation with comments | C++ Solution (Iterative) |  space optimized - O(n) space
\nclass Solution {\npublic:\n    vector<int> findBall(vector<vector<int>>& grid) \n    {\n        int n = grid.size(), m = grid[0].size();\n        \n        if
```\nclass Solution {\npublic:\n    vector<int> findBall(vector<vector<int>>& grid) \n    {\n        int n = grid.size(), m = grid[0].size();\n        \n        if (m==1)\n            return {-1};\n        \n        // 2 vectors to store position of balls (b0,b1,b2...)\n        // index in both represents the column number in that particular row\n        // value in both represents the ball numer that has managed to rach that column \n        // curr - to store the current position of ball number\n        // next - to calculate next position of ball number\n        vector<int> curr(m,-1),next(m,-1);\n        \n        // currently each ball starts at it\'s index\n        for (int i=0; i<m; i++)\n        {\n            curr[i]=i;\n        }\n        \n        // iterate through each row and each time calculate the next values based on the current values \n        for (int i=0; i<n; i++)\n        {\n            // if we get 2 consecutive 1, ball will go right side (increase it\'s index in next)\n            // if we get 2 consecutive -1, ball will go left side (decrease it\'s index in next)\n            \n            // check for first 2 columns\n            if (grid[i][0]==1 && grid[i][1]==1)\n            {\n                next[1]=curr[0];\n            }\n            \n            if (grid[i][0]==-1 && grid[i][1]==-1)\n            {\n                next[0]=curr[1];\n            }\n            \n            // check for rest of the colums\n            for (int j=1; j<m-1; j++)\n            {\n                if (grid[i][j]==1 && grid[i][j+1]==1)\n                {\n                    next[j+1]=curr[j];\n                }\n                \n                if (grid[i][j]==-1 && grid[i][j+1]==-1)\n                {\n                    next[j]=curr[j+1];\n                }\n            }\n            \n            // curr will become next for next row\n            curr = next;\n            \n            // for last row, we have next vector containing ball numbers (value) in the respective columns (index)\n            if (i==n-1)\n                break;\n            \n            // initialise next to -1 again \n            for (int i=0; i<m; i++)\n            {\n                next[i]=-1;\n            }\n        }\n        \n        // we need to return vector having whose value represents column and index represents the ball number\n        vector <int> ans (m,-1);\n        \n        for (int i=0; i<m; i++)\n        {\n            if (next[i]!=-1)\n                ans[next[i]]=i;\n        }\n        return ans;\n    }\n};\n```\n\nI hope it helped... please upvote if it did :)
['Dynamic Programming', 'C', 'Iterator', 'C++']