Here is a practice question I am solving:
Write a function to find the first non-repeated character in a string. For instance, the first non-repeated character in 'total' is 'o' and the first non-repeated character in 'teeter' is 'r'.
How can I improve the efficiency of this algorithm?
function repeater(string){
var charCount = {};
for(var i = 0; i < string.length; i++){
if(charCount[string[i]]){
charCount[string[i]] = 'More Than One';
} else {
charCount[string[i]] = 'One Time';
}
}
for(var j = 0; j < string.length; j++){
if(charCount[string[j]] === 'One Time'){
return string.charAt(j);
}
}
return 'Everything is repeated';
}
I also solved this using a nested loop:
var nonRepeater = function(str) {
var index = [];
var count;
str.split('').forEach(function(letter, i) {
count = 0;
str.split('').forEach(function(latter) {
if (letter === latter) {
count += 1;
}
});
index.push(count);
});
// console.log(index.indexOf(1));
return str[index.indexOf(1)];
};
I am in the process of learning about Big-O Notation and from my understanding, worst case scenario these both have the same run time O(n2).
I am trying to find a way to increase the efficiency of this algorithm. I am toying with ways to use a RegEx.
Does anyone know how to write this more efficiently in JavaScript? I have found a few guides in C but I do not know the language at all. I haven't found much help on this in JavaScript.
charCount[string[j]] === 'One Time'
on each index is probable slower thanmultiple[string[j]] === true
– Rodolfo 3 hours agoR
example here), this would be (rle is "run-length encoder" )foo<- rle(sort(my.data)); bar<- foo$values[foo$lengths==1][1]; which(my.data==bar)
– Carl Witthoft 2 hours ago