DEV Community

Cover image for 1365. How Many Numbers Are Smaller Than the Current Number
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

1365. How Many Numbers Are Smaller Than the Current Number

Introduction

Image description

Here we are given an array, now we have to traverse the array and check for every index element , how many numbers are smaller than it. And we have to count it and store it in a new array. Like nums = [8,1,2,2,3] , Output: [4,0,1,1,3].

Examples

Image description

Steps

  1. take new array and counter variable
  2. run a nested for loop.
  3. Both starts from 0 and ends in nums.length
  4. if( i == j), then skip
  5. else if( nums[i] > nums[j]) , count++;
  6. arr[i] = count;
  7. return arr;

Hints

Image description

JavaCode

class Solution {
    public int[] smallerNumbersThanCurrent(int[] nums) {
        int arr[] = new int[nums.length];
        for(int i = 0; i<nums.length; i++){
            int count = 0;
            for(int j=0; j< nums.length; j++){
                if ( i == j){
                    continue;
                }
                else if(nums[i] > nums[j]){
                    count++;
                }
            }
            arr[i] = count;
        }
        return arr;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.