Replace Spaces

Easy
0/40
Average time to solve is 15m
profile
Contributed by
166 upvotes
Asked in companies
MicrosoftAmazonPayPal

Problem statement

You have been given a string 'STR' of words. You need to replace all the spaces between words with “@40”.

Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain a single string 'STR' consisting of one or more words. 
Output Format:
For each test case, return the modified string after replacing all the spaces between words with “@40”.

Print the output of each test case in a separate line.
Note:
You don’t need to print anything, It has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
0 <= |STR| <= 100

Where ‘|STR|’ is the length of a particular string including spaces.

Time limit: 1 sec
Sample Input 1:
2
Coding Ninjas Is A Coding Platform
Hello World
Sample Output 1:
Coding@40Ninjas@40Is@40A@40Coding@40Platform
Hello@40World
Explanation of Sample Output 1:
In test case 1, After replacing the spaces with “@40” string is: 

Coding@40Ninjas@40Is@40A@40Coding@40Platform

In test case 2, After replacing the spaces with “@40” string is: 

Hello@40World
Sample Input 2:
3
Hello
I love coding
Coding Ninjas India
Sample Output 2:
Hello
I@40love@40coding
Coding@40Ninjas@40India    
Explanation for Sample Output 2:
In test case 1, After replacing the spaces with “@40” string is: 

Hello

In test case 2, After replacing the spaces with “@40” string is: 

I@40love@40coding

In test case 3, After replacing the spaces with “@40” string is: 

Coding@40Ninjas@40India
Hint

Think about using another string

Approaches (2)
Using Another String

The basic idea is to use a separate string to store the resultant string. Copy characters from the original string to the resultant string one by one, and whenever there comes a space, simply add “@40” in the resultant string in place of the space.

 

The steps are as follows:

 

  • Initialise a string let’s say 'RES, to store the resultant string.
  • Start traversing through the string one by one and do the following:
    • If you come through space:
      • Add “@40” in place of space.
    • If it is any other character:
      • Simply add the character.
  • Return the resultant string ‘RES’.
Time Complexity

O(N), Where ‘N’ is the size of the string of words.

 

Since we are traversing through the complete string of words only once, the time complexity is O(N).

Space Complexity

O(N), Where ‘N’ is the size of the string of words.

 

Since we are using an auxiliary string to store the resultant string of words, the space complexity is O(N).

Code Solution
(100% EXP penalty)
Replace Spaces
Full screen
Console