Python HackerRank Sentence Transformation Challenge

“Python(Basic) Questions from a HackerRank Assessment I Recently Cleared" 🔹 Problem Statement You are given a sentence consisting of space-separated words with upper and lower case English letters. Each word must be transformed using the following rules: The first character of each word remains unchanged For every next character: Compare it with the previous character (case-insensitive) If the previous character comes earlier in the alphabet → convert current character to uppercase If the previous character comes later → convert current character to lowercase If both characters are the same → keep it unchanged Spaces should remain as they are 🔹 Logic / Approach Traverse the sentence character by character Reset comparison whenever a space is encountered Keep track of the previous character Compare characters using lower() to avoid case issues Apply transformation rules and build the result step by step This ensures accurate transformation while preserving word boundaries. 🔹 Code Implementation (Python) def transformSentence(sentence): result = [] prev_char = None for ch in sentence: if ch == " ": result.append(" ") prev_char = None else: if prev_char is None: result.append(ch) else: if prev_char.lower() < ch.lower(): result.append(ch.upper()) elif ch.lower() < prev_char.lower(): result.append(ch.lower()) else: result.append(ch) prev_char = ch return "".join(result) 🔹 Sample Input a Blue MOON 🔹 Output a BLUe MOOn #Python #HackerRank #CodingPractice #ProblemSolving #LearningJourney #SoftwareEngineering

To view or add a comment, sign in

Explore content categories