Intersection of two Sorted Array


/***
find the intersection of two sorted array.
two solutions:
       1) two index and compare: complexity O(m+n)
       2) do BS through another array: complexity O(m*logn)
Choice based on the tuple size of array
***/

#include<iostream>
#include<vector>

using namespace std;

// time complexity: O(m+n)
vector<int> intersection(int *a, int *b, int asz, int bsz) {

       vector<int> intersect;
       int pa = 0, pb = 0;

       while(pa != asz && pb != bsz) {
              if(a[pa] == b[pb]) {
                     intersect.push_back(a[pa]);
                     pa++;
              }
              else if(a[pa] < b[pb]) pa++;
              else pb++;
       }
       return intersect;
}

// binary search: time complexity O(m*logn)
bool bs(int *in, int start, int end, int n) {
       if (start > end) return false;
      
       int mid = (start + end) / 2;
       if (in[mid] == n) return true;
       else if (in[mid] > n)
       {
              if (bs(in, start, mid-1, n)) return true;
       } else {
              if (bs(in, mid+1, end, n)) return true;
       }
       return false;
}

vector<int> intersection_b(int *a, int *b, int asz, int bsz) {
       vector<int> intersect;
       for(int i = 0; i<asz; i++) {
              if (bs(b, 0, bsz-1, a[i]))
                     intersect.push_back(a[i]);
       }
       return intersect;
}

void main() {
       int a1[] = {1, 3, 5, 6, 8};
       int a2[] = {2, 4, 6, 9};
       int sz1 = sizeof(a1) / sizeof(int);
       int sz2 = sizeof(a2) / sizeof(int);
       vector<int> insect, insect_b;

       insect = intersection(a1, a2, sz1, sz2);
       insect_b = intersection_b(a1, a2, sz1, sz2);

       if (!insect.empty() && !insect_b.empty())
       {
              for(int i = 0; i<insect.size(); i++) {
                     cout<<insect[i]<<"  ";
                     cout<<insect_b[i]<<endl;
              }
       }
}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs