Quick actions

cmd+k|ctrl+k

Navigation

Languages

First  Recurring Character

Snippet info

Language

JavaScript

Visibility

public

Author

kishorrathva8298

Created

2022-03-31T22:23:47.862227Z

Updated

2022-03-31T22:24:06.762698Z

// Google Question
// Given an array = [2,5,1,2,3,5,1,2,4];
// It should return 2

// Given an array = [2,1,1,2,3,5,1,2,4];
// It should return 1

// Given an array = [2,3,4,5];
// It should return undefiened

const firstRecurringCharacter = (array) => {
  const map = new Map();
  let first;
  for (let i = 0; i < array.length; i++) {
    let count = map.get(array[i]) | 1;
    if (!map.get(array[i])) {
      map.set(array[i], count);
    } else {
      if (!first) {
        // At this point we know which is the first recurring character,
        //  so it doesn't matter if we add anything in first variable
        // and we can use it to store the actual character
        first = array[i];
        break;
      }
      first = count + 1;
      map.set(array[i], count + 1);
    }
  }
  return first;
};
console.log(firstRecurringCharacter([2, 1, 1, 2, 3, 5, 1, 2, 4]));
console.log(firstRecurringCharacter([2, 5, 1, 2, 3, 5, 1, 2, 4]));
console.log(firstRecurringCharacter([2, 3, 4, 5]));
INFO