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

Tahzib Mahmud Rifat @rifat87

About: Open source || Backend-Development || IoT || Robotics || Computer Vision

Joined:
Feb 13, 2024

1365. How Many Numbers Are Smaller Than the Current Number

Publish Date: Feb 26 '24
0 0

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

Comments 0 total

    Add comment