-
Code const firstNonRepeatingCharacter = (str) => { let count = str.split('').reduce((obj, char) => { obj[char] = ++obj[char] || 1; return obj; }, {}); for (const key in count) { if (count[key] === 1) { return key; } } return null; };
Test Cases // Since Node 10, we're using Mocha. // You can use `chai` for assertions. const chai = require("chai"); const assert = chai.assert; // Uncomment the following line to disable truncating failure messages for deep equals, do: // chai.config.truncateThreshold = 0; // Since Node 12, we no longer include assertions from our deprecated custom test framework by default. // Uncomment the following to use the old assertions: // const Test = require("@codewars/test-compat"); describe("Solution", function() { it('should return the first non-repeating character', function() { assert.strictEqual(firstNonRepeatingCharacter('abcd'), 'a'); assert.strictEqual(firstNonRepeatingCharacter('aabbcdc'), 'd'); }); it('should return the first non-repeating character when special characters are included', function() { assert.strictEqual(firstNonRepeatingCharacter('a@b@bc'), 'a'); }); it('should return null when all characters are repeating', function() { assert.strictEqual(firstNonRepeatingCharacter('aabbcc'), null); }); it('should return the first character if it is the only one', function() { assert.strictEqual(firstNonRepeatingCharacter('z'), 'z'); }); it('should handle an empty string correctly', function() { assert.strictEqual(firstNonRepeatingCharacter(''), null); }); it('should handle strings with numbers', function() { assert.strictEqual(firstNonRepeatingCharacter('1122a'), 'a'); }); it('should handle very long strings with the non-repeating character at the end', function() { const longString = 'a'.repeat(10000) + 'b'.repeat(10000) + 'c'; assert.strictEqual(firstNonRepeatingCharacter(longString), 'c'); }); it('should handle very long strings with all characters repeating', function() { const longString = 'a'.repeat(20000) + 'b'.repeat(20000); assert.strictEqual(firstNonRepeatingCharacter(longString), null); }); });
Output:
-
Code - const firstNonRepeatingCharacter = (str) => {
let chars = [], counts = [];for(const char of str) {let index = chars.indexOf(char);if(index < 0) {index = counts.length;chars.push(char);counts.push(0);}counts[index]++;}for(let index = 0; index < chars.length; index++) {if(counts[index] === 1) {return chars[index];- let count = str.split('').reduce((obj, char) => {
- obj[char] = ++obj[char] || 1;
- return obj;
- }, {});
- for (const key in count) {
- if (count[key] === 1) {
- return key;
- }
- }
- return null;
- };
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}