TIP102 Unit1 Reverse Sentence - codepath/compsci_guides GitHub Wiki

TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Strings, List Operations

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function reverse_sentence() should take a string sentence and return the sentence with the order of words reversed.
HAPPY CASE
Input: "tubby little cubby all stuffed with fluff"
Expected Output: "fluff with stuffed all cubby little tubby"

Input: "hello world"
Expected Output: "world hello"

EDGE CASE
Input: "Pooh"
Expected Output: "Pooh" (single word)

Input: "A B C D E"
Expected Output: "E D C B A"

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: To to manipulate the string by breaking it down into its component words, reversing the order of these words, and then reconstructing the sentence with the words in the new order.

1. Split the sentence into a list of words using `split()`.
2. Reverse the list of words using slicing.
3. Join the reversed list back into a single string using `join()`.
4. Return the resulting reversed sentence.

⚠️ Common Mistakes

  • Not handling multiple spaces correctly (though the problem states words are separated by single spaces).
  • Not considering the case with a single word.

I-mplement

Implement the code to solve the algorithm.

def reverse_sentence(sentence):
    # Split the sentence into words
    words = sentence.split()
    # Reverse the list of words
    reversed_words = words[::-1]
    # Join the reversed list back into a sentence
    reversed_sentence = ' '.join(reversed_words)
    return reversed_sentence