Leetcode 2000: Reverse Prefix of Word

grid47
grid47
Exploring patterns and algorithms
Apr 21, 2024 4 min read

You are given a string ‘word’ and a character ‘ch’. Reverse the portion of the string starting at index 0 and ending at the index of the first occurrence of ‘ch’. If ‘ch’ is not found, return the original string.
Problem
Approach
Steps
Complexity
Input: The input consists of a string 'word' and a character 'ch'. The length of the string is between 1 and 250 characters. The string consists of lowercase English letters.
Example: word = 'abcdefd', ch = 'd'
Constraints:
• 1 <= word.length <= 250
• word consists of lowercase English letters
• ch is a lowercase English letter
Output: Return the resulting string after reversing the segment from index 0 to the first occurrence of 'ch'. If 'ch' is not found, return the original string.
Example: 'dcbaefd'
Constraints:
Goal: The goal is to reverse the substring from the start of the string to the first occurrence of the character 'ch'. If 'ch' is absent, return the string unchanged.
Steps:
• 1. Find the first occurrence of 'ch' in the string.
• 2. If 'ch' is found, reverse the substring from index 0 to the index of the first occurrence of 'ch'.
• 3. If 'ch' is not found, return the original string.
Goal: The input string must consist of lowercase English letters, and the length must be between 1 and 250 characters.
Steps:
• The string length is between 1 and 250.
• The string only contains lowercase English letters.
Assumptions:
• The input string will always contain valid lowercase letters, and the character 'ch' is also a lowercase letter.
Input: word = 'abcdefd', ch = 'd'
Explanation: The first occurrence of 'd' is at index 3. The substring from index 0 to 3 is reversed, giving 'dcbaefd'.

Input: word = 'abcd', ch = 'z'
Explanation: 'z' does not exist in 'abcd', so no reversal is done and the original string is returned.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus