The question

Find the first non-repeated (unique) character in a given string.

My answer

At first glance I am tempted to start from the left and add each character go to a hashtable with the number of times I have seen it. Once I have gone through the whole string I will do it again now searching for the first character that returns 1.

This seems to be the right solution so lets look at the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function checkFirstNonRepeated(word) {
  var map = {};

  for (var i = 0; i < word.length; i++) {
    if (undefined === map[word[i]]) {
      map[word[i]] = 1;
    } else {
      map[word[i]]++;
    }
  }

  for (i = 0; i < word.length; i++) {
    if (1 === map[word[i]]) {
      return word[i];
    }
  }
}

function test() {
  if (checkFirstNonRepeated('asdfasdf') === undefined) {
    console.log('success');
  }

  if (checkFirstNonRepeated('asdfasd') === 'f') {
    console.log('success');
  }
}

test(); // Prints success twice
[ computer_science  algorithms  javascript  programming  ]
B-Trees - Database storage internals
Programming Concurrency in Rust
Introduction to Rust
Introduction to HTML Canvas
React refs