Google Interview Question
Software EngineersCountry: United States
O(m * n) time.
The follow up question is similar to the CareerCup site question having id=5121790555717632 (would be cool to allow links to the website itself).
#include <iostream>
#include <vector>
using namespace std;
bool Valid(vector<vector<char>> const &m)
{
for (int r = 0; r < m.size(); ++r) {
for (int c = 0; c < m[r].size(); ++c) {
int dups = 0;
if (r > 0 &&
m[r - 1][c] == m[r][c])
{
++dups;
}
if (r > 1 &&
m[r - 2][c] == m[r][c])
{
++dups;
}
if (dups > 1) {
return false;
}
dups = 0;
if (c > 0 &&
m[r][c - 1] == m[r][c])
{
++dups;
}
if (c > 1 &&
m[r][c - 2] == m[r][c])
{
++dups;
}
if (dups > 1) {
return false;
}
}
}
return true;
}
int main()
{
vector<vector<char>> m = {
{'R', 'G', 'R', 'B'},
{'R', 'Y', 'G', 'R'},
{'G', 'B', 'Y', 'Y'},
{'Y', 'G', 'B', 'G'},
{'B', 'R', 'Y', 'B'},
};
cout << Valid(m) << "\n";
}
- funcoolgeek December 15, 2017