String Join

Without using a built-in string join method, implement a join(arr, s) method, which receives an array of strings, arr, and a string, s, and returns a single string consisting of the strings in arr with s in between them.

Examples:

  • arr = ["join", "by", "space"], s = " "
    • Output: "join by space"
  • arr = ["b", "", "k", "", "p", "r n", "", "d", "d"], s = "ee"
    • Output: "beekeepeerneeeeddeed!!"

If strings in your language are immutable, assume that you have access to a function array_to_string(arr), which takes an array of individual characters and returns a string with those characters in O(len(arr))O(len(arr)) time.

1def join(arr: List[str], s: str) -> str:
2 if not arr:
3 return ""
4 res = []
5 for i in range(len(arr)):
6 res.append(arr[i])
7 if i < len(arr) - 1:
8 res.append(s)
9 return "".join(res)
,
0
s = ","
arr=["a", "b"]
s=,
res=
Step 1 / 5
Step 1:
Initialize result buffer
Focus: default
s=","res=""