Index of Leftmost Non-repeating Element

PHOTO EMBED

Tue Feb 08 2022 11:04:00 GMT+0000 (UTC)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #string #index #leftmostnonrepeatingcharacter

// One Traversal
// Efficient Approach-1 : Time Complexity : O(n)
 
    static final int CHAR=256;
    static int nonRep(String str) 
    {
        int[] fI=new int[CHAR];
        Arrays.fill(fI,-1);
    
        for(int i=0;i<str.length();i++){
            if(fI[str.charAt(i)]==-1)
            fI[str.charAt(i)]=i;
            else
            fI[str.charAt(i)]=-2;
        }
        int res=Integer.MAX_VALUE;
        for(int i=0;i<CHAR;i++){
            if(fI[i]>=0)res=Math.min(res,fI[i]);
        }
        return (res==Integer.MAX_VALUE)?-1:res;
    }
 
 
// Two Traversal
// Better Approach : Time Complexity : O(n) 
 
    static final int CHAR=256;
    static int nonRep(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 nonRep(String str) 
    {
        for(int i=0;i<str.length();i++){
            boolean flag=false;
            for(int j=0;j<str.length();j++){
                if(i!=j&&str.charAt(i)==str.charAt(j)){
                    flag=true;
                    break;
                }
            }
            if(flag==false)return i;
        }
        return -1;
    }
content_copyCOPY

Given a string, the task is to find the leftmost character that does not repeat. Input : str = "geeksforgeeks" Output: --------- Index of leftmost repeating character: 5