Javascript integer encoding is missing

Write a function:

function solution(A); 

      

which, given a non-empty null-indexed array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given:

A[0] = 1   
A[1] = 3   
A[2] = 6   
A[3] = 4   
A[4] = 1   
A[5] = 2

      

the function should return 5. Suppose that:

β€’ N is an integer within the range [1..100,000]; β€’ each element of array A is an integer within the range

      

[- 2,147,483,648..2,147,483,647].

Complexity:     β€’ expected worst-case time complexity - O (N); β€’ the expected worst-case complexity of space is O (N), outside of the storage of input (not counting the storage required for input arguments).

My answer is 100% WRONG! What's wrong with it? First let me point out the obvious mistakes

  • return value - I return 0 because there is no indication of what to return if an integer is missing.

The assumptions I made may be wrong

  • returns the smallest positive integer (greater than 0) that does not occur in A. Here I am not checking for negative values

my code, which works on its own test cases, and works on negative numbers too, got 0%.

function solution(A) {

    // write your code in JavaScript (Node.js 0.12)
    A.sort();
    var a_length = A.length;

    for(var i = 0; i < a_length; i++){

        // if i is 0 - 1 = -1 then do not do the following
        // if i is 1 - 1 - 0 then do the follow
        // if i >= 0 then do the following
        if(i - 1 >= 0){

            // remember above there is a A.sort() so it 
            // looks like this
            // A[0] = 1
            // A[1] = 1
            // A[2] = 2
            // A[3] = 3
            // A[4] = 4
            // A[5] = 6

            // if A[1] is 1 and A[1-1 = 0] is 1 then this is 1>1 false 
            // if A[2] is 2 and A[2-1 = 1] is 1 then this is 1>1 false  
            // if A[3] is 3 and A[3-1 = 2] is 2 then this is 1>1 false  
            // if A[4] is 4 and A[4-1 = 3] is 3 then this is 1>1 false  
            // if A[5] is 6 and A[5-1 = 4] is 4 then this is 2>1 true return A[i - 1] + 1 where A[5 - 1 = 4] is 4 + 1 is 5. 5 is returned.
            if(A[i] - A[i - 1] > 1){
                return A[i - 1] + 1;
            }
        }
    }

    // this does not check for negative
    // returns the minimal positive integer (greater than 0
    // this is a return no minimal positive integer found
    return 0;
}

      

Everything is wrong, example of test result:

simple simple test 0.072 s WRONG ANSWER received 3 expected 1

Why does this work for me and not for them.

+2


source to share


20 replies


function solution(A) {
        var min = 1;
        A.sort(function(a,b){
           // Sort the array explicit way
           return a - b; 
        });

        for (var i in A) {
            if (A[i] > -1 && A[i] == min) {
                    min++;
            }
        }

        return min;
}

      



+15


source


There is my JavaScript solution for Codility MissingInteger (got 100/100)



function solution(A) {
    const len = A.length;
    const hash = {};
    for (let i = 0; i < len; i++) {
        // here we are making an object with all 
        // numbers in a given array as object keys and values
        // if 0 is given as possible digit we could assing 
        // hash[A[i]] = true; or any truthy value
        hash[A[i]] = A[i];
    }
    for (let i = 1; i < 1000002; i++) {
        // here we are trying to find any number 
        // between 1 and 1000001 (given constraints) 
        // which do not exists in an object
        // if the number is not in the object that our missing one
        if(!hash[i]) return i;
    }
    return 1;
}

      

+8


source


function solution(A) {
        A.sort(function(a,b){
           // Sort the array explicit way
           return a - b; 
        });
        return A.reduce((prev, next)=> {
            if(next > -1 && next === prev) {
                prev++;
            }
            return prev;
        }, 1);
     ;
}
      

Run codeHide result


+3


source


function solution(A) {
// write your code in JavaScript (Node.js 6.4.0)
var b = A.sort(function(a,b){return a-b});
var length = b.length;
var min = b[0];
var max = b[length-1];
if (max<=0){return 1;}
if (min<=0 && max==1){return 2;}
if (min>1){return 1;}
if (min >=0){
    for(var i=0; i<length; i++){
       if(b[i+1]- b[i] > 1){
           return b[i]+1;
       }
    }
}
if (min<=0 && max>=0){
    for(var i=0; i<length; i++){
        if(b[i]>0 && b[i-1]<=0){
            if(b[i]-0>1){
               return 1; 
            }
            if(b[i+1]-b[i]>1){
                return b[i]+1;
            }
        }
        if(b[i]>0){
            if(b[i+1]- b[i] > 1){
               return b[i]+1;
            }
        }
    }
}
return max+1;

      

}

+2


source


My JS solution got 100 across the board. Basically, I generate a new array, keyed by the values ​​of the original array, and set each one to some kind of true value. This does two things: it takes negative values ​​out of the loop to iterate over the new array, and it also allows you to loop from the smallest value and return the first index, which gives you an undefined value.

function solution(A) {
    orderedArr = [];
    for (let i = 0; i < A.length; i++) {
        if (!orderedArr[A[i]]) {
            orderedArr[A[i]] = true;
         }
    }
    if (orderedArr.length === 0) return 1;
    for (let i = 1; i < orderedArr.length; i++) {
        if (!orderedArr[i]) {
            return i;
        }
    }
    return orderedArr.length;
}

      

+2


source


For this problem, I would like to start by sorting a given array. Then I iterate over the sorted array decrementing. I give to reduce the accumulator acc

initially equal 1

(what 1 after the decimal point for). Only when the cell val

is equal to the battery do I increase the battery. Otherwise, I return the accumulator as is. When I can no longer find an element in the array that is equal to the accumulator, that accumulator is the lowest missing positive integer.

const solution = A => {
    A.sort((a, b) => a - b);
    return A.reduce((acc, val) => acc === val ? acc + 1 : acc, 1);
}

      

I know this question has been around a long time ago, but I hope this answer is useful to someone. In this answer, I'm using Array.prototype.sort () , Array.prototype.reduce () and ternary . Knowing these patterns should provide a deeper understanding of this answer.

+1


source


Try something like this:

// Array containing your numbers
var Arr = [1, 3, 6, 4, 1, 2];
solution(Arr);

function solution(Arr) {
    var len = Arr.length;
    var min = 100001;
    var num;

    // check if it is empty
    if (len == 0) {
        alert('Empty zero-indexed array given');
    }

    // find array min number
    for(var i = 0; i < len; i++) {
        if (Arr[i] < min) {
            min = Arr[i];
        }
    }

    for (var i = 0; i < 100000; i++) {
        var x = Arr.indexOf(min);
        if (x == -1) {
            num = min;
            break;
        }
        min++;
    }

    alert('Min value in array is: ' + num);
}

      

Here is a working Jsfiddle demo .

0


source


I think your solution was wrong because you were using sort. Sorting is an O (n * log (n)) operation, and they asked for a solution that has both O (n) time and space complexity.

0


source


My decision:

function solution(A) {
// write your code in JavaScript (Node.js 6.4.0)
var B = A.sort(function(a,b){return a-b});
if(A.length == 1) {
    if(A[0] > 0) {
        if(A[0]>1) {
            return 1
        } else {
            return A[0]+ 1;    
        }
    } else {
        return 1   
    }
} else if(A.length > 1) {
    let max = Math.max.apply(null,A);
    let min = Math.min.apply(null,A);
    if(max > 0) {
        if(B[0]-0 > 1) { //for arrays that have a minimum higher than 1
            return 1
        }
        for(i=0;i<B.length-1;i++) { 
            if(B[i+1]- B[i] > 1){ //check the difference between next and current number, we also ignore the case of [x,-1,1,x2], since if a 0 is omitted, 1-(-1) will make 0 the highest missing number
                if(B[i] == -1 && B[i+1] == 1) {
                    //do nothing
                } else {
                    if(B[i]>0) {
                        return B[i]+1; //if the first number is positive, we can say the number after it is the smallest possible integer
                    } else {
                        return 1
                    }
                }   
            } 
        }
        return max + 1;
    } else {
        return 1
    }

} else {
    return null;
}
}

      

0


source


I got 100% of this solution

function solution(A) {
    let  sortedOb={};
    let biggest=0;
    A.forEach(el=>{
        if(el>0)
        {
             sortedOb[el]=0;
              biggest =  el>biggest? el:biggest
        }
    });
    let arr = Object.keys(sortedOb).map(el=>+el);
    if(arr.length==0)
    return 1;
    for(let i = 1; i<=biggest; i ++){
        if(sortedOb[i] === undefined)
        return i
    }
    return biggest+1
}

      

0


source


You can try this: I used C #

static void Main(string[] args)
{

    int[] tempArray = new int[1000000];
    int[] givenArray = new int[] { 1, 2,3};   // or     { 1, 2,6,4,3}

    int results = myFunction(tempArray, givenArray);
    Console.WriteLine(results);
    Console.ReadKey();
}

private static int myFunction(int[] tempArray, int[] givenArray)
{
    int res = 0;

    for (int x = 1; x < tempArray.Length; x++)
    {

        if (!givenArray.Contains(x))
        {
            tempArray[x] = x;
        }
    }

    for (int y = 0; y < tempArray.Length; y++)
    {
        if (tempArray[y] > 0)
        {
            res = tempArray[y];
            break;
        }
    }
    return res;
}

      

0


source


another way to do it ::

  1. Sort the array and get the least significant digit of the array.

  2. Increase the least significant digit and check if it already exists.

  3. Return the smallest positive number.

Got it !!

//var A =[1,3,4,10];
var i =0;
var solution = function(A) {
var min = 0;
var max = 0;
sortedArray = A.sort(function(a, b){return a-b});
min =sortedArray[0]; //min value
max =sortedArray[sortedArray.length-1];//max value in array

if(min < 0){
alert("min is 1"); //use return 1
}
else if(min > 0){
for(;i<sortedArray.length;i++){
x = checkifNoExists(min+i+1);//start checking the no. with min  
if(x){
    var lowest = min+i+1
    break;
}
}
alert(lowest);//use return lowest
}
}
checkifNoExists = function(no){//to check if no exists in array
for(var y = 0;y<sortedArray.length;y++){
if(sortedArray[y] == no){
var found = no
}
}
if(found == "" || found == undefined){
return true;
}else{
return false;
}   
}       

      

0


source


I tried to implement a JavaScript solution similar to the one I used in Java and realized that native Array.sort()

JavaScripts lacked performance ...

I used the RadixSort implementation from @ Blindman67 for array sorting and a simple loop and typed 100/100 @O (N) or O (N * log (N)).

function solution(A) {
    A = radixSort(A);
    let min = 1;
    for (let i = 0; i <= A.length; ++i) {
      if (A[i] == min && min <= A.length) {
        min++;
      }
    }
    return min;
}

// RadixSort by: https://codereview.stackexchange.com/users/120556/blindman67
function radixSort(numbers) {
  function emptyBuckets() {          // empties buckets and adds contents back to workArray
    workArray.length = 0;
    for (i = 0; i < 10; i += 1) {   // could have used buckets forEach but this is quicker on average
      if (buckets[i].length > 0) {
        workArray.push(...buckets[i]);
        buckets[i].length = 0;
      }
    }
  }

  var i;                  // hoist declarations
  const results = [];     // array that holds the finnal sorted numbers
  const buckets = [[], [], [], [], [], [], [], [], [], []];  // buckets
  const workArray = [...numbers]; // copy the numbers
  var power = 0;                  // current digit as a power of ten
  var tenPow = 1;                 // ten to the power of power
  if (numbers.length <= 1) {        // if one or no items then dont sort
    return workArray;           // dont sort if there is no need.
  }
  // as numbers are sorted and moved to the result array the numbers
  while (workArray.length > 0) {
    for (i = 0; i < workArray.length; i += 1) { // for all numbers still being sorted
      if (workArray[i] < tenPow) {            // is the number samller than the current digit
        results.push(workArray[i]);         //Yes it is sorted then remove a put o nthe result array
      } else {
        // add to bucket. Use Math.floor and save complexity doing it in one statement line
        buckets[Math.floor(workArray[i] / tenPow) % 10].push(workArray[i]);
      }
    }
    power += 1;
    tenPow = Math.pow(10, power);
    emptyBuckets();
  }
  return results;
}

      

0


source


My swift 3 solution (100/100)

public func solution(_ A : inout [Int]) -> Int {
  let set = Set(A)
  var value = 1
  while true {
    if !set.contains(value) {
      return value
    }
    value += 1
  }
}

      

0


source


This was my solution, which scored 66% on the scale of tasks, 100% on correctness and only 25% on performance. Not the most efficient solution, but a working one nonetheless.

  1. It is checked first to make sure the largest number in the array is greater than 0, if not, we end up with a result of 1
  2. Loop over numbers from 1 to largest number in an array
  3. If this number has no index in the array, this is our result
  4. If all numbers from 1 to the highest in the array are present, the next largest number is the result
const test1 = [1, 3, 6, 4, 1, 2]; // Returns 5
const test2 = [1, 2, 3]; // Returns 4
const test3 = [-1, -3]; // Returns 1

function solution(A) {
  const lowestNum = Math.min.apply(Math, A);
  const highestNum = Math.max.apply(Math, A);

  // Check highestNum to make sure it over 0
  if (highestNum > 0) {
    // Loop through all the numbers from 1 to the highes in the array
    for (var i = 1; i < highestNum; i++) {
      // If i does not have an index in the array, that our solution
      if (Number(A.indexOf(i)) === -1) {
        return i;
      }
    }
    // If looped through array and all have an index, the next number is our answer
    return i + 1;
  } else {
  // If highestNum is not over 0, answer is 1
    return 1;
  }
}

solution(test1);

      

JS Fiddle demo

0


source


Using Javascript, I did it in a rather weird way, but got 100% on score, correctness, and performance. However, I got O (N) or O (N * log (N)). So, I would like to bring this down.

function solution(A){
    // remove all negative and zero 
    let positiveArray = A.filter(x => x > 0);
    // sort all positive values
    let sortedArray = positiveArray.sort((x,y) => x-y);
    // return first that doesn't appear in order
    return sortedArray.reduce((prev, next) => {
        if(next === prev){
            prev++
        }
        return prev;
    },1);
}

      

0


source


function solution(A){
    A.sort((a, b) => a-b);
    let int = 1;
    for(let i = 0; i < A.length; i++){

        if(A[i] > 0 && A[i] === int){
            int++;
        } else if (A[i] > 0 && A[i] > int){
            return int;
        }
    }
    return int;
}

      

0


source


Problem score: 100% Correctness: 100% Performance: 100%

function solution(A) {
    // write your code in JavaScript (Node.js 8.9.4)

    let map = {};
    A.map(x => { map[x] = x; return x });

    let result = 1;
    while (true) {
        if (!map[result]) return result;
        result++;
    };
}

      

0


source


This is the solution I tried during my test. Not as optimized, but simple enough to read.

Idea:

  • Create a loop that will start at 1 as we are only looking for a positive integer
  • For each iteration, check if the current number is available in the array.
  • If not, abort the cycle.

function solution(arr) {
  let i;
  let num = 1;
  for (i = 1; i <= arr.length; i++) {
    let exists = arr.some((n) => n === i);
    if (!exists) {
      num = i;
      break;
    }
  }
  return num;
}

console.log(solution([2, 3, 4, 5, 5]))

console.log(solution([2, 3, 4, 5, 5, 1]))
      

Run codeHide result



Solution 2 using hashmap:

This is a more efficient and more recommended solution.

  • Loop through the array and create a hashmap of the values. This will remove duplicates and also make searching easier.
  • Also create a variable max

    and calculate the maximum value in the array.
  • Now cycle from 1 to max.
    • If no value is found, return the index.
    • If all values ​​are present, return max + 1

function solution(arr) {
  let max = 0;
  const hashMap = arr.reduce((map, num) => {
    map[num] = true;
    max = max > num ? max : num;
    return map
  }, {});
  
  for(let i = 1; i <= max; i++) {
    if (!hashMap[i]) return i
  }
  return max + 1;
}

console.log(solution([2, 3, 4, 5, 5]))

console.log(solution([2, 3, 4, 5, 5, 1]))
      

Run codeHide result


0


source


function solution(A) {
var swap = function(i, j) {
    var tmp = A[i];
    A[i] = A[j];
    A[j] = tmp;
};
for (let i = 0; i < A.length; i++) {
    while (0 < A[i] && A[i] - 1 < A.length
            && A[i] != i + 1
            && A[i] != A[A[i] - 1]) {
        swap(i,A[i] - 1);
    }
}
for (let i = 0; i < A.length; i++) {
      if (A[i] != i + 1) {
         return i + 1;
      }
   }
return A.length + 1;
}

      

Here is the final solution you are looking for

0


source







All Articles