A blind man walks into a hardware store to buy a hammer. There are hammers hanging behind the front desk, but obviously the blind man isn't able to see them. And yet a few minutes later, he happily walks out of the store, having just purchased a new hammer.
How did he do it?
He walks up the the front desk where the clerk is working and says "I'd like to buy a hammer."
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
Imagine John, a party magician, is carrying three pieces of gold each piece weighing one kilogram. While taking a walk he comes to a bridge which has a sign posted saying the bridge could hold only a maximum of 80 kilograms. John weighs 78 kilograms and the gold weighs three kilograms. John reads the sign and still safely crossed the bridge with all the gold. How did he manage this?
John is a juggler. When he came to the bridge he juggled the gold, always keeping one piece in the air.
A farmer is travelling with a fox, a sheep and a small sack of hay. He comes to a river with a small boat in it. The boat can only support the farmer and one other animal/item. If the farmer leaves the fox alone with the sheep, the fox will eat the sheep. And if the farmer leaves the sheep alone with the hay, the sheep will eat the hay.
How can the farmer get all three as well as himself safely across the river?
The farmer takes the sheep across the river, then returns back.
The farmer takes the fox across the river.
The farmer takes the sheep back to the first side of the river.
The farmer leaves the sheep back on the first side of the river, and takes the hay to the other side.
The farmer returns to the first side of the river.
The farmer brings the sheep back to the second side.