Problem Statement
Replace all spaces in a string with %20
, similar to URL encoding.
Example Inputs
- Input:
"Mr John Smith"
- Output:
"Mr%20John%20Smith"
- Input:
"Hello World"
- Input:
" OpenAI GPT "
- Output:
"%20OpenAI%20GPT%20"
- Input:
"URL encoding test"
- Output:
"URL%20encoding%20test"
JavaScript Method - Using Only String Methods
Approach
To replace all spaces in a string with %20
, we can use the JavaScript .replace()
method with a global regular expression that matches spaces.
Steps
- Use
.replace(/ /g, '%20')
to replace all spaces in the string with %20
.
- Return the modified string.
Time & Space Complexity
- Time Complexity: O(n), where n is the length of the string, as each character is processed once.
- Space Complexity: O(n), because a new string is created with
%20
replacing spaces.
Code Snippet
Dry Run
Example input: "Mr John Smith"
- Step 1:
str.replace(/ /g, '%20')
→ "Mr%20John%20Smith"
- Final output:
"Mr%20John%20Smith"
Alternative Approach - Using a Loop and Conditionals
Approach
We can build the URL-encoded string manually by iterating through each character in the original string and adding %20
for spaces and the character itself for all other characters.
Steps
- Initialize an empty string
encodedStr
.
- Loop through each character in the original string.
- If the character is a space, add
%20
to encodedStr
.
- If the character is not a space, add it to
encodedStr
.
- Return
encodedStr
as the final result.
Time & Space Complexity
- Time Complexity: O(n), as each character is processed once.
- Space Complexity: O(n), since a new string is created.
Code Snippet
Dry Run
Example input: "Mr John Smith"
- Initialize:
encodedStr = ""
- Loop through
"Mr John Smith"
:
- Add
M
→ encodedStr = "M"
- Add
r
→ encodedStr = "Mr"
- Add
%20
for space → encodedStr = "Mr%20"
- Add
J
→ encodedStr = "Mr%20J"
- Continue until all characters are processed.
- Final output:
"Mr%20John%20Smith"
Complexity Analysis
JavaScript Method (Using String Methods)
- Time Complexity: O(n)
- Space Complexity: O(n)
Alternative Approach (Using Loop and Conditionals)
- Time Complexity: O(n)
- Space Complexity: O(n)
Conclusion
Replacing spaces with %20
for URL encoding can be efficiently achieved using JavaScript’s .replace()
method with regular expressions. A manual approach with a loop is also effective and offers similar time complexity, making both options suitable for this task.