code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

02 First Not Repeating Character

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
 * Given a string s consisting of small English letters, find and return the first instance 
 * of a non-repeating character in it. If there is no such character, return '_'.
 * 
 * Example
 * 
 * For s = "abacabad", the output should be
 * firstNotRepeatingCharacter(s) = 'c'.
 * 
 * There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears
 * in the string first
*/

function firstNotRepeatingCharacter(value) {
  if(!value) return '_'
  let charDict = {};cd 
  for (const char of value) {
    if(!charDict[char]){
      charDict[char] = 1
    } else {
      charDict[char] += 1
    }
  }
  for (const key in charDict) {
    if (charDict[key] === 1) {
      return key
    }
  }
  return '_'
}

test('first Not Repeating Character', () => {
  expect(firstNotRepeatingCharacter('abacabad')).toEqual('c')
});

Created 2020-03-31T14:01:50+00:00 · Edit