Given a string S consisting of lowercase Latin Letters. Find the first non-repeating character in S. Bonus:- Try solving it in O(n) time complexity and O(1) space complexity.
Input Format
The first line will contain the string S.
Output Format
You need to print the first non-repeating character. If there is no non-repeating character then print -1 .
Example 1
Input
hello
Output
h
Explanation
In the given string, the first character which is non-repeating is h, as it appears first and there is no other h in the string.
Example 2
Input
zxvczbtxyzvy
Output
c
Explanation
In the given string, c is the first character which is non-repeating.
Constraints:
1 <= S.length() <= 1000
Solution of Non-Repeating Character in java :–
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { //your code here Scanner sc = new Scanner(System.in); int f[] = new int[26]; String s = sc.next(); int n = s.length(); for(int i=0;i<n;i++){ f[s.charAt(i)-'a']++; } for(int i=0;i<n;i++){ if(f[s.charAt(i)-'a']==1){ System.out.println(s.charAt(i)); return; } } System.out.println(-1); } }
Add a Comment