Published on

Count Inversion in array

Authors

Problem Overview

Given an integer array nums, return the number of inversion in the array.

Inversion: Two number nums[i] and nums[j] forms and inversion if nums[i]>nums[j] and i<j.

For similar Leetcode problem visit Leetcode Link;

Sample Input Output

Input: nums = [0,5,2,3,1];
Output: 5

Javascript Solution

For every element i inversion count will be total numbers from i+1 to n count which are less than nums[i].

Brute Force Solution

We pick one number nums[i] and count the all number from i+1 to n that are less than nums[i].

Time Complexity: O(N*N)

Space Complexity: O(1)

Code

var inversionCount = function(nums) {
let inversion = 0;
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] > 2 * nums[j]) {
inversion++;
}
}
}
return inversion;
};

Using Devide and Conquer Algorithm

  1. Iterate over the shortest array s
  2. Keep accumulating (XOR ^ing) the elements of both s and t, after we have converted them to Numbers with CharCodeAt() so the XOR can work. Elements that appear both in t and s will give us zero ( X^X=0), yet that zero will not affect the total sum (X^0=X)
  3. Return the converted back to character final sum, which is essentially the (desired) character not present in s
leetcode submission result

Original Solution Link GeorgeChryso;

const findTheDifference = function(s, t) {
let sum=0 // initialize the accumulator
// t.length > s.length because there will always be 1 extra letter on t (the one we want to return)
for (let i = 0; i < s.length; i++) {
sum^= // accumulate with XOR
t[i].charCodeAt()^ // the converted to Number t[i]
s[i].charCodeAt() // along with a converted to Number s[i],
}
sum^=t[i].charCodeAt() // add the remaining letter of t
return String.fromCharCode(sum) // return the converted to Character total
};
Quick example:
s='abcd' , t='dcbqa'

Same Algorithm Implementation Using ES6

/**
* @param {number} x
* @return {number}
*/
var findTheDifference = function (s, t) {
return String.fromCharCode(
[...s, ...t].reduce((acc, c) => {
return acc ^ c.charCodeAt(0)
}, 0)
)
}