DEV Community

Cover image for first non-repeating character.
chandra penugonda
chandra penugonda

Posted on • Edited on

first non-repeating character.

This problem was asked by SAP Labs.

Given a string of characters, return the index of the first non-repeating character.

Example
function nonRepeatingFirstCharacter(str) {

}

const str = "abcdcaf";
console.log(nonRepeatingFirstCharacter(str)); // 1
Explanation: The non-duplicate characters in the above string are b, d and f. Since b occurs first, the index of b, which is 1 is returned.
Enter fullscreen mode Exit fullscreen mode

Solution

function nonRepeatingFirstCharacter(str) {
  const map = new Map();
  for (const char of str) {
    map.set(char, (map.get(char) || 0) + 1);
  }
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    if (map.get(char) === 1) return i;
  }
  return -1;
}

const str = "abcdcaf";
console.log(nonRepeatingFirstCharacter(str)); // 1

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Use a hash table (object) to store count of each character in one pass
  • Increment count if character is already in table, default to 1
  • Then loop through string again checking if char count is 1
  • Return index immediately if non-duplicate char found

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay