~/coding-interview/leetcode-solution-first-unique-character-string.md

First Unique Character in a String - Leet Code Solution

// TL;DR

Count character frequencies with a HashMap in one pass, then scan again to find the first character with count 1. O(n).

First Unique Character in a String - Leet Code Solution

Problem Statement

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

Example

s = "leetcode"
return 0.

s = "loveleetcode"
return 2.

Note: You may assume the string contains only lowercase English letters.

Solution Brute Force

Lets take a look at the simple solution.

  • Have two loops. first will iterate till length of string
  • in second loop, iterate from beginning to end.
  • And check if the character is found anywhere
  • We can keep track of duplicate found by a boolean flag
  • And if during our inner loop, if we found that character is not found. This is our answer

Code

public int firstUniqChar_bruteforce(String s) {
   for (int i=0; i<s.length(); i++) {
      boolean unique = true;
      for (int j=0; j<s.length(); j++) {
         if (i != j && s.charAt(i) == s.charAt(j)) {
            unique = false;
            break;
         }
      }
      
      if (unique) {
         return i;
      }
   }
   
   return -1;
}

Complexity

Its O(n^2)

Another Solution using a HashMap

  • Iterate over string, and keep track of count of each character
  • Maintain a HashMap<Character, Integer>
  • Now, iterate over string again
  • For each character, lookup in our HashMap
  • If the count of that character is only 1, this is our answer
  • Since, 1 means this character is in the string only 1 times.

Code

public int firstUniqChar(String s) {
   Map<Character, Integer> map = new HashMap<Character, Integer>();
   for (int i=0; i<s.length(); i++) {
      int count = map.getOrDefault(s.charAt(i), 0);
      count ++;
      map.put(s.charAt(i), count);
   }
   
   for (int i=0; i<s.length(); i++) {
      if (map.get(s.charAt(i)) == 1) {
         return i;
      }
   }
   return -1;
}

Complexity

Its O(n)

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Valid Palindrome - Leet Code Solution

Valid Palindrome - Leet Code Solution

Problem Statement Given a string, determine if it is a palindrome, considering…

Valid Anagrams - Leet Code Solution

Valid Anagrams - Leet Code Solution

Problem Statement Given two strings s and t , write a function to determine if t…

Reverse String - Leet Code Solution

Reverse String - Leet Code Solution

Problem Statement Write a function that reverses a string. The input string is…

Reverse digits of a signed integer - Leet Code Solution

Reverse digits of a signed integer - Leet Code Solution

Problem Statement Given a signed integer, reverse digits of an integer. Return…

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…