Microsoft Interview Question: Write an algorithm to reverse... | Glassdoor

Interview Question

Software Developer I Interview(Student Candidate) Redmond, WA

Write an algorithm to reverse a string. Apply that

  algorithm to reverse a sentence.

Interview Answer

1 Answer


Reversing a string is easy: Index at the start moving toward the end, index at the end moving to the front. Swap the letters at each index and increment / decrement the indices respectively. O(n)

My first attempt at reversing the sentence, I reversed the entire sentence string, then split the sentence into words and reversed each word. O(n * w). The best way is to split on white spaces first and make the previous algorithm generic so that you aren't just constrained to swapping letters. Then swap words of a sentence in the same way that you would swap letters of a word. O(w)

Interview Candidate on Sep 26, 2012

Add Answers or Comments

To comment on this, Sign In or Sign Up.