Related
Well in this question I have to find the longest sequence of zeros in the binary representation of an integer.
After a lot of hard work, I'm able to find the longest sequence of zeros with my logic which I changed many times.
I have one problem with my logic which is if I input an integer that has no gap in it has to give me an answer 0 which I tried to make by myself but I failed.
Right now if I input an integer that has no gap it gives me output infinity.
I want my answer to print 0 when the binary representation of an integer has no gap in it.
var dn = prompt("Enter a number: ");
var bn = new Array();
var i = 0;
var binary = [];
while (dn != 0) {
bn[i] = dn % 2;
dn = Math.floor(dn / 2);
i++;
}
for (var j = i - 1; j >= 0; j--) {
binary.push(bn[j]);
}
console.log(binary.join(""));
var currentGap = 0;
var gaps = [];
var len = binary.length;
for (var k = 0; k < len; k++) {
if (binary[k] == 0) {
currentGap++;
if (binary[k + 1] == 1) {
gaps.push(currentGap);
currentGap = 0;
}
}
}
console.log(Math.max(...gaps));
You could add initialize gaps with 0, or add condition when gaps remains empty to print 0 else max of gaps.
var dn = prompt("Enter a number: ");
var bn = new Array();
var i = 0;
var binary = [];
while (dn != 0) {
bn[i] = dn % 2;
dn = Math.floor(dn / 2);
i++;
}
for (var j = i - 1; j >= 0; j--) {
binary.push(bn[j]);
}
console.log(binary.join(""));
var currentGap = 0;
//var gaps = []
var gaps = [0];
var len = binary.length;
for (var k = 0; k < len; k++) {
if (binary[k] == 0) {
currentGap++;
if (binary[k + 1] == 1) {
gaps.push(currentGap);
currentGap = 0;
}
}
}
//if (gaps.length === 0)
// console.log(0)
//else
// console.log(Math.max(...gaps));
console.log(Math.max(...gaps));
You can simply print 0 if your gaps array has no length.
var dn = prompt("Enter a number: ");
var bn = new Array();
var i = 0;
var binary = [];
while (dn != 0) {
bn[i] = dn % 2;
dn = Math.floor(dn / 2);
i++;
}
for (var j = i - 1; j >= 0; j--) {
binary.push(bn[j]);
}
console.log(binary.join(""));
var currentGap = 0;
var gaps = [];
var len = binary.length;
for (var k = 0; k < len; k++) {
if (binary[k] == 0) {
currentGap++;
if (binary[k + 1] == 1) {
gaps.push(currentGap);
currentGap = 0;
}
}
}
console.log(gaps.length ? Math.max(...gaps) : 0); // <-- This
I apologize if I'm misunderstanding your question, but would this satisfy your problem?
const s = prompt("Enter a number:");
const longest = Math.max(...parseInt(s).toString(2).split('1').map(s=>s.length));
console.log(longest);
just change var gaps = [];
to var gaps = [0];
You can also do that...
let dn = parseInt(prompt("Enter a number: "))
if (isNaN(dn)) console.log('Not a Number!')
else
{
let
dnStr = dn.toString(2) // binary convertion
, count = 0
, zVal = '0'
;
while (dnStr.includes(zVal) )
{
count++
zVal += '0'
}
console.log( `${dnStr}\n--> ${count}` )
}
If you want to do your own binary convertion, prefert o use Javasscript binary opérators:
let dn = parseInt(prompt("Enter a number: "))
if (isNaN(dn)) console.log('Not a Number!')
else
{
let gap = [0]
let Bin = []
let count = 0
for (;;)
{
Bin.unshift( dn & 1 ) // --> dn % 2
if (dn & 1)
{
gap.push(count)
count = 0
}
else count++
dn >>>=1 // --> dn = Math.floor(dn / 2)
if (!dn) break // --> if (dn === 0 )
}
console.log(Bin.join(''))
console.log(Math.max(...gap))
}
I had a go at this and this is what I came up with as a function:
function binaryGap(N){
let binary = Math.abs(N).toString(2); // Convert to Binary string
let binarySplit = binary.split("1"); // Split the string wherever there is "1"
let tempBinaryArr = []; // create an empty array to store the element from Splice
let max = 0; // Setting the max length to zero to compare with each element
// Removing the zeros at the end
if(binarySplit[binarySplit.length -1] == 0){
tempBinaryArr = binarySplit.splice(binarySplit.length -1, 1);
}
//Looping through each element of binarySplit to compare with variable max
for(let j=0; j < binarySplit.length; j++){
if(max < binarySplit[j].length){
max = binarySplit[j].length;
}
}
return `Longest Sequence of Zeros: ${max}`;
}
If I understood the task correctly, you can arrange the logic in something like this. In case if the input comes as a string you don't need the .toString() part
function splitByZero(str) {
const eachSubstr = str
.toString()
.split(1)
.filter((e) => e); //to remove empty values in the new array
let maxLength = 0;
for (const substr of eachSubstr) {
if (maxLength < substr.length) {
maxLength = substr.length;
}
}
console.log(maxLength);
}
splitByZero(111011100011);
function findLongestDistance(){
findGap("1000100100001");
findGap("1000100");
findGap("000100");
findGap("10000");
findGap("000001");
findGap("111111")
}
function findGap(n){
var split = n.split(/1/g);
var longestZeros = 0;
if(split.length>2){
for(var i in split){
var len = split[i].length;
if(len>longestZeros){
longestZeros = len;
}
}
console.log(longestZeros);
return longestZeros;
}
console.log(0);
return 0;
}
I am trying to do one problem of hackerrank but I am not able to solve that problem
Can someone please help me with wrong logic implementation done by me?
problem
Print the length of the longest string, such that is a child of both s1 and s2.
Sample Input
HARRY
SALLY
Sample Output
2
Explanation
The longest string that can be formed by deleting zero or more characters from HARRY and SALLY is AY, whose length is 2.
Sample Input 1
AA
BB
Sample Output 1
0
Explanation 1
AA and BB have no characters in common and hence the output is 0
Sample Input 2
SHINCHAN
NOHARAAA
Sample Output 2
3
Explanation 2
The longest string that can be formed between SHINCHAN and NOHARAAA while maintaining the order is NHA.
I have written some logic which is as follows:
function commonChild(s1, s2) {
var arr = s2.split(),
currenString = '',
maxLength = 0,
index = -1;
console.log(arr);
for (var i = 0; i < s1.length; i++) {
var char = s1.charAt(i),
charIndex = arr.indexOf(char);
console.log(char)
if (index < charIndex) {
index = charIndex;
currenString +=char;
}
maxLength= Math.max(maxLength,currenString.length)
}
return maxLength;
}
commonChild('ABCDEF', 'FBDAMN');
console.log(commonChild('ABCDEF', 'FBDAMN'));
pardon me. this is an unoptimized solution.
function maxCommon(a, b, offset) {
offset = offset || 0;
if (a === b) {
return [[a, b]];
}
var possibleSolns = [];
for (var i = 0 + offset; i < a.length; i++) {
for (var j = 0 + offset; j < b.length; j++) {
if (a.charAt(i) === b.charAt(j)) {
possibleSolns.push([
a.substring(0, offset) + a.substring(i),
b.substring(0, offset) +b.substring(j)
]);
break;
}
}
}
var results = [];
possibleSolns.forEach(function(soln) {
var s = maxCommon(soln[0], soln[1], offset+1);
if (s.length === 0) {
s = [[soln[0].substring(0, offset +1), soln[1].substring(0, offset +1)]];
}
results = results.concat(s);
});
return results;
}
var maxLen = -1;
var soln = null;
maxCommon("ABCDEF", "FBDAMN").map(function(_) {
return _[0];
}).forEach(function(_) {
if (_.length > maxLen) {
soln = _;
maxLen = _.length;
}
});
console.log(soln);
I kept most of your logic in the answer:
function commonChild(s1, s2) {
var // Sets strings to arrays
arrayString1 = s1.split(""),
arrayString2 = s2.split(""),
collectedChars = "",
maxLength = 0,
max = arrayString1.length;
for (var i = 0; i < max; i++) {
var
char = arrayString1[i],
count = arrayString2.indexOf(char);
// check if char is in second string and not in collected
if (count != -1 && collectedChars.indexOf(char) == -1) {
collectedChars += char;
maxLength++;
}
}
return maxLength;
}
// expected output 4
console.log(commonChild(
'ABCDEF',
'FBDAMN'
));
// expected output 1
console.log(commonChild(
'AA',
'FBDAMN'
));
Using lodash and spread operation you can do it in this way.
const test = (first, second) => {
const stringArray1 = [...first];
const stringArray2 = [...second];
return _.intersection(stringArray1, stringArray2).length;
}
console.log(test('ABCDEF', 'FBDAMN'));
You can solve it using lcs least common subsequence
function LCS(s1,s2,x,y){
var result = 0;
if(x==0 || y==0){
result = 0
}else if(s1[x-1] == s2[y-1]){
result = 1+ LCS(s1,s2,x-1,y-1)
} else if(s1[x-1] != s2[y-1]){
result = Math.max(LCS(s1,s2,x-1,y), LCS(s1,s2,x,y-1))
}
return result;
}
// Complete the commonChild function below.
function commonChild(s1, s2) {
return LCS(s1,s2,s1.length,s2.length);
}
Based on your code before the edit.
One little change is to change var arr = s2.split() to split('').
The main change in the logic is that I added a loop to run over the string each time from another character (first loop from the first, second from the second etc).
function commonChild(s1, s2) {
var arr = s2.split(''),
currenString = '',
maxLength = 0,
index = -1,
j = -1;
for (var ii = 0; ii < s1.length; ii++) {
index = -1;
currenString = '';
for (var i = ii; i < s1.length; i++) {
var char = s1.charAt(i),
j = arr.indexOf(char);
if (index < j) {
index = j;
currenString += char;
}
maxLength = Math.max(maxLength, currenString.length)
}
}
return maxLength;
}
console.log(commonChild('ABCDEF', 'FBDAMN'));
I'm trying to figure out how to find three smallest numbers. I've got 2 first, but I'm not sure how to find the third one. I can not use any methods which change the original array. Thank you.
let max_1 = 0;
let max_2 = 0;
let max_3 = 0;
for(let i=0; i<compare.length; i++){
let nr = +compare[i];
if(nr > max_1){
max_2 = max_1;
max_1 = nr;
}else if(nr < max_1 && nr > max_2){
?
}
}
Try the following:
var arr1 = [1,2,4,5,3,3,2];
let arr = [...new Set(arr1)];
var i, first, second, third;
third = first = second = 2147483647;
for (i = 0; i < arr.length ; i ++)
{
if (arr[i] < first)
{
third = second;
second = first;
first = arr[i];
}
else if (arr[i] < second)
{
third = second;
second = arr[i];
}
else if (arr[i] < third)
third = arr[i];
}
console.log(first+ " "+ second+" "+ third);
You could use reduce like below - it will return an array holding the 3 smallest numbers.
const array = [1,2,3,4,5,6,7,-1,-2, -2];
const threeSmallest = [...new Set(array)].reduce((a, b) => {
if (a.length < 3) return a.concat(b);
a.sort((x,y) => y - x);
let index = a.findIndex(e => e > b);
if (index > -1) {
a.splice(index, 1);
return a.concat(b);
}
return a;
},[]);
console.log(threeSmallest);
I am in mid of my JavaScript session. Find this code in my coding exercise. I understand the logic but I didn't get this map[nums[x]] condition.
function twoSum(nums, target_num) {
var map = [];
var indexnum = [];
for (var x = 0; x < nums.length; x++)
{
if (map[nums[x]] != null)
// what they meant by map[nums[x]]
{
index = map[nums[x]];
indexnum[0] = index+1;
indexnum[1] = x+1;
break;
}
else
{
map[target_num - nums[x]] = x;
}
}
return indexnum;
}
console.log(twoSum([10,20,10,40,50,60,70],50));
I am trying to get the Pair of elements from a specified array whose sum equals a specific target number. I have written below code.
function arraypair(array,sum){
for (i = 0;i < array.length;i++) {
var first = array[i];
for (j = i + 1;j < array.length;j++) {
var second = array[j];
if ((first + second) == sum) {
alert('First: ' + first + ' Second ' + second + ' SUM ' + sum);
console.log('First: ' + first + ' Second ' + second);
}
}
}
}
var a = [2, 4, 3, 5, 6, -2, 4, 7, 8, 9];
arraypair(a,7);
Is there any optimized way than above two solutions? Can some one explain the first solution what exactly map[nums[x]] this condition points to?
Using HashMap approach using time complexity approx O(n),below is the following code:
let twoSum = (array, sum) => {
let hashMap = {},
results = []
for (let i = 0; i < array.length; i++){
if (hashMap[array[i]]){
results.push([hashMap[array[i]], array[i]])
}else{
hashMap[sum - array[i]] = array[i];
}
}
return results;
}
console.log(twoSum([10,20,10,40,50,60,70,30],50));
result:
{[10, 40],[20, 30]}
I think the code is self explanatory ,even if you want help to understand it,let me know.I will be happy enough to for its explanation.
Hope it helps..
that map value you're seeing is a lookup table and that twoSum method has implemented what's called Dynamic Programming
In Dynamic Programming, you store values of your computations which you can re-use later on to find the solution.
Lets investigate how it works to better understand it:
twoSum([10,20,40,50,60,70], 50)
//I removed one of the duplicate 10s to make the example simpler
In iteration 0:
value is 10. Our target number is 50. When I see the number 10 in index 0, I make a note that if I ever find a 40 (50 - 10 = 40) in this list, then I can find its pair in index 0.
So in our map, 40 points to 0.
In iteration 2:
value is 40. I look at map my map to see I previously found a pair for 40.
map[nums[x]] (which is the same as map[40]) will return 0.
That means I have a pair for 40 at index 0.
0 and 2 make a pair.
Does that make any sense now?
Unlike in your solution where you have 2 nested loops, you can store previously computed values. This will save you processing time, but waste more space in the memory (because the lookup table will be needing the memory)
Also since you're writing this in javascript, your map can be an object instead of an array. It'll also make debugging a lot easier ;)
function twoSum(arr, S) {
const sum = [];
for(let i = 0; i< arr.length; i++) {
for(let j = i+1; j < arr.length; j++) {
if(S == arr[i] + arr[j]) sum.push([arr[i],arr[j]])
}
}
return sum
}
Brute Force not best way to solve but it works.
Please try the below code. It will give you all the unique pairs whose sum will be equal to the targetSum. It performs the binary search so will be better in performance. The time complexity of this solution is O(NLogN)
((arr,targetSum) => {
if ((arr && arr.length === 0) || targetSum === undefined) {
return false;
} else {
for (let x = 0; x <=arr.length -1; x++) {
let partnerInPair = targetSum - arr[x];
let start = x+1;
let end = (arr.length) - 2;
while(start <= end) {
let mid = parseInt(((start + end)/2));
if (arr[mid] === partnerInPair) {
console.log(`Pairs are ${arr[x]} and ${arr[mid]} `);
break;
} else if(partnerInPair < arr[mid]) {
end = mid - 1;
} else if(partnerInPair > arr[mid]) {
start = mid + 1;
}
}
};
};
})([0,1,2,3,4,5,6,7,8,9], 10)
function twoSum(arr, target) {
let res = [];
let indexes = [];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (target === arr[i] + arr[j] && !indexes.includes(i) && !indexes.includes(j)) {
res.push([arr[i], arr[j]]);
indexes.push(i);
indexes.push(j);
}
}
}
return res;
}
console.log('Result - ',
twoSum([1,2,3,4,5,6,6,6,6,6,6,6,6,6,7,8,9,10], 12)
);
Brute force.
const findTwoNum = ((arr, value) => {
let result = [];
for(let i= 0; i< arr.length-1; i++) {
if(arr[i] > value) {
continue;
}
if(arr.includes(value-arr[i])) {
result.push(arr[i]);
result.push(value-arr[i]);
break;;
}
}
return result;
});
let arr = [20,10,40,50,60,70,30];
const value = 120;
console.log(findTwoNum(arr, value));
OUTPUT : Array [50, 70]
function twoSum(arr){
let constant = 17;
for(let i=0;i<arr.length-2;i++){
for(let j=i+1;j<arr.length;j++){
if(arr[i]+arr[j] === constant){
console.log(arr[i],arr[j]);
}
}
}
}
let myArr = [2, 4, 3, 5, 7, 8, 9];
function getPair(arr, targetNum) {
for (let i = 0; i < arr.length; i++) {
let cNum = arr[i]; //my current number
for (let j = i; j < arr.length; j++) {
if (cNum !== arr[j] && cNum + arr[j] === targetNum) {
let pair = {};
pair.key1 = cNum;
pair.key2 = arr[j];
console.log(pair);
}
}
}
}
getPair(myArr, 7)
let sumArray = (arr,target) => {
let ar = []
arr.forEach((element,index) => {
console.log(index);
arr.forEach((element2, index2) => {
if( (index2 > index) && (element + element2 == target)){
ar.push({element, element2})
}
});
});
return ar
}
console.log(sumArray([8, 7, 2, 5, 3, 1],10))
Use {} hash object for storing and fast lookups.
Use simple for loop so you can return as soon as you find the right combo; array methods like .forEach() have to finish iterating no matter what.
And make sure you handle edges cases like this: twoSum([1,2,3,4], 8)---that should return undefined, but if you don't check for !== i (see below), you would erroneously return [4,4]. Think about why that is...
function twoSum(nums, target) {
const lookup = {};
for (let i = 0; i < nums.length; i++) {
const n = nums[i];
if (lookup[n] === undefined) {//lookup n; seen it before?
lookup[n] = i; //no, so add to dictionary with index as value
}
//seen target - n before? if so, is it different than n?
if (lookup[target - n] !== undefined && lookup[target - n] !== i) {
return [target - n, n];//yep, so we return our answer!
}
}
return undefined;//didn't find anything, so return undefined
}
We can fix this with simple JS object as well.
const twoSum = (arr, num) => {
let obj = {};
let res = [];
arr.map(item => {
let com = num - item;
if (obj[com]) {
res.push([obj[com], item]);
} else {
obj[item] = item;
}
});
return res;
};
console.log(twoSum([2, 3, 2, 5, 4, 9, 6, 8, 8, 7], 10));
// Output: [ [ 4, 6 ], [ 2, 8 ], [ 2, 8 ], [ 3, 7 ] ]
Solution In Java
Solution 1
public static int[] twoNumberSum(int[] array, int targetSum) {
for(int i=0;i<array.length;i++){
int first=array[i];
for(int j=i+1;j<array.length;j++){
int second=array[j];
if(first+second==targetSum){
return new int[]{first,second};
}
}
}
return new int[0];
}
Solution 2
public static int[] twoNumberSum(int[] array, int targetSum) {
Set<Integer> nums=new HashSet<Integer>();
for(int num:array){
int pmatch=targetSum-num;
if(nums.contains(pmatch)){
return new int[]{pmatch,num};
}else{
nums.add(num);
}
}
return new int[0];
}
Solution 3
public static int[] twoNumberSum(int[] array, int targetSum) {
Arrays.sort(array);
int left=0;
int right=array.length-1;
while(left<right){
int currentSum=array[left]+array[right];
if(currentSum==targetSum){
return new int[]{array[left],array[right]};
}else if(currentSum<targetSum){
left++;
}else if(currentSum>targetSum){
right--;
}
}
return new int[0];
}
function findPairOfNumbers(arr, targetSum) {
var low = 0, high = arr.length - 1, sum, result = [];
while(low < high) {
sum = arr[low] + arr[high];
if(sum < targetSum)
low++;
else if(sum > targetSum)
high--;
else if(sum === targetSum) {
result.push({val1: arr[low], val2: arr[high]});
high--;
}
}
return (result || false);
}
var pairs = findPairOfNumbers([1,2,3,4,4,5], 8);
if(pairs.length) {
console.log(pairs);
} else {
console.log("No pair of numbers found that sums to " + 8);
}
Simple Solution would be in javascript is:
var arr = [7,5,10,-5,9,14,45,77,5,3];
var arrLen = arr.length;
var sum = 15;
function findSumOfArrayInGiven (arr, arrLen, sum){
var left = 0;
var right = arrLen - 1;
// Sort Array in Ascending Order
arr = arr.sort(function(a, b) {
return a - b;
})
// Iterate Over
while(left < right){
if(arr[left] + arr[right] === sum){
return {
res : true,
matchNum: arr[left] + ' + ' + arr[right]
};
}else if(arr[left] + arr[right] < sum){
left++;
}else{
right--;
}
}
return 0;
}
var resp = findSumOfArrayInGiven (arr, arrLen, sum);
// Display Desired output
if(resp.res === true){
console.log('Matching Numbers are: ' + resp.matchNum +' = '+ sum);
}else{
console.log('There are no matching numbers of given sum');
}
Runtime test JSBin: https://jsbin.com/vuhitudebi/edit?js,console
Runtime test JSFiddle: https://jsfiddle.net/arbaazshaikh919/de0amjxt/4/
function sumOfTwo(array, sumNumber) {
for (i of array) {
for (j of array) {
if (i + j === sumNumber) {
console.log([i, j])
}
}
}
}
sumOfTwo([1, 2, 3], 4)
function twoSum(args , total) {
let obj = [];
let a = args.length;
for(let i = 0 ; i < a ; i++){
for(let j = 0; j < a ; j++){
if(args[i] + args[j] == total) {
obj.push([args[i] , args[j]])
}
}
}
console.log(obj)}
twoSum([10,20,10,40,50,60,70,30],60);
/* */
I'm trying to find an easy way to loop (iterate) over an array to find all the missing numbers in a sequence, the array will look a bit like the one below.
var numArray = [0189459, 0189460, 0189461, 0189463, 0189465];
For the array above I would need 0189462 and 0189464 logged out.
UPDATE : this is the exact solution I used from Soufiane's answer.
var numArray = [0189459, 0189460, 0189461, 0189463, 0189465];
var mia= [];
for(var i = 1; i < numArray.length; i++)
{
if(numArray[i] - numArray[i-1] != 1)
{
var x = numArray[i] - numArray[i-1];
var j = 1;
while (j<x)
{
mia.push(numArray[i-1]+j);
j++;
}
}
}
alert(mia) // returns [0189462, 0189464]
UPDATE
Here's a neater version using .reduce
var numArray = [0189459, 0189460, 0189461, 0189463, 0189466];
var mia = numArray.reduce(function(acc, cur, ind, arr) {
var diff = cur - arr[ind-1];
if (diff > 1) {
var i = 1;
while (i < diff) {
acc.push(arr[ind-1]+i);
i++;
}
}
return acc;
}, []);
console.log(mia);
If you know that the numbers are sorted and increasing:
for(var i = 1; i < numArray.length; i++) {
if(numArray[i] - numArray[i-1] != 1) {
//Not consecutive sequence, here you can break or do whatever you want
}
}
ES6-Style
var arr = [0189459, 0189460, 0189461, 0189463, 0189465];
var [min,max] = [Math.min(...arr), Math.max(...arr)];
var out = Array.from(Array(max-min),(v,i)=>i+min).filter(i=>!arr.includes(i));
Result: [189462, 189464]
Watch your leading zeroes, they will be dropped when the array is interpreted-
var A= [0189459, 0189460, 0189461, 0189463, 0189465]
(A returns [189459,189460,189461,189463,189465])
function absent(arr){
var mia= [], min= Math.min.apply('',arr), max= Math.max.apply('',arr);
while(min<max){
if(arr.indexOf(++min)== -1) mia.push(min);
}
return mia;
}
var A= [0189459, 0189460, 0189461, 0189463, 0189465];
alert(absent(A))
/* returned value: (Array)
189462,189464
*/
To find a missing number in a sequence, First of all, We need to sort an array. Then we can identify what number is missing. I am providing here full code with some test scenarios. this code will identify only missing positive number, if you pass negative values even then it gives positive number.
function findMissingNumber(inputAr) {
// Sort array
sortArray(inputAr);
// finding missing number here
var result = 0;
if (inputAr[0] > 1 || inputAr[inputAr.length - 1] < 1) {
result = 1;
} else {
for (var i = 0; i < inputAr.length; i++) {
if ((inputAr[i + 1] - inputAr[i]) > 1) {
result = inputAr[i] + 1;
}
}
}
if (!result) {
result = inputAr[inputAr.length - 1] + 1;
}
return result;
}
function sortArray(inputAr) {
var temp;
for (var i = 0; i < inputAr.length; i++) {
for (var j = i + 1; j < inputAr.length; j++) {
if (inputAr[j] < inputAr[i]) {
temp = inputAr[j];
inputAr[j] = inputAr[i];
inputAr[i] = temp;
}
}
}
}
console.log(findMissingNumber([1, 3, 6, 4, 1, 2]));
console.log(findMissingNumber([1, 2, 3]));
console.log(findMissingNumber([85]));
console.log(findMissingNumber([86, 85]));
console.log(findMissingNumber([0, 1000]));
This can now be done easily as a one-liner with the find method:
const arr = [1,2,3,5,6,7,8,9];
return arr.find((x,i) => arr[i+1]-x > 1) + 1
//4
const findMissing = (arr) => {
const min = Math.min(...arr);
const max = Math.max(...arr);
// add missing numbers in the array
let newArr = Array.from(Array(max-min), (v, i) => {
return i + min
});
// compare the full array with the old missing array
let filter = newArr.filter(i => {
return !arr.includes(i)
})
return filter;
};
const findMissing = (numarr) => {
for(let i = 1; i <= numarr.length; i++) {
if(i - numarr[i-1] !== 0) {
console.log('found it', i)
break;
} else if(i === numarr.length) console.log('found it', numarr.length + 1)
}
};
console.log(findMissing([1,2,3,4,5,6,7,8,9,10,11,12,13,14]))
It would be fairly straightforward to sort the array:
numArray.sort();
Then, depending upon what was easiest for you:
You could just traverse the array, catching sequential patterns and checking them as you go.
You could split the array into multiple arrays of sequential numbers and then check each of those separate arrays.
You could reduce the sorted array to an array of pairs where each pair is a start and end sequence and then compare those sequence start/ends to your other data.
function missingNum(nums){
const numberArray = nums.sort((num1, num2)=>{
return num1 - num2;
});
for (let i=0; i < numberArray.length; i++){
if(i !== numberArray[i]){
return i;
}
}
}
console.log(missingNum([0,3,5,8,4,6,1,9,7]))
Please check below code.....
function solution(A) {
var max = Math.max.apply(Math, A);
if(A.indexOf(1)<0) return 1;
var t = (max*(max+1)/2) - A.reduce(function(a,b){return a+b});
return t>0?t:max+1;
}
Try as shown below
// Find the missing number
let numArray = [0189459, 0189460, 0189461, 0189463, 0189468];
let numLen = numArray.length;
let actLen = Number(numArray[numLen-1])-Number(numArray[0]);
let allNumber = [];
for(let i=0; i<=actLen; i++){
allNumber.push(Number(numArray[0])+i);
}
[...allNumber].forEach(ele=>{
if(!numArray.includes(ele)){
console.log('Missing Number -> '+ele);
}
})
I use a recursive function for this.
function findMissing(arr, start, stop) {
var current = start,
next = stop,
collector = new Array();
function parseMissing(a, key) {
if(key+1 == a.length) return;
current = a[key];
next = a[key + 1];
if(next - current !== 1) {
collector.push(current + 1);
// insert current+1 at key+1
a = a.slice( 0, key+1 ).concat( current+1 ).concat( a.slice( key +1 ) );
return parseMissing(a, key+1);
}
return parseMissing(a, key+1);
}
parseMissing(arr, 0);
return collector;
}
Not the best idea if you are looking through a huge set of numbers. FAIR WARNING: recursive functions are resource intensive (pointers and stuff) and this might give you unexpected results if you are working with huge numbers. You can see the jsfiddle. This also assumes you have the array sorted.
Basically, you pass the "findMissing()" function the array you want to use, the starting number and stopping number and let it go from there.
So:
var missingArr = findMissing(sequenceArr, 1, 10);
let missing = [];
let numArray = [3,5,1,8,9,36];
const sortedNumArray = numArray.sort((a, b) => a - b);
sortedNumArray.reduce((acc, current) => {
let next = acc + 1;
if (next !== current) {
for(next; next < current; next++) {
missing.push(next);
}
}
return current;
});
Assuming that there are no duplicates
let numberArray = [];
for (let i = 1; i <= 100; i++) {
numberArray.push(i);
}
let deletedArray = numberArray.splice(30, 1);
let sortedArray = numberArray.sort((a, b) => a - b);
let array = sortedArray;
function findMissingNumber(arr, sizeOfArray) {
total = (sizeOfArray * (sizeOfArray + 1)) / 2;
console.log(total);
for (i = 0; i < arr.length; i++) {
total -= arr[i];
}
return total;
}
console.log(findMissingNumber(array, 100));
Here is the most efficient and simple way to find the missing numbers in the array. There is only one loop and complexity is O(n).
/**
*
* #param {*} item Takes only the sorted array
*/
function getAllMissingNumbers(item) {
let first = 0;
let second = 1;
let currentValue = item[0];
const container = [];
while (first < second && item[second]) {
if ((item[first] + 1) !== item[second]) { // Not in sequence so adds the missing numbers in an array
if ((currentValue + 1) === item[second]) { // Moves the first & second pointer
first = second;
second++;
currentValue = item[first];
} else { // Adds the missing number between two number
container.push(++currentValue);
}
} else { // Numbers are in sequence so just moves the first & second pointer
first = second;
second++;
currentValue = item[first];
}
}
return container;
}
console.log(getAllMissingNumbers([0189459, 0189460, 0189461, 0189463, 0189465].sort( (a, b) => a - b )));
console.log(getAllMissingNumbers([-5,2,3,9]));
Adding one more similar method
Find the min and max of the numbers in the array
Loop with the max and min numbers to get the full list
compare the full list of numbers with the input array to get the difference
const array = [0189459, 0189460, 0189461, 0189463, 0189465]
const max = Math.max(...array)
const min = Math.min(...array)
let wholeNumber = []
for(var i = min ;i<=max ;i++ ){
wholeNumber.push(i)
}
const missing = wholeNumber.filter((v)=>!array.includes(v))
console.log('wholeNumber',wholeNumber)
console.log('missingNumber',missing)
Here's a variant of #Mark Walters's function which adds the ability to specify a lower boundary for your sequence, for example if you know that your sequence should always begin at 0189455, or some other number like 1.
It should also be possible to adjust this code to check for an upper boundary, but at the moment it can only look for lower boundaries.
//Our first example array.
var numArray = [0189459, 0189460, 0189461, 0189463, 0189465];
//For this array the lowerBoundary will be 0189455
var numArrayLowerBoundary = 0189455;
//Our second example array.
var simpleArray = [3, 5, 6, 7, 8, 10, 11, 13];
//For this Array the lower boundary will be 1
var simpleArrayLowerBoundary = 1;
//Build a html string so we can show our results nicely in a div
var html = "numArray = [0189459, 0189460, 0189461, 0189463, 0189465]<br>"
html += "Its lowerBoundary is \"0189455\"<br>"
html += "The following numbers are missing from the numArray:<br>"
html += findMissingNumbers(numArray, numArrayLowerBoundary);
html += "<br><br>"
html += "simpleArray = [3, 5, 6, 7, 8, 10, 11, 13]<br>"
html += "Its lowerBoundary is \"1\".<br>"
html += "The following numbers are missing from the simpleArray:<br>"
html += findMissingNumbers(simpleArray, simpleArrayLowerBoundary);
//Display the results in a div
document.getElementById("log").innerHTML=html;
//This is the function used to find missing numbers!
//Copy/paste this if you just want the function and don't need the demo code.
function findMissingNumbers(arrSequence, lowerBoundary) {
var mia = [];
for (var i = 0; i < arrSequence.length; i++) {
if (i === 0) {
//If the first thing in the array isn't exactly
//equal to the lowerBoundary...
if (arrSequence[i] !== lowerBoundary) {
//Count up from lowerBoundary, incrementing 1
//each time, until we reach the
//value one less than the first thing in the array.
var x = arrSequence[i];
var j = lowerBoundary;
while (j < x) {
mia.push(j); //Add each "missing" number to the array
j++;
}
} //end if
} else {
//If the difference between two array indexes is not
//exactly 1 there are one or more numbers missing from this sequence.
if (arrSequence[i] - arrSequence[i - 1] !== 1) {
//List the missing numbers by adding 1 to the value
//of the previous array index x times.
//x is the size of the "gap" i.e. the number of missing numbers
//in this sequence.
var x = arrSequence[i] - arrSequence[i - 1];
var j = 1;
while (j < x) {
mia.push(arrSequence[i - 1] + j); //Add each "missing" num to the array
j++;
}
} //end if
} //end else
} //end for
//Returns any missing numbers, assuming that lowerBoundary is the
//intended first number in the sequence.
return mia;
}
<div id="log"></div> <!-- Just used to display the demo code -->