Start learning free

LESSON 143 OF 409 · LOOPS & GLOBAL VARIABLES

H4ck3r Sp34k in C++ (Time Complexity: O(n))

Practice Read the full explanation

Given a string, write a function that returns a coded (h4ck3r 5p34k) version of the string.

In order to work properly, the function should replace all "a"s with 4, "e"s with 3, "i"s with 1, "o"s with 0, and "s"s with 5.

Example 1:

Input:  "javascript is cool"

Output: "j4v45cr1pt 15 c00l"

Example 2:

Input:  "programming is fun"

Output: "pr0gr4mm1ng 15 fun"

Example 3:

Input:  "become a coder"

Output: "b3c0m3 4 c0d3r"
Hints:

We have to iterate through every character of input, check for each scenario and treat it accordingly:
  • Is it an 'a'? If so, replace with '4'. Otherwise:
  • Is it an 'e'? If so, replace with '3'. Otherwise:
  • Is it an 'i'? If so, replace with '1'. Otherwise:
  • Is it an 'o'? If so, replace with '0'. Otherwise:
  • Is it an 's'? If so, replace with '5'. Otherwise, keep it as it is.
In many languages strings are immutable, so we don't change input in place. How does that affect us? How can we put this strategy into code?

In many languages strings are immutable, which means you cannot directly change a character of a string (for example, assigning '4' to the character at index 4 of input). So we create a new string where we will store the solution as we build it. How can we translate these two hints in code?

Let's create a new string named solution, initially empty, where we will push all the encoded characters of input. We will use a for loop and a character variable c to iterate through input and treat the scenarios inside the loop:
  • Start with solution as an empty string.
  • For each character c of input: if c is 'a', append '4' to solution; if it is 'e', append '3'; if 'i', append '1'; if 'o', append '0'; if 's', append '5'; otherwise append c itself.
  • After the loop, return solution.


We have a for loop that performs exactly n iterations (n is the length of input), thus the Time Complexity is O(n).
The extra space we use is the extra string solution. Its length will be n in the end, thus the Extra Space used is also O(n).
(This assumes appending a character takes constant time. In languages where += on an immutable string copies the whole string each time, the running time can be closer to O(n2).)
STEP 1 OF 9
    Ctrl + Enter to check

    C++ · LOOPS & GLOBAL VARIABLES

    Hacker Speak in C++, explained

    Understanding the Problem

    The core challenge of this problem is to iterate through each character of the input string and replace specific characters with their corresponding "h4ck3r sp34k" equivalents. This type of problem is common in text processing and can be useful in various applications such as encoding messages or creating stylized text.

    Potential pitfalls include forgetting that strings are immutable in many programming languages, meaning you cannot change a character in place. Instead, you need to build a new string with the desired modifications.

    Approach

    To solve this problem, we can use a straightforward approach:

    1. Create an empty string to store the result.
    2. Iterate through each character of the input string.
    3. For each character, check if it matches one of the characters to be replaced ('a', 'e', 'i', 'o', 's').
    4. If it matches, append the corresponding replacement character to the result string.
    5. If it does not match, append the original character to the result string.
    6. Return the result string.

    This approach ensures that we process each character exactly once, making it efficient with a time complexity of O(n), where n is the length of the input string.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Initialize an empty string result.
    2. Iterate through each character c in the input string.
    3. Use a series of if-else statements to check if c is 'a', 'e', 'i', 'o', or 's'.
    4. If c matches one of these characters, append the corresponding replacement character to result.
    5. If c does not match any of these characters, append c itself to result.
    6. After the loop, return result.

    Code Implementation

    
    #include <iostream>
    #include <string>
    
    std::string toHackerSpeak(const std::string& input) {
        std::string result;
        for (char c : input) {
            if (c == 'a') {
                result += '4';
            } else if (c == 'e') {
                result += '3';
            } else if (c == 'i') {
                result += '1';
            } else if (c == 'o') {
                result += '0';
            } else if (c == 's') {
                result += '5';
            } else {
                result += c;
            }
        }
        return result;
    }
    
    int main() {
        std::string input1 = "javascript is cool";
        std::string input2 = "programming is fun";
        std::string input3 = "become a coder";
    
        std::cout << toHackerSpeak(input1) << std::endl;
        std::cout << toHackerSpeak(input2) << std::endl;
        std::cout << toHackerSpeak(input3) << std::endl;
    
        return 0;
    }
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the length of the input string. This is because we iterate through each character of the string exactly once.

    The space complexity is also O(n) because we create a new string to store the result, which in the worst case will be the same length as the input string.

    Edge Cases

    Potential edge cases include:

    • An empty input string: The function should return an empty string.
    • A string with no characters to be replaced: The function should return the original string.
    • A string with all characters to be replaced: The function should correctly replace all characters.

    Examples:

    Input: ""
    Output: ""
    
    Input: "hello"
    Output: "h3ll0"
    
    Input: "aeios"
    Output: "43105"
    

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Simple cases with a few characters to be replaced.
    • Edge cases such as an empty string or a string with no characters to be replaced.
    • Complex cases with a mix of characters to be replaced and characters to remain unchanged.

    Using a testing framework like Google Test can help automate and manage these test cases effectively.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller, manageable parts.
    • Think about the constraints and edge cases early on.
    • Write pseudocode to outline your approach before jumping into coding.
    • Test your solution with a variety of test cases to ensure its correctness.

    Practicing similar problems and studying different algorithms can help improve your problem-solving skills.

    Conclusion

    In this blog post, we discussed how to solve the problem of converting a string to "h4ck3r sp34k" in C++. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is important for developing strong problem-solving skills and improving your ability to work with text processing tasks.

    We encourage you to practice and explore further to deepen your understanding and proficiency in solving similar problems.

    Additional Resources

    For further reading and practice problems related to this topic, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free