ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Find First Non-Repeating Character

JavaScript

Goal -- WPM

Ready
Exercise Algorithm Area
1function findFirstNonRepeatingChar(str) {
2if (!str) {
3return null; // Handle empty or null string
4}
5
6const charCount = new Map();
7
8// Count character frequencies
9for (let i = 0; i < str.length; i++) {
10const char = str[i];
11charCount.set(char, (charCount.get(char) || 0) + 1);
12}
13
14// Find the first character with a count of 1
15for (let i = 0; i < str.length; i++) {
16const char = str[i];
17if (charCount.get(char) === 1) {
18return char;
19}
20}
21
22return null; // No non-repeating character found
23}
Algorithm description viewbox

Find First Non-Repeating Character

Algorithm description:

This function identifies the first character in a given string that appears only once. It's useful in text processing tasks, such as analyzing character distributions or implementing simple form validation where unique input is required. The algorithm iterates through the string twice: once to count frequencies and once to find the first unique character.

Algorithm explanation:

The `findFirstNonRepeatingChar` function first handles the edge case of an empty or null input string by returning `null`. It then uses a `Map` to store the frequency of each character in the string. The first loop iterates through the string, incrementing the count for each character encountered. The second loop iterates through the string again, checking the count of each character in the `Map`. The first character found with a count of 1 is returned. If no such character exists after checking the entire string, `null` is returned. The time complexity is O(n) because we iterate through the string twice. The space complexity is O(k), where k is the number of unique characters in the string, due to the `Map` storage.

Pseudocode:

function findFirstNonRepeatingChar(string):
  if string is empty or null:
    return null

  create a map called charCount

  for each character in string:
    increment count for character in charCount

  for each character in string:
    if count of character in charCount is 1:
      return character

  return null