- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 55 lines of C++ from the credited upstream file 827.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int largestIsland(vector<vector<int>>& grid) {4 const int m = grid.size();5 const int n = grid[0].size();6 int maxSize = 0;7 8 vector<int> sizes{0, 0};9 10 11 12 13 for (int i = 0; i < m; ++i)14 for (int j = 0; j < n; ++j)15 if (grid[i][j] == 1)16 sizes.push_back(paint(grid, i, j, sizes.size())); 17 18 for (int i = 0; i < m; ++i)19 for (int j = 0; j < n; ++j)20 if (grid[i][j] == 0) {21 const unordered_set<int> neighborIds{22 getId(grid, i + 1, j), getId(grid, i - 1, j),23 getId(grid, i, j + 1), getId(grid, i, j - 1)};24 maxSize = max(maxSize, 1 + getSize(neighborIds, sizes));25 }26 27 return maxSize == 0 ? m * n : maxSize;28 }29 30 private:31 int paint(vector<vector<int>>& grid, int i, int j, int id) {32 if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())33 return 0;34 if (grid[i][j] != 1)35 return 0;36 grid[i][j] = id; 37 return 1 + paint(grid, i + 1, j, id) + paint(grid, i - 1, j, id) +38 paint(grid, i, j + 1, id) + paint(grid, i, j - 1, id);39 }40 41 42 int getId(const vector<vector<int>>& grid, int i, int j) {43 if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size())44 return 0; 45 return grid[i][j];46 }47 48 int getSize(const unordered_set<int>& neighborIds, const vector<int>& sizes) {49 int size = 0;50 for (const int neighborId : neighborIds)51 size += sizes[neighborId];52 return size;53 }54};55