Help in Hackerearth problem

Hi all,
I am trying to solve this hackerearth problem problem statement
I understood the editorial but I didn’t understood how complexity of editorial solution is O(n*m) Please help me with it and do suggest some other ways possible to solve the same problem.