code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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