Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Find the first non-repeating character in a string of lowercase letters; return its index or −1.

Problem: Find the first non-repeating character in a string of lowercase letters; return its index or −1.
static int firstUnique(String s) {
    int[] cnt = new int[26];
    for (char c : s.toCharArray()) cnt[c - 'a']++;
    for (int i = 0; i < s.length(); i++)
        if (cnt[s.charAt(i) - 'a'] == 1) return i;
    return -1;
}
// firstUnique("swiss") + " " + firstUnique("aabb")
What does the commented expression evaluate to?
  1. A. 0 -1
  2. B. 1 0
  3. C. 2 -1
  4. D. 1 -1

Correct answer: D. 1 -1

Two passes: count, then scan in string order for the first count of 1. In "swiss", 's' appears 3 times, 'w' once at index 1. "aabb" has none → −1. Scanning the count array (alphabet order) instead of the string would report 'i' (index 2). O(n) time, O(26) space.

More Coding Interview Problems questions

Exams that ask this topic