First Unique Character in a String | String Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a String, find the first non-repeating character in the given String and return it’s index.

Example 

First Unique Character in a String

Input :- "hello"
Output :- 0
Input :- "google"
Output :- 4

Solution

This problem can be solved in following steps :-

  1. Create an array of characters from the input string.
  2. Create an integer array (count array) of size 26 (Total number of characters in the English language), This array will be used to store the frequency of each character in the input string.
  3. Traverse the character array from start (index 0) to end (n-1, where n is the length of an array) and convert each character into an index of count array by subtracting the character from ‘a’ and converting it into ASCII code. Increase the count for the calculated index by 1.
  4. Again traverse the character array, like in step 3. This time instead of increasing the count by 1, check the first index whose value is equal to 1 and return the traverse index.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		int result = main.firstUniqChar("google");
		System.out.print(result);
	}
	
	/* Solution */
	public int firstUniqChar(String s) {
		
        int[] countArray = new int[26];
        char[] array = s.toCharArray();
        
        for(int i=0; i<array.length; i++){            
            countArray[array[i]-'a']++;
        }
        
        for(int i=0; i<array.length; i++){
            if(countArray[array[i]-'a'] == 1){
                return i;
            }
        }
        return -1;
    }
}

Result

4

Similar Post

  1. Count and Say
  2. Reverse only Letters of a String
  3. Reverse Vowels of a String

That’s all for First Unique Character in a String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.