AI solution for JavaScript Coding Question on BFE.dev
105. find the first duplicate character in a string
One possible solution in JavaScript:
function firstDuplicate(str) {
let charSet = new Set();
for(let i = 0; i < str.length; i++) {
let char = str[i];
if (charSet.has(char)) {
return char;
} else {
charSet.add(char);
}
}
return null;
}
This solution uses a set to keep track of unique characters seen so far. As soon as a duplicate character is found, it is returned. If no duplicates are found, the function returns null
. The time complexity of this solution is O(n) and the space complexity is O(n), since we need to store all unique characters in the set.
A more memory-efficient solution would be to use an object to keep track of character frequencies instead of storing all unique characters in a set. This would reduce space complexity to O(1), but increase time complexity to O(n^2). Here's the implementation:
function firstDuplicate(str) {
let charFreq = {};
for(let i = 0; i < str.length; i++) {
let char = str[i];
if (charFreq[char]) {
return char;
} else {
charFreq[char] = true;
}
}
return null;
}
Overall, the choice of solution depends on the trade-off between time and space complexity that is acceptable for the given use case.