First Unique Character in a String (Leetcode 387)
Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.
Examples
- Example 1
- Input:
s = "leetcode"
- Output:
0
- Input:
- Example 2
- Input:
s = "loveleetcode"
- Output:
2
- Input:
- Example 3
- Input:
s = "aabb"
- Output:
-1
- Input:
Solution 1
- Split string and loop over each character
- If indexOf and lastIndexOf are equal it means there is only 1 occurrence
- This is the first instance of a unique character
- Return this as the result
- If no items pass return '-1'
const firstUniqChar = (input) => {
var inputArr = input.split("");
for (var i = 0; i < inputArr.length; i++) {
var char = inputArr[i];
if (inputArr.indexOf(char) == inputArr.lastIndexOf(char)) {
return inputArr.indexOf(char);
}
}
return -1;
};
const example1 = "leetcode";
const example2 = "loveleetcode";
const example3 = "aabb";
const example4 = "dddccdbba";
console.log("example1", firstUniqChar(example1)); // 0
console.log("example2", firstUniqChar(example2)); // 2
console.log("example3", firstUniqChar(example3)); // -1
console.log("example4", firstUniqChar(example4)); // 8
Big O -> O(3n) -> O(n)
Solution 2
const firstUniqChar = (input) => {
const resultsObj = {};
let firstNonRepeatingCharIndex = -1;
input.split("").forEach((char) => {
resultsObj[char] = resultsObj[char] ? resultsObj[char] + 1 : 1;
});
for (const x in resultsObj) {
if (resultsObj[x] === 1) {
firstNonRepeatingCharIndex = input.indexOf(x);
// break out of for loop
break;
}
}
return firstNonRepeatingCharIndex;
};
const example1 = "leetcode";
const example2 = "loveleetcode";
const example3 = "aabb";
const example4 = "dddccdbba";
console.log("example1", firstUniqChar(example1)); // 0
console.log("example2", firstUniqChar(example2)); // 2
console.log("example3", firstUniqChar(example3)); // -1
console.log("example4", firstUniqChar(example4)); // 8
Big O -> O(2n) -> O(n)