Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Input: nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation:
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Solution : 

class Solution {
public List<Integer> countSmaller(int[] nums) {
List<Integer> intList = new ArrayList<Integer>(nums.length);
int i, j;
int n = nums.length;
int low[] = new int[n];

// initialize all the counts in countSmaller array as 0
for (i = 0; i < n; i++)
low[i] = 0;

for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (nums[j] < nums[i])
low[i]++;
}
intList.add(low[i]);
}
return intList;
}

// Driver program to test above functions
public static void main(String[] args) {
Solution small = new Solution();
int arr[] = {5,2,6,1};
List<Integer> output = small.countSmaller(arr);
output.forEach(System.out::println);
}
}

Comments

Popular posts from this blog

Android - Using KeyStore to encrypt and decrypt the data

Stack and Queue

Java Reflection API