Try It On GFG Prac Ce
Try It On GFG Prac Ce
the
arrays and rearrange the elements such that the smallest n elements are in a[] and the
remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order.
Examples:
Table of Content
The idea is to traverse b[] from the end in reverse order and compare each element with the last
(largest) element of a[]. For any index i, if b[i] is smaller than the last element of a[],
replace b[i] with the last element of a[] and use insert step of inser on sort to find the correct
place of b[i] in a[].
How do we keep a[] sorted? Every me we add any element from b[] to a[], we find the correct
index using insert step of inser on sort.
How do we keep b[] sorted? This is ensured by the fact that we traverse b[] from end and insert
only when current element of b[] is smaller.
Illustra on
C++CJavaPythonC#JavaScript
// JavaScript Code to Merge two sorted arrays a[] and b[] without
func on mergeArrays(a, b) {
10
11
12
13
14
15
let j = a.length - 2;
16
17
a[j + 1] = a[j];
18
j--;
19
20
a[j + 1] = b[i];
21
b[i] = last;
22
23
24
25
26
27
28
mergeArrays(a, b);
29
30
console.log(a.join(" "));
31
console.log(b.join(" "));
Output
123589
10 13 15 20
Time Complexity: O(m * n), where n and m are sizes of a[] and b[] respec vely.
Auxiliary Space: O(1)
We can use the fact that nth smallest elemen n the sorted combined array acts as a pivot dividing
the elements among a[] and b[]. Ini ally, this nth smallest element can lie in either arrays so
instead of finding it, we can find the first index idx in a[], such that the elements a er this index
were larger than the pivot.
Elements of a[] placed a er index idx should be replaced with smaller elements from b[]. Now all
elements were in the correct arrays and we can apply sor ng to both arrays to maintain the order.
1/6
C++CJavaPythonC#JavaScript
10
// in both the arrays.
11
func on kthSmallest(a, b, k) {
12
13
let lo = 0, hi = n, idx = 0;
14
15
16
17
18
19
20
21
22
if (mid2 > m) {
23
lo = mid1 + 1;
24
con nue;
25
}
26
27
28
29
30
31
32
33
34
35
// If it is a valid par on
36
37
idx = mid1;
38
break;
39
40
41
// Check if we need to take lesser elements from a[]
42
43
hi = mid1 - 1;
44
45
46
47
else {
48
lo = mid1 + 1;
49
50
51
return idx;
52
53
54
func on mergeArrays(a, b) {
55
const n = a.length;
56
const m = b.length;
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
mergeArrays(a, b);
72
73
console.log(a.join(" "));
74
console.log(b.join(" "));
Output
123589
10 13 15 20