VOOZH about

URL: https://www.geeksforgeeks.org/dsa/urlify-a-given-string-replace-spaces/

⇱ URLify a given string (Replace spaces with %20) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

URLify a given string (Replace spaces with %20)

Last Updated : 11 Apr, 2026

Given a string s, replace all the spaces in the string with '%20'.

Examples:

Input: s = "i love programming"
Output: i%20love%20programming
Explanation: The 2 spaces are replaced by '%20'

Input: s = "ab cd"
Output: ab%20cd

[Approach] Traverse the String - O(n) Time and O(n) Space

The idea is to iterate through each character of the input string and build a new string (or result container). Whenever a space character is encountered, replace it with the string "%20", otherwise append the current character as it is.

Dry run for s = "g ee ks":

  1. For i = 0, 'g' is not a space, so it is appended to result, making it "g".
  2. For i = 1, ' ' is a space, so "%20" is appended, making result = "g%20".
  3. For i = 2, 'e' is not a space, so it is appended, making result = "g%20e".
  4. For i = 3, 'e' is not a space, so it is appended, making result = "g%20ee".
  5. For i = 4, ' ' is a space, so "%20" is appended, making result = "g%20ee%20".
  6. For i = 5, 'k' is not a space, so it is appended, making result = "g%20ee%20k".
  7. For i = 6, 's' is not a space, so it is appended, making result = "g%20ee%20ks".

Traversal is complete, so the final result "g%20ee%20ks" is returned.


Output
i%20love%20programming
Comment
Article Tags: