Get first unique element of string

Problem: Suppose you are given a string and your task is to find the first unique element of that string.
str = “bcdadbdcfd”
Ruby Way:

def first_uniq(str)
  a =  diff = []
  dup = [] #seperate array assigned due to by reference assignemt
  s.each_char { |c|  
     a.include?(c) ? dup << c : a << c
  diff = a - dup

JavaScript Way[1]:

var string = "bcdadbdcfd"; // answer should be a

var arr = string.split("");
var occurences = {};
var lowestindex = string.length+1;

arr.forEach( function(c){  // runs for O(n)
  tmp = c;
  if( typeof occurences[tmp] == "undefined")
    occurences[tmp] = tmp;
    occurences[tmp] += tmp;

for(var p in occurences) { // again for O(n)
  if(occurences[p].length == 1)
    lowestindex = Math.min(lowestindex, string.indexOf(p));

if(lowestindex > string.length)
  alert( 'no unique');

alert( string[lowestindex]);

[1] purposed by Jamshed Ahmed


I am Senior Software Engineer. I love reading, writing, sharing,developing, hiking, movies, trips, mountains, brooks, hills etc.

Tagged with: , ,
Posted in Interview questions, Javascript, Ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: