The question was that you are given a string such that it contains word(s) whose reverse exists in the same string. The task was to return first word whose reverse was present in the string.
e.g., if the input string is
I am a good student. I like interviewing a lot. Interviewing makes me happy. Being yppah is a key to successful life. Successful life is what we want
Output: happy
The constraint on the string is that we can not read the string from backwards. That means we have to traverse the string from beginning(i.e., index 0) to end(i.e., index str.length() - 1)
Potential solution:
I approached the problem in a naive manner.
I checked for all the words
if they are the reverse of the any word in the so far traversed string
if yes, then return the corresponding word
else continue the above steps
What else could have been the approaches? How could the problem be solved optimally. Any sort of help would be highly appreciated. Thanks in advance.