Finding the first non-repeating character of a string in JavaScript

We are required to write a JavaScript function that takes in a string as the first and the only argument.

The function should find and return the index of first character it encounters in the string which appears only once in the string.

If the string does not contain any unique character, the function should return -1.

For example, if the input string is:

const str = 'hellohe';

Then the output should be:

const output = 4;

Because the character 'o' at index 4 is the first character that appears only once in the string.

Method 1: Using Object to Track Character Count

This approach uses an object to store both the count and first occurrence index of each character:

const str = 'hellohe';

const firstUnique = (str = '') => {
    let obj = {};
    
    // First pass: count characters and store their first index
    for(let i = 0; i 

4

Method 2: Using Map for Better Performance

A more efficient approach using JavaScript Map:

const firstUniqueMap = (str = '') => {
    const charMap = new Map();
    
    // Count character frequencies
    for(let i = 0; i 

4
-1
0

Method 3: Using Array Methods

A functional approach using array methods:

const firstUniqueArray = (str = '') => {
    const chars = str.split('');
    
    const index = chars.findIndex((char, i) => {
        return str.indexOf(char) === i && str.lastIndexOf(char) === i;
    });
    
    return index;
};

console.log(firstUniqueArray('hellohe'));
console.log(firstUniqueArray('programming'));
4
0

Comparison

Method Time Complexity Space Complexity Readability
Object Tracking O(n) O(n) Medium
Map O(n) O(n) High
Array Methods O(n²) O(n) Very High

Key Points

  • The Map approach is generally preferred for its clean syntax and good performance
  • The object method works well but requires more complex data handling
  • Array methods are most readable but less efficient for large strings
  • All methods return -1 when no unique character exists

Conclusion

The Map-based solution offers the best balance of performance and readability for finding the first non-repeating character. Choose the array method approach for simpler cases where performance isn't critical.

Updated on: 2026-03-15T23:19:00+05:30

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements