Skip to content

Commit 91bd89c

Browse files
author
hasibulislam999
committed
Count of Smaller Numbers After Self problem solved
1 parent 5b177ea commit 91bd89c

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/**
2+
* Title: Count of Smaller Numbers After Self
3+
* Description: Given an integer array nums, return an integer array counts where counts[i] is the number of smaller elements to the right of nums[i].
4+
* Author: Hasibul Islam
5+
* Date: 10/04/2023
6+
*/
7+
8+
/**
9+
* @param {number[]} nums
10+
* @return {number[]}
11+
*/
12+
/**
13+
* @param {number[]} nums
14+
* @return {number[]}
15+
*/
16+
var countSmaller = function (nums) {
17+
/*
18+
Approach: use merge sort and count inverses
19+
*/
20+
let counts = [],
21+
indexMapArr = [];
22+
for (let i = 0; i < nums.length; i++) {
23+
counts[i] = 0;
24+
}
25+
for (let i = 0; i < nums.length; i++) {
26+
indexMapArr.push([nums[i], i]);
27+
}
28+
mergeSort(0, nums.length - 1, indexMapArr);
29+
return counts;
30+
31+
function mergeSort(left, right, arr, order = 1) {
32+
if (left < right) {
33+
let mid = Math.floor((left + right) / 2);
34+
mergeSort(left, mid, arr, order);
35+
mergeSort(mid + 1, right, arr, order);
36+
merge(left, mid, right, arr, order);
37+
}
38+
return arr;
39+
}
40+
function merge(left, mid, right, arr, order) {
41+
let leftArr = [],
42+
rightArr = [],
43+
mainCounter = left,
44+
leftCounter = 0,
45+
rightCounter = 0,
46+
inversions = 0;
47+
for (let i = left; i <= mid; i++) {
48+
leftArr.push(arr[i]);
49+
}
50+
for (let i = mid + 1; i <= right; i++) {
51+
rightArr.push(arr[i]);
52+
}
53+
while (leftCounter < leftArr.length && rightCounter < rightArr.length) {
54+
if (order !== -1) {
55+
//For sorting in ascending order
56+
if (leftArr[leftCounter][0] <= rightArr[rightCounter][0]) {
57+
counts[leftArr[leftCounter][1]] += inversions;
58+
arr[mainCounter] = leftArr[leftCounter++];
59+
} else {
60+
inversions++;
61+
arr[mainCounter] = rightArr[rightCounter++];
62+
}
63+
} else {
64+
//For sorting in descending order
65+
if (leftArr[leftCounter] >= rightArr[rightCounter]) {
66+
arr[mainCounter] = leftArr[leftCounter++];
67+
} else {
68+
arr[mainCounter] = rightArr[rightCounter++];
69+
}
70+
}
71+
mainCounter++;
72+
}
73+
while (leftCounter < leftArr.length) {
74+
counts[leftArr[leftCounter][1]] += inversions;
75+
arr[mainCounter] = leftArr[leftCounter++];
76+
mainCounter++;
77+
}
78+
while (rightCounter < rightArr.length) {
79+
arr[mainCounter] = rightArr[rightCounter++];
80+
mainCounter++;
81+
}
82+
}
83+
};

0 commit comments

Comments
 (0)