Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding common minimum value between two arrays

I am working on a problem in Javascript. Finding common minimum value between two arrays. However, I have been told that this might not work on some values. What is the issue?

function cmp(a, b) { return a - b; }

function findMinimum(A, B) {
    var n = A.length;
    var m = B.length;
    A.sort(cmp);
    B.sort(cmp);
    var i = 0;
    for (var k = 0; k < n; k++) {
        if (i < m - 1 && B[i] < A[k])
            i += 1;
        if (A[k] == B[i])
            return A[k];
    }
    return -1;
}
like image 345
Vintage Avatar asked Oct 24 '25 06:10

Vintage


1 Answers

This should work. Just replace the first if with a while. The while loop loops through array B till it finds an element which is greater than the minimum element of A. Then the outer for loop loops through A to find any element that matches the current element of B or till it reaches an element that is greater than the current element of B, where the process repeats.

function cmp(a, b) {
  return a - b;
}

function findMinimum(A, B) {
  var n = A.length;
  var m = B.length;
  A.sort(cmp);
  B.sort(cmp);
  var i = 0;
  for (var k = 0; k < n; k++) {
    while (i < m - 1 && B[i] < A[k])
      i += 1;
    if (A[k] == B[i])
      return A[k];
  }
  return -1;
}

findMinimum([1,3,5,7], [0,0,1,4,9]);  // 1
findMinimum([3,5,7,9], [1,2,4,7,10]); // 7
like image 69
ripr Avatar answered Oct 26 '25 18:10

ripr