Kth smallest in Sorted Array

/***
Given two sorted arrays A, B of size m and n respectively. Find the k-th smallest element in the union of A and B. You can assume that there are no duplicate elements.

Solution:
1) linear O(K) two index
***/

#include<iostream>
#include <algorithm>

using namespace std;


// time complexity: O(k), space: O(1)
int kth_smallest_linear(int *a, int *b, int asz, int bsz, int k) {
       int a_index = 0, b_index = 0;
       int num;

       //edge case - constant time
       if(asz == 0) return b[k-1];
       if(bsz == 0) return a[k-1];
       if(k == 0 && asz + bsz < k) return INT_MIN;
       if(asz + bsz == k) {
              if(a[asz-1] > b[bsz-1]) return a[asz-1];
              else return b[bsz-1];
       }     

       while(a_index != asz && b_index != bsz && k != 0) {
              if(a[a_index] < b[b_index]) {
                     num = a[a_index++];
              } else {
                     num = b[b_index++];
              }
              k--;
       }

       if(k == 0) return num;
       else {
              if(a_index == asz) return b[b_index+k-1];
              else return a[a_index+k-1];
       }
}

//time complexity: O(log(min(m, n, k))), space complexity: program stack memory O(n)
int kth_smallest_log(int *a, int *b, int asz, int bsz, int k) {

       //base case;
       if(asz == 0) return b[k-1];
       if(bsz == 0) return a[k-1];
       if(k == 1) return min(a[0], b[0]);
       if(asz + bsz == k) {
              if(a[asz-1] > b[bsz-1]) return a[asz-1];
              else return b[bsz-1];
       } else if (asz + bsz < k && k == 0) return INT_MIN;
       else {
              int subK = k/2;
              int asub, bsub;
              asub = min(subK, asz);
              bsub = min(subK, bsz);
              if(a[asub-1] < b[bsub-1]) {
                     return kth_smallest_log(a+asub, b, asz-asub, bsz, k-asub);
              } else {
                     return kth_smallest_log(a, b+bsub, asz, bsz-bsub, k-bsub);
              }
       }
}

void main() {
       int a[] = {1, 3, 6, 8, 11, 25};
       int b[] = {2, 3, 7, 9, 19};
       int asz = sizeof(a) / sizeof(int);
       int bsz = sizeof(b) / sizeof(int);

       cout<<kth_smallest_linear(a, b, asz, bsz, asz+bsz)<<endl;
       cout<<kth_smallest_log(a, b, asz, bsz, asz+bsz)<<endl;

}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs