My solution to a “Daily Coding Problem” that I received in my mail today.
Given an array of integers, return a new array where each element in the new array is the number of smaller elements to the right of that element in the original input array.
For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0], since:
- There is 1 smaller element to the right of 3
- There is 1 smaller element to the right of 4
- There are 2 smaller elements to the right of 9
- There is 1 smaller element to the right of 6
- There are no smaller elements to the right of 1
Daily Coding Problem solution in Typescript,
oneSixtyFive(arr: number[]): number[] | null {
//we can safely assume, arr would't be null
let counts: number[] = [];
arr.forEach((val, idx, array) => {
let count = 0;
for(let j = (idx+1); j < array.length; j++) {
if(array[j] < val) {
count += 1;
};
}
counts.push(count);
});
return counts;
}
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.
0 Comments