Introduction
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
Steps
- take new array and counter variable
- run a nested for loop.
- Both starts from 0 and ends in nums.length
- if( i == j), then skip
- else if( nums[i] > nums[j]) , count++;
- arr[i] = count;
- return arr;
Hints
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; } }
Top comments (0)