// Efficient Approach-2 : Time & Space similar to previous method
static final int CHAR=256;
static int leftMost(String str)
{
boolean[] visited=new boolean[CHAR];
int res=-1;
for(int i=str.length()-1;i>=0;i--){
if(visited[str.charAt(i)])
res=i;
else
visited[str.charAt(i)]=true;
}
return res;
}
// One Traversal
// Efficient Approach-1 : Time Complexity : O(n + CHAR), Auxiliary Space : O(CHAR)
static final int CHAR=256;
static int leftMost(String str)
{
int[] fIndex=new int[CHAR];
Arrays.fill(fIndex,-1);
int res=Integer.MAX_VALUE;
for(int i=0;i<str.length();i++){
int fi=fIndex[str.charAt(i)];
if(fi==-1)
fIndex[str.charAt(i)]=i;
else
res=Math.min(res,fi);
}
return (res==Integer.MAX_VALUE)?-1:res;
}
// Better Approach : Time Complexity : O(n) but requires two loops for input string
static final int CHAR=256;
static int leftMost(String str)
{
int[] count=new int[CHAR];
for(int i=0;i<str.length();i++){
count[str.charAt(i)]++;
}
for(int i=0;i<str.length();i++){
if(count[str.charAt(i)]>1)return i;
}
return -1;
}
// Naive Code : Time Complexity : O(n^2)
static int leftMost(String str)
{
for(int i=0;i<str.length();i++){
for(int j=i+1;j<str.length();j++){
if(str.charAt(i)==str.charAt(j))return i;
}
}
return -1;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter