Google Interview Question for SDE1s

Country: United States

Comment hidden because of low score. Click to expand.
of 1 vote

Sort n+m list and keep their [i,j] as auxililary info. pick from the smallest number among the sorted n+m number list. Each consecutive pick must satisfy (i <= i_prev && j <= j_prev) || (i >= i_prev && j >= j_prev).

- Aaron December 27, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
of 0 vote

Easy DP could be O(n*m*(n+m)).
Greedy algorithm is iteratively choosing minimum from rest values, then check if it is valid in previous selected path by comparing its coordinate with previous coordinate and next coordinate in path. O(n*m*log(n+m))

struct Node{
    int val;
    int x;
    int y;
int cmp(Node &a, Node &b){
    return  a.val < b.val;
vector<int> get_ans(vector<vector<int>> &grid){
    int n = grid.size();
    int m = grid[0].size();
    vector<Node> vec(n * m - 2);
    int site = 0;
    for (int i = 0; i < n; ++i){
        for (int j = 0; j < m; ++j){
            if ((i == 0 && j == 0) || (i == n-1 && j == m-1)){
            vec[site].val = grid[i][j];
            vec[site].x = i;
            vec[site].y = j;
    sort(vec.begin(), vec.end(), cmp);
    map<pair<int,int>, int> mp;
    mp[make_pair(0,0)] = grid[0][0];
    mp[make_pair(n-1,m-1)] = grid[n-1][m-1];
    for (int i = 0; i < vec.size(); ++i){
        pair<int, int> p = make_pair(vec[i].x, vec[i].y);
        cout << p.first << ", " << p.second << endl;
        auto it = mp.upper_bound(p);
        if (it != mp.end() && (vec[i].x > it->first.first || vec[i].y > it->first.second)){
        if (it != mp.end() && (vec[i].x < it->first.first || vec[i].y < it->first.second)){
        cout << "pass" << endl;
        mp[p] = vec[i].val;
    vector<int> ans;
    for (auto it = mp.begin(); it != mp.end(); ++it){
    sort(ans.begin(), ans.end());
    return ans;

- lxfuhuo December 31, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.

Add a Comment

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.


is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More


CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More