-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstoccurence.java
More file actions
48 lines (44 loc) · 1.31 KB
/
Copy pathFirstoccurence.java
File metadata and controls
48 lines (44 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*Given a string S of lowercase English letters, the task is to find the index of the first non- repeating character. If there is no such A character, return -1.*/
import java.util.HashMap;
import java.util.ArrayList;
class FirstOccurrence
{
public static void main(String args[])
{
HashMap<Character, ArrayList<Integer>>map=new HashMap<>();
String s ="aaabbbccc";
int i = 0;
char[] charArray=s.toCharArray();
int size=s.length();
// Populate the map with character indices
for (char c:charArray)//TC=O(n)
{
if (!map.containsKey(c)) {
map.put(c,new ArrayList<>());
}
map.get(c).add(i);
i++;
}
int min=Integer.MAX_VALUE;
// finding out the min index.
for (HashMap.Entry<Character, ArrayList<Integer>>entry:map.entrySet())//tc=O(n)
{
if (entry.getValue().size() == 1) {
int curr=entry.getValue().get(0);
if(curr<min)
{
min=curr;
}
}
}
if(min==Integer.MAX_VALUE)
{
System.out.println("-1");
}
else
{
System.out.println(min);
}
}
}
//TIMECOMPLECITY=O(n).