Index of Leftmost Repeating Character

PHOTO EMBED

Tue Feb 08 2022 10:54:10 GMT+0000 (Coordinated Universal Time)

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

// 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;
    }
content_copyCOPY

Input : str = "geeksforgeeks" Output: --------- Index of leftmost repeating character: 0