Find the element that appears once in sorted array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have a sorted array of literals like this −

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];

We are required to write a JavaScript function that takes in one such array and returns the first number that appears only once in the array. If there is no such number in the array, we should return false.

For this array, the output should be 6

Example

Following is the code −

const arr = [2, 2, 3, 3, 3, 5, 5, 6, 7, 8, 9];
const firstNonDuplicate = arr => {
   let appeared = false;
   for(let i = 0; i < arr.length; i++){
      if(appeared){
         if(arr[i+1] !== arr[i]){
            appeared = false;
         };
      }else{
         if(arr[i+1] === arr[i]){
            appeared = true;
            continue;
         };
         return arr[i];
      };
   };
   return false;
};
console.log(firstNonDuplicate(arr));

Output

Following is the output in the console −

6
raja
Published on 15-Sep-2020 15:31:35
Advertisements