How can I log the index of each array item? - javascript

I'm a beginner and struggling with this exercise. Can anyone tell me why the console is logging the index of both characters as 1. I want it to log the character 'a' every time it appears in the word. So for example, if we ran the function with the word ‘Saturday’ and ‘a’ as below, it should log an array [1,6]. Instead it is logging [1, 1].
const subLength = (word, letter) => {
let wordArray = word.split("");
let indexArray = []
for (i = 0; i < wordArray.length; i++) {
if (wordArray[i] === letter) {
indexArray.push(wordArray.indexOf(letter));
}
}
console.log(indexArray);
}
subLength('Saturday', 'a');

You could take the index i from the loop directly.
String#indexOf returns the first found index, but if you take an index as second parameter it searches from this position.
const subLength = (word, letter) => {
let wordArray = word.split("");
let indexArray = [];
for (let i = 0; i < wordArray.length; i++) { // take let here too
if (wordArray[i] === letter) {
indexArray.push(i);
}
}
console.log(indexArray);
}
subLength('Saturday', 'a');
An approach without using split.
const
subLength = (word, letter) => {
let indexArray = [];
for (let i = 0; i < word.length; i++) {
if (word[i] === letter) indexArray.push(i);
}
console.log(indexArray);
};
subLength('Saturday', 'a');

A simpler method would be to filter over the indexes.
const subLength = (word, letter) => [...Array(word.length).keys()]
.filter(i => word[i] === letter);
console.log(subLength('Saturday', 'a'));

Related

Why is my nested loop only finding one duplicate character in a string?

My apologies if this is a duplicate, I couldn't find an answer after searching for a while on Stackoverflow.
I am trying to use a nested loop to find any duplicate characters in a string.
So far, all I can manage to do is to find one duplicate the string.
For example, when I try the string "aabbcde", the function returns ['a', 'a'], whereas I was expecting ['a', 'a', 'b', 'b'].
I obviously have an error in my code, can anybody help point me towards what it could be?
const myStr = "aabbcde";
function duplicateCount(text){
const duplicates = [];
for (let i = 0; i < text.length; i++) {
for (let j = 0; j < text[i].length; j++) {
if (text[i] === text[j]) {
duplicates.push(text[i]);
}
}
}
return duplicates;
}
duplicateCount(myStr);
It should be something like this.
issues in this loop for (let j = 0; j < text[i].length; j++)
const myStr = "aabbcde";
function duplicateCount(text){
const duplicates = [];
for (let i = 0; i < text.length; i++) {
for (let j = i+1; j < text.length; j++) {
if (text[i] === text[j]) {
duplicates.push(text[i]);
}
}
}
return duplicates;
}
console.log(duplicateCount(myStr));
Using nested loop will make it very hard to do it,we can use a Object to store the appear count,and then filter the count
const myStr1 = "aabbcde";
const myStr2 = "ffeddbaa";
const duplicateCount = str => {
let map = {}
for(c of str){
map[c] = (map[c]??0) + 1
}
let result = []
for(m in map){
if(map[m] <= 1){
continue
}
result.push(...Array(map[m]).fill(m))
}
return result
}
console.log(duplicateCount(myStr1))
console.log(duplicateCount(myStr2))
You can simply achieve the result you're looking for by creating an object map of the string (meaning each key of the object will be each unique character of the string and their associated values will be the number of times each character is repeated in the string).
After you create an object map of the string, you can loop through the object and check if each value is greater than one or not. If they're you would push that item into a result array by the number of times the character is repeated. Please find my code here:
const myStr = 'aabbcde';
const duplicateCount = (str) => {
const result = [];
const obj = {};
str.split('').map((char) => {
obj[char] = obj[char] + 1 || 1;
});
for (key in obj) {
if (obj[key] > 1) {
for (let i = 0; i < obj[key]; i++) {
result.push(key);
}
}
}
return result;
};
console.log(duplicateCount(myStr));

Calculate duplicated letters next to each other

I need to calculate pairs of same letters that stay each other in twos, I got this code
const calculateLetters = (text: string) => {
const arrayStr = [...text];
let count = 0;
for (let i = 0; i < arrayStr.length; i++) {
if (arrayStr[i] === arrayStr[i + 1]) {
count += 1;
}
}
return count;
};
console.log(calculateLetters('ABBAAA'));
But now it returns 3, what I need to do is make count equal 2, because I need to calculate pairs of same letters.
In your if statement, if you've found a pair, then iterate till the point your i+1th element is not same as ith element, and then count again.
You can accomplish this with RegEx The below pattern will count matches of the same character pairs.
const countPairs = (text) => {
//Grab the matches length if any exist, otherwise return 0
return (text.match(/(.)\1/g))?.length ?? 0
}
console.log(countPairs("abc")) //Result is 0
console.log(countPairs("ABBAAA")) //Result is 2
console.log(countPairs("aabBccDD111")) //Result is 4
With your code, you just need to move past the match when you find one
const calculateLetters = (text) => {
const arrayStr = [...text];
let count = 0;
for (let i = 0; i < arrayStr.length; i++) {
if (arrayStr[i] === arrayStr[i + 1]) {
count += 1;
//move past the match
i++;
}
}
return count;
};
console.log(calculateLetters('ABBAAA'));
const calculateLetters = (text: string) => {
const arrayStr = [...text];
let count = 0;
for (let i = 0; i < arrayStr.length; i++) {
let j = i;
while(i + 1 < arrayStr.length && arrayStr[i] === arrayStr[i + 1]) {
i+= 1;
}
if(i != j){
count += 1;
}
}
return count;
};
console.log(calculateLetters('ABBAAA'));
Define a zip function that can be used to create a list of pairs of adjacent letters in the text. Then count the pairs that match.
Since you want unique adjacent letters, pass the pairs through a Set before counting.
const zip = (a, b) => a.map((k, i) => [k, b[i]])
const calculateLetters = (text) => {
const chars = [...text]
const adjacentLetters = zip(chars, chars.slice(1))
const uniqueAdjacentLetters = [
...new Set(adjacentLetters.map(([a,b]) => `${a}:${b}`))
].map(x => x.split(':'))
const count = uniqueAdjacentLetters.reduce(
(total, [a,b]) => total + ((a === b) ? 1 : 0),
0,
)
return count
}
console.log(calculateLetters('ABBAAA'))

Multiple of letters count in js

i have a task:
Count the number of letters “a” in text
Count the number of letters “o” in text
Write the result of multiplying the number of letters “a” and “o”.
is it possible to solve this task in a shorter way??
function countString(str, letter) {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
count += 1;
}
}
return count;
}
const string = hello my name is Ola.toLowerCase()
const letterToCheck = "o"
const letterToCheckTwo = "a"
const result = countString(string, letterToCheck);
const resultTwo = countString(string, letterToCheckTwo);
const total = result + resultTwo
console.log(total)
With regular expression function match() will output all the matched conditions.
const string = "hello my name is Ola"
const numberOfA = string.match(/a/gi);
const numberOfO = string.match(/o/gi);
console.log(numberOfA.length * numberOfO.length)
you can do something like this using map filter and reduce
const calculate = (string, letters) => letters
.map(l => string.split('').filter(c => c === l).length)
.reduce((res, item) => res * item)
const string = 'hello my name is Ola'.toLowerCase()
console.log(calculate(string, ['a', 'o']))
console.log(calculate(string, ['a', 'o', 'e']))
You can create an object that stores the count of all the characters and then you can compute the product using this object.
const str = "Avacado";
const charsCount = Array.prototype.reduce.call(
str,
(r, ch) => {
const lowerCh = ch.toLowerCase()
r[lowerCh] ??= r[lowerCh] || 0;
r[lowerCh] += 1;
return r;
},
{}
);
console.log(charsCount["o"] * charsCount["a"]);
Note: Array.prototype.reduce is a generic method, so it can be used with a string as well.
There are a few different approaches. In this post I've programmed in a way that allows you to expand to different letters, different amounts of letters, and different strings easily. There may be better approaches if your problem never needs to change.
In your current code, your are traversing the strings twice and counting the occurrences of the letter within them. You could easily pass the function an array and only traverse the string once:
function countString(str, letters) {
//rather than being a character, letter is now an array of characters
let count = 0;
for (let i = 0; i < str.length; i++) {
if (letters.includes(str.charAt(i))) {
count += 1;
}
}
return count;
}
const string = "hello my name is " + Ola.toLowerCase()
const lettersToCheck = ["o", "a"]
const result = countString(string, lettersToCheck);
//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i++){
product *= result[i];
}
console.log(product);
Rather than iterating over the strings, however, a different approach is to use regular expressions and .match(). This approach has fewer iterations, although I'm not sure about the low level efficiency, since lots of the comparison is encapsulated by .match():
function countString(str, letters) {
//iterates over the array of letters rather than the string
for (var i = 0; i < letters.length; i++){
count += (str.match(new RegExp(letters[i], "g")) || []).length;
}
return count;
}
const string = "hello my name is " + Ola.toLowerCase()
const lettersToCheck = ["o", "a"]
const result = countString(string, lettersToCheck);
//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i++){
product *= result[i];
}
console.log(product);
If regex is too much, you could also use .split() to iterate over the characters rather than the string:
function countString(str, letters) {
//iterates over the array of letters rather than the string
for (var i = 0; i < letters.length; i++){
count += str.split(letters[i]).length - 1;
}
return count;
}
const string = "hello my name is " + Ola.toLowerCase()
const lettersToCheck = ["o", "a"]
const result = countString(string, lettersToCheck);
//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i++){
product *= result[i];
}
console.log(product);
See this post for more information
You can compute the letter frequency each time the phrase changes and then request the product by specifying the letters in the frequency map.
const letterFrequencyMap = (str) =>
str.toLowerCase().split('').reduce((acc, k) =>
acc.set(k, (acc.get(k) ?? 0) + 1), new Map);
const computeProduct = (freq, ...keys) =>
keys.reduce((product, k) => product * (freq.get(k) ?? 1), 1);
// Main
const phrase = "It's about to be noon in a bit.";
const freq = letterFrequencyMap(phrase);
// a = 2; o = 4
console.log(computeProduct(freq, 'a', 'o')); // 8

remove duplicate character in string and make unique string

I wrote a code and it works fine, But is there any easy and more handy way to implement that using javascript RegExp Object or any other way ?
function removeDuplicateChar(str) {
var temp = [], j = 0;
var arr = str.split("");
arr.sort();
for(var i = 0; i < arr.length-1; i++) {
if(arr[i] != arr[i+1]) {
temp[j++] = arr[i];
}
}
temp[j++] = arr[arr.length-1];
for(var i = 0; i < j; i++) {
arr[i] = temp[i];
}
return arr.join("").substring(0,j);
}
console.log(removeDuplicateChar("Rasikawef dfv dd"));
Do you like one liners? Minimal code can be very efficient. Compare the following:
With sets and list comprehension:
const remDup= e => [...new Set(e)].sort().join("");
console.log(remDup("Rasikawef dfv dd"))
With reduce:
const remDup= s=> s.split("").sort().reduce((a,b)=>(a[a.length-1]!=b)?(a+b):a,"")
console.log(remDup("Rasikawef dfv dd"))
With filter:
const remDup= s=> s.split("").filter((e,i,f)=>f.indexOf(e)==i).sort().join("")
console.log(remDup("Rasikawef dfv dd"))
With map:
const remDup= s=> s.split("").map((c,i,o)=>(o.indexOf(c)==i)?c:"").sort().join("")
console.log(remDup("Rasikawef dfv dd"))
let removeDuplicate = (string) => string.split("").reduce((s, c) => {
if (s) {
if (-1 == s.indexOf(c)) return s + c;
}
return s;
});
console.log(removeDuplicate("banana")); // => ban
console.log(removeDuplicate("Rasikawef dfv dd")); // => Rasikwef dv

return the first non repeating character in a string in javascript

So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.
The problem is I have an arbitrary string that I would like to return the first non repeating character. EX: 'aba' -> would return b
'aabcbd' -> would return c.
This is what I have so far, just a simple for loop to start.
var someString = 'aabcbd';
var firstNonRepeatedCharacter = function(string) {
for(var i = 0; i < someString.length; i++){
}
};
http://jsfiddle.net/w7F87/
Not sure where to go from here
You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:
function firstNonRepeatedCharacter(string) {
for (var i = 0; i < string.length; i++) {
var c = string.charAt(i);
if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
return c;
}
}
return null;
}
Demo: http://jsfiddle.net/Guffa/Se4dD/
If you're looking for the first occurrence of a letter that only occurs once, I would use another data structure to keep track of how many times each letter has been seen. This would let you do it with an O(n) rather than an O(n2) solution, except that n in this case is the larger of the difference between the smallest and largest character code or the length of the string and so not directly comparable.
Note: an earlier version of this used for-in - which in practice turns out to be incredibly slow. I've updated it to use the character codes as indexes to keep the look up as fast as possible. What we really need is a hash table but given the small values of N and the small, relative speed up, it's probably not worth it for this problem. In fact, you should prefer #Guffa's solution. I'm including mine only because I ended up learning a lot from it.
function firstNonRepeatedCharacter(string) {
var counts = {};
var i, minCode = 999999, maxCode = -1;
for (i = 0; i < string.length; ++i) {
var letter = string.charAt(i);
var letterCode = string.charCodeAt(i);
if (letterCode < minCode) {
minCode = letterCode;
}
if (letterCode > maxCode) {
maxCode = letterCode;
}
var count = counts[letterCode];
if (count) {
count.count = count.count + 1;
}
else {
counts[letterCode] = { letter: letter, count: 1, index: i };
}
}
var smallestIndex = string.length;
for (i = minCode; i <= maxCode; ++i) {
var count = counts[i];
if (count && count.count === 1 && count.index < smallestIndex) {
smallestIndex = count.index;
}
}
return smallestIndex < string.length ? string.charAt(smallestIndex) : '';
}
See fiddle at http://jsfiddle.net/b2dE4/
Also a (slightly different than the comments) performance test at http://jsperf.com/24793051/2
var firstNonRepeatedCharacter = function(string) {
var chars = string.split('');
for (var i = 0; i < string.length; i++) {
if (chars.filter(function(j) {
return j == string.charAt(i);
}).length == 1) return string.charAt(i);
}
};
So we create an array of all the characters, by splitting on anything.
Then, we loop through each character, and we filter the array we created, so we'll get an array of only those characters. If the length is ever 1, we know we have a non-repeated character.
Fiddle: http://jsfiddle.net/2FpZF/
Two further possibilities, using ECMA5 array methods. Will return undefined if none exist.
Javascript
function firstNonRepeatedCharacter(string) {
return string.split('').filter(function (character, index, obj) {
return obj.indexOf(character) === obj.lastIndexOf(character);
}).shift();
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
Or if you want a bit better performance, especially on longer strings.
Javascript
function firstNonRepeatedCharacter(string) {
var first;
string.split('').some(function (character, index, obj) {
if(obj.indexOf(character) === obj.lastIndexOf(character)) {
first = character;
return true;
}
return false;
});
return first;
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
I came accross this while facing similar problem. Let me add my 2 lines.
What I did is a similar to the Guffa's answer. But using both indexOf method and lastIndexOf.
My mehod:
function nonRepeated(str) {
for(let i = 0; i < str.length; i++) {
let j = str.charAt(i)
if (str.indexOf(j) == str.lastIndexOf(j)) {
return j;
}
}
return null;
}
nonRepeated("aabcbd"); //c
Simply, indexOf() gets first occurrence of a character & lastIndexOf() gets the last occurrence. So when the first occurrence is also == the last occurence, it means there's just one the character.
Here's a Solution using Regex to replace all repeating characters and then returning the first character.
function firstNonRepeat(str) {
// Sorting str so that all repeating characters will come together & replacing it with empty string and taking first character using substr.
var rsl = str.split('').sort().join('').replace(/(\w)\1+/g,'').substr(0,1);
if(rsl) return rsl;
else return 'All characters are repeated in ' + str;
}
console.log(firstNonRepeat('aaabcccdeeef'));
console.log(firstNonRepeat('aaacbdcee'));
console.log(firstNonRepeat('aabcbd'));
First of all, start your loop at 1, not 0. There is no point in checking the first character to see if its repeating, obviously it can't be.
Now, within your loop, you have someString[i] and someString[i - 1]. They are the current and previous characters.
if someString[i] === someString[i - 1] then the characters are repeating, if someString[i] !== someString[i - 1] then they are not repeating, so you return someString[i]
I won't write the whole thing out for you, but hopefully the thought process behind this will help
function FirstNotRepeatedChar(str) {
var arr = str.split('');
var result = '';
var ctr = 0;
for (var x = 0; x < arr.length; x++) {
ctr = 0;
for (var y = 0; y < arr.length; y++) {
if (arr[x] === arr[y]) {
ctr+= 1;
}
}
if (ctr < 2) {
result = arr[x];
break;
}
}
return result;
}
console.log(FirstNotRepeatedChar('asif shaik'));
Here's an O(n) solution with 2 ES6 Sets, one tracking all characters that have appeared and one tracking only chars that have appeared once. This solution takes advantage of the insertion order preserved by Set.
const firstNonRepeating = str => {
const set = new Set();
const finalSet = new Set();
str.split('').forEach(char => {
if (set.has(char)) finalSet.delete(char);
else {
set.add(char);
finalSet.add(char);
}
})
const iter = finalSet.values();
return iter.next().value;
}
let arr = [10, 5, 3, 4, 3, 5, 6];
outer:for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if(arr[i]===arr[j+1]){
console.log(arr[i]);
break outer;
}
}
}
//or else you may try this way...
function firstDuplicate(arr) {
let findFirst = new Set()
for (element of arr)
if (findFirst.has(element ))
return element
else
findFirst.add(element )
}
function firstUniqChar(str) {
let myMap = new Map();
for(let i = 0; i < str.length; i++) {
let char = str.charAt(i);
if(!myMap.has(char)) {
myMap.set(char, 0);
}
myMap.set(char, myMap.get(char) + 1 );
}
for(let [key, value] of myMap) {
if(value === 1) {
return key;
}
}
return null;
}
let result = firstUniqChar("caabbdccee");
console.log(result);
You can use Map Object and set key and value, where in value you store the count for that particular character, After that you can iterate over map and check where is value 1 and return that key.
Map Object remembers the original insertion order of the keys.
This solution should works with array with integers and string.
function firstNoneRepeating(list, map = new Map()) {
for (let item of list) {
if (map.has(item)) {
map.set(item, map.get(item) + 1);
} else {
map.set(item, 1);
}
}
for (let [key, value] of map.entries()) {
if (value === 1) {
return key;
}
}
}
console.log(firstNoneRepeating("aabcbd"));
console.log(firstNoneRepeating([5, 2, 3, 4, 2, 6, 7, 1, 2, 3]));
let str='aabcbd'
let ans=''
for (let i=0;i<str.length;i++){
if(str.indexOf(str.charAt(i))===str.lastIndexOf(str.charAt(i))){
ans+=str.charAt(i)
break
}
}
console.log(ans)
Fill an empty array with zeros, with same length as the string array, and tally up how many times they appear through the loop. Grab the first one in the tallied array with a value of 1.
function firstNotRepeatingCharacter(s) {
const array = s.split("");
let scores = new Array(array.length).fill(0);
for (let char of array) {
scores[array.indexOf(char)]++;
}
const singleChar = array[scores.indexOf(1)];
return singleChar ? singleChar : "_"
}
You can iterate through each character to find() the first letter that returns a single match(). This will result in the first non-repeated character in the given string:
const first_nonrepeated_character = string => [...string].find(e => string.match(new RegExp(e, 'g')).length === 1);
const string = 'aabcbd';
console.log(first_nonrepeated_character(string)); // c
Here is my solution which have time complexity of o(n)
function getfirstNonRepeatingCharacterInAString(params) {
let count = {};
for (let i = 0; i < params.length; i++) {
let count1 = 0;
if (!count[params.charAt(i)]) {
count[params.charAt(i)] = count1 + 1;
}
else {
count[params.charAt(i)] = count[params.charAt(i)] + 1;
}
}
for (let key in count) {
if (count[key] === 1) {
return key;
}
}
return null;
}
console.log(getfirstNonRepeatingCharacterInAString("GeeksfoGeeks"));
Here is my solution using forEach and convert the string into an array
function firstNotRepeatingCharacter(s) {
var strArr = s.split("");
var found = "_";
strArr.forEach(function(item, index) {
if (strArr.indexOf(item) == index && strArr.indexOf(item, index + 1) == -1) {
if (found === "_") {
found = item;
}
}
})
return found;
}
firstNotRepeatingCharacter("abacabad")
Here is another approach:
Everytime you find equal chars store it in an array and break out of the loop. If the char is not found in the array then you have your first nonRepeating char
function nonRepeatingChars(value) {
const memory = []
for (let i = 0; i < value.length; i++) {
for (let j = i + 1; j < value.length; j++) {
if (value[i] === value[j]) {
memory.push(value[j])
break;
}
}
if (!memory.some(x => x === value[i])) {
return value[i];
}
}
return "all chars have duplicates";
}
console.log('First non repeating char is:',nonRepeatingChars("esen"))
console.log('First non repeating char is:',nonRepeatingChars("esesn"))
console.log('First non repeating char is:',nonRepeatingChars("eseulsn"))
console.log('First non repeating char is:',nonRepeatingChars("esesnn"))
> var firstNonRepeatedCharacter = function (str){
> for(i=0;i<str.length;i++){
> if(str.indexOf(str.charAt(i)) === str.lastIndexOf(str.charAt(i))){
> console.log(str.charAt(i));
> break;
> } } }
>
> firstNonRepeatedCharacter ("areerak");
you can check below link
https://codepen.io/t3veni/pen/wvvxJzm
Easy way to solve this algorithm, very straight forward.
function firstNonRepeatChar(str){
let map = {};
for(let i=0; i<str.length; i++){
if(Object.keys(map).includes(str[i])){
map[str[i]]++
}
else{
map[str[i]] = 1;
}
}
for(let j=0; j< Object.values(map).length; j++){
if(Object.values(map)[j] == 1){
console.log(Object.keys(map)[j]);
return
}
if (j == Object.values(map).length-1 && Object.values(map)[j] != 1){
console.log('_');
return;
}
else{
continue;
}
}
}
nonRepeat("aaabbcccdeeef");
Here is one other solution just using array, using 26 unique character as length of array:
var firstUniqChar = (function(s) {
var arr = [];
var str = s.toLowerCase();
for(let c of str){
let index = c.charCodeAt(0) - "a".charCodeAt(0);
arr[index]? ++arr[index]: arr[index]=1;
}
for(let c of str){
let index = c.charCodeAt(0) - 97;
if(arr[index] == 1){
return c;
};
}
return -1;
}("aabcbd"));
console.log(firstUniqChar);
We can keep track of frequency of each character of the string in an object.
For example : for "aabcbd" we can store the frequency as
{ "a":2, "b":2, "c":1, "d":1 }
This will take O(n) time.
Then we can traverse over this object and find the first character with frequency 1, which will also take O(n) time. So, the time complexity for this approach will be O(n).
const firstNonRepeating=(str)=>{
const obj={};
str.split("").forEach(item=>{
obj[item]
? obj[item]++
: obj[item]=1;
});
const item = Object.keys(obj).find(key=> obj[key] === 1);
return item;
}
Note: I use ES6 Object.keys method which may not work in older
browsers.
//To find first non repeating letter
//It will check for both upper and lower case
//only use one String.indexOf()
var mystr="ohvhvtccggt";
var checkFirstNonRepeating=function(){
var ele=[];
for(var i=0;i<mystr.length;i++) {
var key=mystr.charAt(i);
if(!ele[key])
ele[key]=0;
ele[key]++;
//Just check for second occurance of character
//no need to use indexOf twice
if(mystr.indexOf(key,i+1)==-1 && ele[key]<2)
return mystr[i];
}
return "All repeating letters";
}
console.log(checkFirstNonRepeating());
/*
Input : "ohvhvtoccggt"
Output : All repeating letters
Input :"oohjtht"
Output :j
*/
I used object to keep track of characters count in a string then return the char that has the fa value of 1. Here is a demo:
function firstNotRepeatingCharacter(s) {
// initialize an empty object to store chars
let seen = {};
let letter = '';
// iterate over each char in a string
// if it is already there increase value by one
// else set the value to 1
for(let char of s){
if (seen[char]){
seen[char] +=1;
} else {
seen[char] = 1;
}
}
// iterate over the new constructed object
// if the value is 1 and the output variable is empty
// return the associated key to the value 1
// else return '_'
for(let v in seen){
while(seen[v] == 1 && letter === ''){
letter += v;
return letter;
}
}
return('_');
}
console.log(firstNotRepeatingCharacter("abacabad"));
console.log(firstNotRepeatingCharacter("cbc"));
console.log(firstNotRepeatingCharacter("bcccccccccccccyb"));
console.log(firstNotRepeatingCharacter("aaa"));
The most satisfactory and easy to understand answer is the following.
function firstNotRepeatingCharacter(s) {
const arr = s.split("");
for(let i = 0; i < arr.length; i++){
let chr = arr[i];
if( arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i])){
return arr[i]
}
}
return "_"
}
Explanation: It loops through all the characters of a string from forward and backward and then compares the values. If the index of both forward and backward search is true then it returns that character.
let str = 'aabbcdd';
let val = str.split('').reduce((a, e)=>{ if(str.indexOf(e) == str.lastIndexOf(e)) {a = e }; return a})
console.log(val); // c
the implementation below has a good time complexity and it accounts for letters with different cases:
steps
must touch every character in the string to know if it's repeated or not
function firstNonRepeatingLetter(wordd) {
const chars = {}
let word = wordd.toLowerCase()
// go through chars
// store chars in hash with values of array storing index of char and true if only 1 encountered so far
for (let i = 0; i < word.length; i += 1) {
let char = word[i]
if (chars[char]) {
chars[char][0] = false
} else {
chars[char] = [true, i]
}
}
let output = ''
let index;
for (let key in chars) {
// return char with true and lowest index
if (chars[key][0]) {
index = index === undefined ? chars[key][1] : index
if (index >= chars[key][1]) {
output = key
}
}
}
return index === undefined ? '' : wordd[index]
}
console.log(firstNonRepeatingLetter('sTreSS')) //T```
The bellow solution is a kind of frequency counter pattern and it will run only one loop, so O(n) will be the time complexity.
function firstNotRepeatingCharacter(str) {
const obj = {};
for (let i = 0, L = str.length; i < L; i++) {
const char = str[i];
obj[char] = obj[char] ? obj[char] + 1 : 1;
}
for (let key of Object.keys(obj)) {
if (obj[key] == 1) {
return key;
}
}
return -1;
}
Here is another solution
function firstNotRepeatingCharacter(s) {
const obj = {};
for (let i of s) {
if(!obj[i]) {
obj[i] = 1;
} else if (obj[i]) {
obj[i] = +obj[i] + 1;
}
}
for (let [key, value] of Object.entries(obj)) {
if(value == 1) return key;
}
return "_"
}
Using below method can achieve first non repeated character
function main(str) {
str = String(str).toLowerCase();
let non_repeated_char = 'N/A';
for (let i = 0; i < str.length; i++) {
let currentChar = str[i];
let repeated_times = String(str).split('').filter(e => e == currentChar).length;
if (repeated_times === 1) {
non_repeated_char = currentChar;
break;
}
}
return non_repeated_char;
};
let Result = main("basketball");
console.log("The Non Repeated char is-->", Result);

Categories

Resources