Find the Smallest Common Number - Coderust: Hacking the Coding Interview Log InJoin for free Ask a Question Find the Smallest Common NumberGiven three integer arrays sorted in ascending order, return the smallest number found in all three arrays. We'll cover the following Try it yourself#C++ Java Python JS Ruby Go #include <iostream> #include <vector> using namespace std; int FindLeastCommonNumber(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) { //TODO: Write - Your - Code return -1; } # Enter to Rename, Shift+Enter to Preview Test Need Hint? Save Reset Solution#
Let’s visualize the step by step implementation of the solution described above.
Created with Fabric.js 3.6.667102530636404567850161014Iterators pointing towards 0th index of all the arrays.But the values of arrays at 0th index are not the same. 1 of 8 Let’s take a look at the solution code below: C++ Java Python JS Ruby Go #include <iostream> #include <vector> #include <string> using namespace std; int FindLeastCommonNumber(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) { // Initialize starting indexes for arr1, arr2 and arr3 int i = 0, j = 0, k = 0; while (i < arr1.size() && j < arr2.size() && k < arr3.size()) { // Finding the smallest common number if ((arr1[i] == arr2[j]) && (arr2[j] == arr3[k])) return arr1[i]; // Let's increment the iterator // for the smallest value. if (arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) { i++; } else if (arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) { j++; } else if (arr3[k] <= arr1[i] && arr3[k] <= arr2[j]) { k++; } } return -1; } # Enter to Rename, Shift+Enter to Preview Run Save Reset Back Search a Rotated Array Next Rotate an Array by N Elements Mark as Completed Report an Issue |