Pankaj Tanwar
Published on

Reverse Prefix of Word.

––– views

Problem of the day - Reverse Prefix of Word

Tag - Easy

Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.

  • For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

Return the resulting string.

Example 1:

Input: word = "abcdefd", ch = "d" Output: "dcbaefd" Explanation: The first occurrence of "d" is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".


I had a couple of thought in mind. How about find the index of char and reverse the sub-string and concat it. But it seems, very slow algo.

To reverse the string, I came up the approach of swapping elements. Pretty basic stuff.

class Solution {
public:
string reversePrefix(string word, char ch) {
int char_index = -1;
char temp;
for(int i=0;i<word.length();i++) {
if(word[i] == ch) {
char_index = i;
break;
}
}
// if not found
if(char_index == -1) return word;
// swap elements
for(int i=0;i<=char_index / 2;i++) {
temp = word[i];
word[i] = word[char_index - i];
word[char_index - i] = temp;
}
return word;
}
};

If you feel, I am missing on something, feel free to reach out to me


I welcome your suggestions to improve it further!


Thanks for being part of my daily-code-workout journey. As always, if you have any thoughts about anything shared above, don't hesitate to reach out.


You might like previous editions of my coding diary