DDSA Solutions

URLify a given string

Time: O(n)
Space: O(n)
Advertisement

Intuition

Replace spaces in string with "%20". Process from end to avoid extra shifting.

Algorithm

  1. 1Count spaces. Expand array. Two pointers from end: copy non-space chars, insert "%20" for spaces.

Common Pitfalls

  • Classic CTCI problem. Expand in-place from end to avoid O(n^2) shifting. O(n).
URLify a given string.java
Java
// Approach: Traverse characters and build the result; replace each space with "%20"
// and append non-space characters directly using StringBuilder.
// Time: O(n) Space: O(n)
class Solution {

    String URLify(String s) {
        StringBuilder res = new StringBuilder();
        for (char c : s.toCharArray()) {
            if (c == ' ') {
                res.append("%20");
            } else {
                res.append(c);
            }
        }
        return res.toString();
    }
}
Advertisement
Was this solution helpful?