Java O(N) Runtime and O(1) Space


  • 0
    T

    Run through the array twice. Using a 256 size array cause it accounts for all ASCII characters

    public class Solution {
        public int firstUniqChar(String s) {
            if(s.length() == 0) return -1;
            else if(s.length() == 1) return 0;
            
            int[] alpha = new int[256];
            for(int i = 0; i<s.length(); i++){
                alpha[s.charAt(i)]++;
            }
            for(int i = 0; i<s.length(); i++){
                if(alpha[s.charAt(i)] == 1) return i;
            }
            
            return -1;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.