Skip to content

Instantly share code, notes, and snippets.

@jsmith
Last active February 11, 2020 22:49
Show Gist options
  • Save jsmith/420cf16a6d15f19b315a980c1fbfa5da to your computer and use it in GitHub Desktop.
Save jsmith/420cf16a6d15f19b315a980c1fbfa5da to your computer and use it in GitHub Desktop.
function kSmallest(A, B, k) {
// bounds are inclusive so we are subtracting 1
// we also subtract 1 from k due to 0 based indexing
return helper(A, B, k - 1, 0, A.length - 1, 0, B.length - 1);
}
function helper(A, B, k, s1, e1, s2, e2) {
// Base case:
// If one of the arrays is empty, then it's obviously the kth element of the
// other array.
if (s1 > e1) { return B[s2 + k] }
else if (s2 > e2) { return A[s1 + k] }
const m1 = (s1 + e1) / 2;
const m2 = (s2 + e2) / 2;
if ((m1 - s1) + (m2 - s2) < k) {
// If k is greater than both of the middle values, then we KNOW that k
// falls into one of the second halves of the arrays
// We do this check because K COULD be one of the middle values
// K will be the largest of the two middle values, if it is one
if (A[m1] < B[m2]) {
return helper(A, B, k - (m1 - s1 + 1), m1 + 1, e1, s2, e2);
} else {
return helper(A, B, k - (m2 - s2 + 1), s1, e1, m2 + 1, e2);
}
} else {
console.log('else', A[m1] < B[m2])
if (A[m1] < B[m2]) {
// If the middle value of B is larger than the middle value of A then we can
// safely ignore the second half of B
return helper(A, B, k, s1, e1, s2, m2 - 1);
} else {
// Else we can safely ignore the second half of A
return helper(A, B, k, s1, m1 - 1, s2, e2);
}
}
}
// the only modifications I made was removing the types so that it become valid JS
// also line 11 and 12 had bugs (I forgot to add s1 and s2
// other than that this seems to be working (I never actually ran the code before I submitted)
console.log(kSmallest([1, 6, 8], [4, 7, 9], 1));
console.log(kSmallest([1, 6, 8], [4, 7, 9], 2));
console.log(kSmallest([1, 6, 8], [4, 7, 9], 3));
console.log(kSmallest([1, 6, 8], [4, 7, 9], 4));
console.log(kSmallest([1, 6, 8], [4, 7, 9], 5));
console.log(kSmallest([1, 6, 8], [4, 7, 9], 6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment