HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Find first unique number from array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uniquenumberarrayfirstfindfrom

Problem

I was asked to create a function that return first UNIQUE integer from given array of integers. In a case of success the function return the unique number in a case of failure return -1. The complexity should be \$O(n \log(n))\$. How can this be improved?

function solution(A) {

    var returnNumber = -1;
    var tempArray = new Array();;

   for(i=0; i < A.length; i++){

      var newIndex = A[i];
     if( tempArray[newIndex] === undefined){
        tempArray[newIndex] = 1;
     }
     else{
        tempArray[newIndex] += 1;
     }
    }
   for(j = 0; j < A.length; j++){
     if(tempArray[A[j]] == 1){
       returnNumber = A[j];
       break;
     }
   }
    return returnNumber;
}

//var A =  [1, 4, 3, 3, 1, 2, 0, 0]; //returns 4
var A =  [22, 25, 3, 3, 1, 2, 0, 0,100,22,25,1,2]; // returns 100
solution(A)

Solution

I like your answer. It looks a bit like a counting sort, which is very fast. I expect it's faster than a few of the other answers, although Joseph's answer is cleaner and more readable for sure. If I'm not mistaken your implementation is O(n) (which is excellent).

A couple (minor) things:

Using a dictionary/ hashtable would make more sense than using an array to store the frequency of each number. I'm not sure if creating an array then setting the 10,000th index (eg, if var A=[10000, 1, 1, 5]) as something takes a lot of memory (I don't use js a lot).

if( tempArray[newIndex] === undefined){


can just be

if(!tempArray[newIndex]){


Formatting. Your indentation is all over the place. This is probably due to the copy paste into the text box, but if not this is the biggest thing to make your code more readable.

You have 2 semi-colons:

var tempArray = new Array();;


Lastly, a few comments and better variable names could really help. "A" should be something more descriptive. Ps: The variable A in

function solution(A) {


doesn't have to be the same name as

var A =  [22, 25, 3, 3, 1, 2, 0, 0,100,22,25,1,2]; // returns 100
solution(A)


Though it works fine if it's the same name. I wasn't sure if this was a coincidence or because you didn't know this, but I thought I'd mention it.

That's about all from me... I don't code a lot in js, so any comments are welcome if I've made mistakes above (but I think most of it's pretty applicable).

Code Snippets

if( tempArray[newIndex] === undefined){
if(!tempArray[newIndex]){
var tempArray = new Array();;
function solution(A) {
var A =  [22, 25, 3, 3, 1, 2, 0, 0,100,22,25,1,2]; // returns 100
solution(A)

Context

StackExchange Code Review Q#97031, answer score: 6

Revisions (0)

No revisions yet.