Interviewers ask Puzzles questions because they think your ability to answer will provide some indication of your ability to do the job.
Two words are anagrams if and only if they contain the exact same letters with the exact same frequency (for example, "name" and "mean" are anagrams, but "red" and "deer" are not).
Given two strings S1 and S2, which each only contain the lowercase letters a through z, write a program to determine if S1 and S2 are anagrams. The program must have a running time of O(n + m), where n and m are the lengths of S1 and S2, respectively, and it must have O(1) (constant) space usage.
First create an array A of length 26, representing the counts of each letter of the alphabet, with each value initialized to 0. Iterate through each character in S1 and add 1 to the corresponding entry in A. Once this iteration is complete, A will contain the counts for the letters in S1. Then, iterate through each character in S2, and subtract 1 from each corresponding entry in A. Now, if the each entry in A is 0, then S1 and S2 are anagrams; otherwise, S1 and S2 aren't anagrams.
Here is pseudocode for the procedure that was described:
def areAnagrams(S1, S2)
A = new Array(26)
for each character in S1
arrayIndex = mapCharacterToNumber(character) //maps "a" to 0, "b" to 1, "c" to 2, etc...
A[arrayIndex] += 1
for each character in S2
arrayIndex = mapCharacterToNumber(character)
A[arrayIndex] -= 1
for (i = 0; i < 26; i++)
if A[i] != 0
Ques2.-You are a cook in a remote area with no clocks or other way of keeping time other than a four-minute and a seven-minute hourglass. On the stove is a pot of boiling water. Jill asks you to cook a nine-minute egg in exactly 9 minutes, and you know she is a perfectionist and can tell if you undercook or overcook the egg by even a few seconds. How can you cook the egg for exactly 9 minutes?
1. Flip both hourglasses over and drop the egg into the water.
2. When the 4-minute timer runs out, flip it over (4 minutes elapsed, 3 remaining on the 7-minute timer).
3. When the 7-minute timer runs out, flip it over. (7 minutes elapsed, 1 remaining in the 4-minute timer)
4. When the 4-minute timer runs out, flip the 7-minute timer over. (8 minutes elapsed. 6 minutes remained in the 7-minute timer, but flipping it over leaves one minute's worth of sand on top. When it runs out exactly nine minutes will have elapsed.