Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d05bbf7

Browse files
algorithm: first unique char in a string (#1103)
* feat: Added Algo first unique char in a string. * Optimised algo to linear time complexity * removed double quotes * Review changes: if-else logic
1 parent c7f9bf9 commit d05bbf7

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

‎DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@
299299
* [CountVowels](String/CountVowels.js)
300300
* [CreatePermutations](String/CreatePermutations.js)
301301
* [DiceCoefficient](String/DiceCoefficient.js)
302+
* [FirstUniqueCharacter](String/FirstUniqueCharacter.js)
302303
* [FormatPhoneNumber](String/FormatPhoneNumber.js)
303304
* [GenerateGUID](String/GenerateGUID.js)
304305
* [HammingDistance](String/HammingDistance.js)

‎String/FirstUniqueCharacter.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @function firstUniqChar
3+
* @description Given a string str, find the first non-repeating character in it and return its index. If it does not exist, return -1.
4+
* @param {String} str - The input string
5+
* @return {Number} - The index of first unique character.
6+
* @example firstUniqChar("javascript") => 0
7+
* @example firstUniqChar("sesquipedalian") => 3
8+
* @example firstUniqChar("aabb") => -1
9+
*/
10+
11+
const firstUniqChar = (str) => {
12+
if (typeof str !== 'string') {
13+
throw new TypeError('Argument should be string')
14+
}
15+
const count = new Map()
16+
17+
for (const char of str) {
18+
if (!count[char]) {
19+
count[char] = 1
20+
} else {
21+
count[char]++
22+
}
23+
}
24+
for (let i = 0; i < str.length; i++) {
25+
if (count[str[i]] === 1) return i
26+
}
27+
return -1
28+
}
29+
30+
export { firstUniqChar }
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { firstUniqChar } from '../FirstUniqueCharacter'
2+
3+
describe('firstUniqChar', () => {
4+
it('locates the index of first unique character in the string', () => {
5+
expect(firstUniqChar('javascript')).toEqual(0)
6+
expect(firstUniqChar('sesquipedalian')).toEqual(3)
7+
expect(firstUniqChar('aabb')).toEqual(-1)
8+
})
9+
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /