educative.io

Educative

Suggest improvement in C++ solution

I think this solution is slightly better as it reduces the number of iterations of the while loop. Rather than only increasing 1 pointer, it will at most increase 2 pointers in each iteration.

int find_least_common_number(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) {
  int i=0,j=0,k=0;
  while(i<arr1.size() && j<arr2.size() && k<arr3.size()){
    if(arr1[i] == arr2[j] && arr2[j] == arr3[k]){
      return arr1[i];
    }
    int maximum = arr1[i];
    if(arr2[j] > maximum) maximum = arr2[j];
    if(arr3[k] > maximum) maximum = arr3[k];
    if(maximum > arr1[i]) i++;
    if(maximum > arr2[j]) j++;
    if(maximum > arr3[k]) k++;
  }
  return -1;
}

Hi, @Kanak_Agrawal

You’re absolutely correct. As you mentioned, this solution of yours is slightly better since now 2 iterators can be incremented together, rather than a single one, which was the case in the solution given in the lesson.