Problem solving with programming: Common elements between two sorted arrays
Given two sorted arrays, how do you efficiently find the common elements between those two?
Given two sorted arrays, how do you efficiently find the common elements between those two?
void printIntersect(vector<int>& s1, vector<int>& s2) { //i and j start 0 i.e first element int i = 0 , j= 0; //while either of the two indices reaches end while ( i < s1.size() && j < s2.size() ) { //if first array element is lesser, advance that index by one if( s1[i] < s2[j] ) { i++; } //otherwise advance second index else if( s1[i] > s2[j] ) { j++; } //both elements are same, print it, and advance both the pointers else { cout<<s1[i]<<" "; i++; j++; } }Read full article from Problem solving with programming: Common elements between two sorted arrays