First non-repeating character in a string
  • Posted: 5 years ago
  • Edit
  • answers (1)
  • views (2867)

Write a function to find the first non-repeating character in a String.


Posted Answers


  • Take an empty integer array of \( 256 \) elements to hold the frequency of character of the string.
  • Iterate through the string and construct the frequency array. Increment the current value of the frequency array by \( 1 \) at the location of the corresponding ASCII value of the character.
  • Iterate through the string and check the frequency array. Return the first element whose frequency is \( 1 \).

Time complexity = \( O(n) \).

public static char FirstNonRepeatingChar(String string) {

/* When the string is null */
if(string == null)
throw new NullPointerException(string);

/* Create an empty integer array to store the frequency */
int[] charFrequency = new int[256];

/* Construct the frequency array */
for(int i = 0; i < string.length; i++)
charFrequency[string.charAt(i)]++;

/* Iterate through string and check the frequency */
for(int i = 0; i < string.length; i++){
if(charFrequency[string.charAt(i)] == 1)
/* Print the first non repeating character */
return string.charAt(i));
break;
}
}

}

You need to Sign In to post your solution.