coding-interview|September 08, 2020|2 min read

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)

Related Posts

Counting Sort Algorithm

Counting Sort Algorithm

Counting sort runs on relatively smaller set of input. Counting sort calculates…

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…

How to prepare for your next Coding Interview

How to prepare for your next Coding Interview

Here are some tips while preparing for your coding interviews. 1. Do study or…

Quick Sort Algorithm

Quick Sort Algorithm

This algorithm is very useful for large input. And, is quite efficient one. It…

Plus One - Leet Code Solution

Plus One - Leet Code Solution

Problem Statement Given a non-empty array of digits representing a non-negative…

Two Sum Problem - Leet Code Solution

Two Sum Problem - Leet Code Solution

Problem Statement Given an array of integers, return indices of the two numbers…

Latest Posts

Serverless vs Containers — The Decision I Keep Revisiting

Serverless vs Containers — The Decision I Keep Revisiting

Every time I start a new service, I have the same argument with myself. Lambda…

Building a Production RAG Pipeline — From Chunking to Retrieval to Generation

Building a Production RAG Pipeline — From Chunking to Retrieval to Generation

Large Language Models are powerful, but they hallucinate. They confidently make…

Prompt Engineering Patterns That Actually Work in Production

Prompt Engineering Patterns That Actually Work in Production

Most prompt engineering advice on the internet is useless in production. “Be…

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Jenkins Pipeline with Jenkinsfile - How To Schedule Job on Cron and Not on Code Commit

Introduction In this post we will see following: How to schedule a job on cron…

How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

How to Git Clone Another Repository from Jenkin Pipeline in Jenkinsfile

Introduction There are some cases, where I need another git repository while…

Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Jenkins Pipeline - How to run Automation on Different Environment (Dev/Stage/Prod), with Credentials

Introduction I have an automation script, that I want to run on different…