First Unique Character in a String

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contains only lowercase letters.
Quadratic Algorithm Time Complexity- O(n2) & Space Complexity - O(1)
public static int firstUniqChar(String s) {
    int length = s.length(), count = 0;
    for (int i = 0; i < length; i++) {
        count = 0;
        for (int j = 0; j < length; j++) {
            if (s.charAt(i) == s.charAt(j)) {
                count++;
                if (count > 1)
                    break;
            }
        }
        if (count == 1)
            return i;
    }
    return -1;
}
Quadratic Algorithm Time Complexity - O(n2) & Space Complexity - O(n)
public static int firstUniqChar(String s) {
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    String sortedString = new String(chars);
    for (int i = 0; i < s.length(); i++) {
        int index = sortedString.indexOf(s.charAt(i));
        if (index == sortedString.lastIndexOf(s.charAt(i)))
            return i;
    }
    return  -1;
}
Linear Algorithm Time Complexity - O(n) & Space Complexity - O(n)
public static  int firstUniqChar(String s) {
    int[] charCount = new int[26];
    for (int i = 0; i < s.length(); i++) {
        charCount[s.charAt(i) - 97] += 1;
    }
    for (int i = 0; i < s.length(); i++) {
        if (charCount[s.charAt(i) -97] == 1)
            return i;
    }
    return -1;
}
Quadratic Algorithm Time Complexity - O(n2) & Space Complexity - O(n)
public static  int firstUniqChar(String s) {
    LinkedHashMap<Character, Integer> linkedHashMap = new LinkedHashMap<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        linkedHashMap.put(c, linkedHashMap.getOrDefault(c , 0)+1);
    }
    for (Map.Entry<Character, Integer> characterIntegerEntry : linkedHashMap.entrySet()) {
        if (characterIntegerEntry.getValue() == 1)
            return s.indexOf(characterIntegerEntry.getKey());
    }
    return -1;
}
Linear Algorithm Time Complexity - O(n) & Space Complexity - O(1)
public static  int firstUniqChar(String s) {
    int res = Integer.MAX_VALUE;
    for (char c = 'a'; c <= 'z' ; c++) {
        int index = s.indexOf(c);
        if (index != -1 && index == s.lastIndexOf(c))
            res = Math.min(res, index);
    }
    return res == Integer.MAX_VALUE ? -1 : res;
}

Comments

Popular posts from this blog

Recursion

Stack

Data Structure & Algorithm