Grid Challenge (Hackerrank)

There's one thing i realized over the course of these months, given time and practice, you can become good at the things you thought you were not capable or smart enough to crack. 

I had flagged this question because i wasn't sure of how to code it and 3 days later i started with this question, all along playing with ideas and somehow, all the test cases passed. Remember kids, If you don't get it in first try, try again, if you fail...give some time and come back to it after some time. 

Question-

Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not.

Approach-

  • Sort the elements in the array
  • Create a bool function to check if element in column 1 is lesser than or greater than element in column 2
  • Implement the bool function over the array
  • Return YES or NO accordingly 
Code-

bool cmp(string a, string b) {
    for(int i = 0; i < a.size(); i++)
        if(a[i] < b[i])
            return true;
    return false;
}
string gridChallenge(vector<string> grid) {
    for(auto &s : grid)
        sort(s.begin(), s.end());
    if(is_sorted(grid.begin(), grid.end(), cmp))
        return "YES";
    else
        return "NO";
}


Popular posts from this blog

Finding the Subarrays (Hackerearth)

Missing Numbers (Hackerrank)

Find Missing Number (Amazon SDE)