algoadvance

Leetcode 2000. Reverse Prefix of Word

Problem Statement

You are given a 0-indexed string word and a character ch. Find the first occurrence of ch in word, and reverse the segment of word that starts at index 0 and ends at the index of the first occurrence (inclusive). If the character ch does not exist in word, return the original string.

Example

Clarifying Questions

  1. Q: Are there any constraints on the length of the word or the type of characters it can contain? A: 1 <= word.length <= 250, word consists of only lowercase English letters, and ch is a lowercase English letter.

  2. Q: What should be done if ch is not found in word? A: The original word should be returned.

  3. Q: Should I consider the possibility of multiple occurrences of the character ch? A: Only the first occurrence of ch should be considered.

Strategy

  1. Search for the character ch:
    • Use the indexOf method to find the first occurrence of ch in the word.
  2. Reverse the segment:
    • If ch is found, use string manipulation to reverse the substring from the start to the found index.
    • Concatenate the reversed substring with the remaining part of the string.
  3. Return the resultant string.

Code

public class Solution {
    public String reversePrefix(String word, char ch) {
        int index = word.indexOf(ch);
        if (index == -1) {
            return word;
        }

        String prefix = new StringBuilder(word.substring(0, index + 1)).reverse().toString();
        String suffix = word.substring(index + 1);

        return prefix + suffix;
    }
}

Time Complexity

Overall, the time complexity for the operation is O(n).

This strategy and implementation ensure that the solution is efficient and meets the problem constraints effectively.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI