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

Here’s my solution in,

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;
}

Like the blog? Subscribe for updates

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. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *