Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Reverse Words in a Sentence

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Reverse Words in a Sentence. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

NCR Corporation surfaces may need to reorder words in a sentence before displaying or processing text. Given a sentence, return its words in reverse order while normalizing whitespace to single spaces.

Implement reverse_words(sentence, method) with three supported approaches:

  1. iterative: Use an iterative algorithm.
  2. recursive: Use a recursion that processes one word position at a time.
  3. fibonacci: Use branching recursion similar in structure to Fibonacci, where the helper recursively processes two subranges and combines them in reverse order. This approach should branch, but it must not repeatedly recompute the same subproblem.

Formal Specification

  • Input: sentence, a string containing zero or more words separated by arbitrary whitespace, and method, one of the three method names above.
  • Output: A string containing the words in reverse order, separated by exactly one space. An empty or whitespace-only sentence returns "".
  • Word characters and their internal spelling must remain unchanged.

Constraints

  • 0 <= len(sentence) <= 10^5
  • The input contains zero or more whitespace-separated words
  • Words may contain printable non-whitespace characters
  • method is exactly "iterative", "recursive", or "fibonacci"

Function Signature

def reverse_words(sentence, method):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output