function firstNonRepeatingChar(s: string): number {
const charCount: {[key: string]: number} = {};
for (const ch of s) {
charCount[ch] = (charCount[ch] || 0) + 1;
}
for (let i = 0; i < s.length; i++) {
if (charCount[s[i]] === 1) {
return i;
}
}
return -1;
}
console.log(firstNonRepeatingChar("swiss"));The string "swiss" has characters: s(3 times), w(1 time at index 1), i(1 time at index 2). The first non-repeating character is 'w' at index 1.
function firstNonRepeatingChar(s: string): number {
const counts: {[key: string]: number} = {};
for (const ch of s) {
counts[ch] = (counts[ch] || 0) + 1;
}
for (let i = 0; i < s.length; i++) {
if (counts[s[i]] === 1) {
return i;
}
}
return -1;
}
console.log(firstNonRepeatingChar("aabbccdde"));Characters and counts: a(2), b(2), c(2), d(2), e(1). 'e' is the only non-repeating character at index 8.
function firstNonRepeatingChar(s: string): number {
const counts = new Map<string, number>();
for (const ch of s) {
if (counts.has(ch)) {
counts.set(ch, counts.get(ch)! + 1);
} else {
counts.set(ch, 1);
}
}
for (let i = 0; i < s.length; i++) {
if (counts.get(s[i]) === 1) {
return i;
}
}
return -1;
}
console.log(firstNonRepeatingChar("abcabcde"));There is no runtime error because the first non-repeating character 'd' is found at index 6 before i reaches s.length. However, the loop condition i <= s.length is incorrect and could access s[s.length] (undefined) in cases with no early return.
function firstNonRepeatingChar(s: string): number {
const counts: {[key: string]: number} = {};
for (const ch of s) {
counts[ch] = (counts[ch] || 0) + 1;
}
for (let i = 0; i < s.length; i++) {
if (counts[s[i]] === 1) {
return i;
}
}
return -1;
}
console.log(firstNonRepeatingChar("aabbcc"));All characters repeat, so no non-repeating character exists. The function returns -1.
function firstNonRepeatingChar(s: string): number {
const counts: {[key: string]: number} = {};
for (const ch of s) {
counts[ch] = (counts[ch] || 0) + 1;
}
for (let i = 0; i < s.length; i++) {
if (counts[s[i]] === 1) {
return i;
}
}
return -1;
}
console.log(firstNonRepeatingChar("😀😃😄😀😃"));JavaScript strings use UTF-16 encoding. The for...of loop iterates over code points (full emojis as keys in counts), but s[i] accesses 16-bit code units (surrogate halves). The keys do not match, so counts[s[i]] is always undefined, and the function returns -1.
