Question: Write an efficient algorithm to Reverse the order of words in a given array of character which form a sequence of words.
Note: Memory-based question, suppodely a part of 'Engineering' section of the written test for a Dev position at Adobe.
Solution: Find below one possible algorithm to solve this problem:-
- Allocate memory for another array of same size
- Iterate through the array and find words (by finding white spaces)
- Put the word reversed (order of characters reversed) in the new array
- Put the white spaces as well (you won't reverse them as they are same either way)
- Continue and complete the iteration for all the words in the array
- Copy the new array reversed into the original array and you're done!
Example: Suppose you have one array "int char float" in the beginning. The expected result should be "float char int" in this case. Let's dry run the above algorithm for this test array and see if it gets us the expected result.
NewArray = " " (a array of 14 characters, currently all blank)
Iteration starts here
First word found: "int", so NewArray = "tni "
Second word found: "char", so NewArray = "tni rahc "
Third word found: "float", so NewArray = "tni rahc taolf"
Iteration ends here
Now reverse of the NewArray = "float char int"







