Start learning free

LESSON 174 OF 674 · LOOPS & GLOBAL VARIABLES

H4ck3r Sp34k

Practice

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