Posts

Showing posts with the label Array

How Many Numbers Are Smaller Than the Current Number

Problem Description: How Many Numbers Are Smaller Than the Current Number Given the array nums, for each nums[i] find out how many numbers in the array are smaller than it. That is, for each nums[i] you have to count the number of valid j's such that j != i and nums[j] < nums[i]. Return the answer in an array.   Example 1: Input: nums = [8,1,2,2,3] Output: [4,0,1,1,3] Explanation:  For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).  For nums[1]=1 does not exist any smaller number than it. For nums[2]=2 there exist one smaller number than it (1).  For nums[3]=2 there exist one smaller number than it (1).  For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2). Example 2: Input: nums = [6,5,4,8] Output: [2,1,0,3] Example 3: Input: nums = [7,7,7,7] Output: [0,0,0,0]   Constraints: 2 <= nums.length <= 500 0 <= nums[i] <= 100 Solution : class Solution {     public int[] smallerNumbersThanCurrent(int[] n...

Number of Good Pairs

Program Description: Number of Good Pairs Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. Example 1: Input: nums = [1,2,3,1,1,3] Output: 4 Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. Example 2: Input: nums = [1,1,1,1] Output: 6 Explanation: Each pair in the array are good. Example 3: Input: nums = [1,2,3] Output: 0   Constraints: 1 <= nums.length <= 100 1 <= nums[i] <= 100 Solution: class Solution {     public int numIdenticalPairs(int[] nums) {         int count = 0;         for(int i = 0; i< nums.length-1; i++){             for(int j=i+1; j<nums.length; j++){                 if(i<j && nums[i]==nums[j]){                     count++;             ...

Shuffle the Array

Program Description: Shuffle the Array Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn]. Return the array in the form [x1,y1,x2,y2,...,xn,yn]. Example 1: Input: nums = [2,5,1,3,4,7], n = 3 Output: [2,3,5,4,1,7]  Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7]. Example 2: Input: nums = [1,2,3,4,4,3,2,1], n = 4 Output: [1,4,2,3,3,2,4,1] Example 3: Input: nums = [1,1,2,2], n = 2 Output: [1,2,1,2] Constraints: 1 <= n <= 500 nums.length == 2n 1 <= nums[i] <= 10^3 Solution : class Solution {     public int[] shuffle(int[] nums, int n) {         int InsertValue = nums[n];         for(int i=1; i< nums.length; i+=2){             if(n>nums.length-1){                 break;             }             InsertValue = nums[n]; ...