AfterAcademy Tech
•
30 Mar 2020

Difficulty: Easy
Asked in: Amazon, Microsoft
Problem descriptionGiven a string S, write a program to find the first non-repeating character in it and return its index.
Problem Note
Example 1
Input: S = "afteracademy"
Output: 1
Example 2
Input: S = "mindorks"
Output: 0
Example 3
Input: S = "abacdcd"
Output: -1
You should try to solve this problem here.
We will be discussing two different approaches to solve this problem
To find the first non-repeating character, we may look for every pair of characters in the string. The first occurring character which does not have any pair will be the answer.
In case of no such characters, return -1.
Pseudo Code
int firstUniqueChar(string s) {
len = s.length()
for(i = 0 to i < len){
bool found = true
for(j = i+1 to j < len){
if(s[i] == s[j]){
found = false
break
}
}
if(found == true){
return i
}
}
return -1
}
Complexity Analysis
Time Complexity: O(n²)
Space Complexity: O(1)
Critical Ideas to Think
If you have read about hashmaps then, you would know that the lookup time of a key is constant. In this problem, we could use the hashmap to store the frequency of each character of the string and that could be done in a single pass of the string.
In another pass of the string, we may look for the first character with value in the map equal to 1.
Solution Step
2. Scan the string and check if the value of the ith character in the map is 1 then return i. 3. Return -1, in case of the value of each character in the map, is greater than 1
Pseudo Code
int firstUniqChar(String s) {
Create a Hashmap freq
n = s.length()
// build hash map : character and how often it appears
for (int i = 0 to i < n) {
c = s[i]
freq[c] = freq[c] + 1
}
// find the index
for (int i = 0 to i < n) {
if (freq[s[i]] == 1)
return i
}
return -1
}
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Critical Ideas to Think

If you have any more approaches or you find an error/bug in the above solutions, please comment down below.
Happy Coding! Enjoy Algorithms!
AfterAcademy Tech
You are given a string S and its length L and you need to sort its characters based on their frequency. The characters in the output will be distinct and ordered based on their frequency in S, higher frequency comes first.

AfterAcademy Tech
Given two strings S1 and S2 of size m and n respectively, you need to check whether the two strings are an anagram of each other or not. S1 is an anagram of S2 if the characters of S1 can be rearranged to form S2.

AfterAcademy Tech
In this blog, we will learn what are unique keys and what is the need for unique keys. We will also discuss various points on which the unique key differ from a primary key.

AfterAcademy Tech
Given three strings S1, S2 and S3, write a program which checks whether S3 is an interleaving of S1 and S2. The problem is a typical dynamic programming problem.
