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?- A. 0 -1
- B. 1 0
- C. 2 -1
- 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
- Problem: Check whether s2 contains a permutation of s1 as a substring. python def hasperm(s1, s2): k = len(s1) need = [0] 26; win = [0] 26…
- Problem: Return the longest common prefix of a list of file paths. python def lcp(words): if not words: return "" p = words[0] for w in…
- Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function…
- Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees…
- Problem: Return the longest palindromic substring of s (first one if there is a tie). python def lps(s): best = "" for c in range(len(s))…
- Problem: Check whether a string of brackets ()[]{} is balanced. python def balanced(s): pair = {')': '(', ']': '[', '}': '{'} st = [] for…