LeetCode Entry

2000. Reverse Prefix of Word

01.05.2024 easy 2024 kotlin rust

Reverse [..ch] prefix in string

2000. Reverse Prefix of Word easy blog post substack youtube 2024-05-01_09-09.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/589

Problem TLDR

Reverse [..ch] prefix in string #easy

Intuition

First find the position, then reverse the prefix.

Approach

Can you make the code shorter? (Don’t do this in the interview, however, we skipped optimized case of not found index.)

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\)

Code


    fun reversePrefix(word: String, ch: Char) = String(
        word.toCharArray().apply { reverse(0, indexOf(ch) + 1) }
    )


    pub fn reverse_prefix(mut word: String, ch: char) -> String {
        let i = word.find(ch).unwrap_or(0) + 1;
        word[..i].chars().rev().chain(word[i..].chars()).collect()
    }