JavaScript job interview question – Find first non repeated character in string

js-code-interview

There are several way to code this puzzle. Some of them are time intensive and some of them are space intensive.

I’ll solve it here using javascript array (hash table in computer science term).

Sample Input & output:

java => j
python => (nothing)
php => h
angularjs => n
aabb => (nothing)

Programming Logic

  • Scan whole string and store each character in “hash table” as key with their initial value = 0
  • If character is already stored into “hash table”, increment its value. (i.e 1)
  • If at-least one character repetition found, set flag (i.e atleast_one_found = true)
  • Now scan hash table in-case above atleast_one_found = true.
  • whenever first hash key value=0 found, return that key as first non-repeated character.

Code

HTML Form to get input string.

<div>
    <h2>First Non Repeated Char</h2>
    <label for="input_string">Enter String</label>
    <input type="text" name="input_string" id="input_string" />
    <input type="button" value="Find" onclick="findFirstNonRepeatedChar('input_string')" />
</div>

JavaScript to find first non repeated character in string

function findFirstNonRepeatedChar(input_string) {

    var str = document.getElementById(input_string).value;
    if (str.length == 0) {
        alert('Empty String');
        return;
    }
    var hash = [];
    var atleast_one_found = false;
    var string_chars = Array.prototype.slice.apply(str);

    for (var i in string_chars) {
        if (typeof (hash[string_chars[i]]) != "undefined") {
            hash[string_chars[i]]++;
            atleast_one_found = true;
        } else {
            hash[string_chars[i]] = 0;
        }
    }
    if (atleast_one_found) {
        for (var j in hash) {
            if (hash[j] == 0) {
                alert('First non repeated char found => ' + j);
                return;
            }
        }
    }
    alert('No non-repeated char found');
}

Final Output

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

AJAX style multiple images upload using HTML5, JSON and jQuery

Next Post

Simple HTML5 geolocation plugin using jQuery

Related Posts