Find the First Non-Repeating Character in a String

Given a string, this algorithm will find the first non-repeating character in the string and return its index. If no such character exists, it will return -1.

Problem

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use a hash table to store the character and its index.
// Then iterate through the string and check if the character is in the hash table.
// If it is, then we know it is a repeating character. If it is not, then we know it is a non-repeating character.
// We can then return the index of the first non-repeating character.
// This solution is optimal because it is O(n) time complexity and O(n) space complexity.

function firstUniqChar(s) {
  let hash = {};
  for (let i = 0; i < s.length; i++) {
    if (hash[s[i]]) {
      hash[s[i]] = -1;
    } else {
      hash[s[i]] = i;
    }
  }
  for (let i = 0; i < s.length; i++) {
    if (hash[s[i]] !== -1) {
      return hash[s[i]];
    }
  }
  return -1;
} console.log(firstUniqChar("leetcode")); // 0
console.log(firstUniqChar("loveleetcode")); // 2

A.I. Evaluation of the Solution

The candidate's solution is a good one. It uses a hash table to store the characters and their indices, and then iterates through the string to check if each character is in the hash table. If it is, then the character is a repeating character. If it is not, then the character is a non-repeating character. The candidate then returns the index of the first non-repeating character. This solution is optimal because it is O(n) time complexity and O(n) space complexity.

Evaluated at: 2022-11-21 08:16:13