-1

Say I have a list indices. I also have a character char. The third argument is a string string. I want to return a copy of string such that string[index] = char for all index in indices.

I do have a function that does this, but I believe that it is inefficient. It is

newString = string
for index in indices:
    newString = newString[:index] + char + newString[index+1:]

The first line makes a copy of the string. Then it iterates through all indices that need to be changed and makes the index equal to char.

According to this question, the efficiency of slicing a string is O(n), which would then make the efficiency of the above code O(nm), where n is the length of the string, and m is the length of indices. I was hoping for a faster solution.

Any improvement would be appreciated.

Edit: An example would be with string = "qwertyuoip", indices = [0, 4, 5, 8], char = "1". Then the 0th, 4th, 5th, and 8th character of string would be replaced with char. The output should be newString = "1wer11ui1p".

Varun Vejalla
  • 183
  • 1
  • 8

1 Answers1

0

Here's a solution using a mutable list:

def replace_indices(s, indices, char):
    chars = list(s)
    for i in indices:
        chars[i] = char
    return ''.join(chars)

The solution has three parts:

  • Build a list of characters from the string s. This takes O(n) time, where n is the length of s.
  • Iterate over the list of indices, setting the character char at each index in the list. This takes O(m) time, where m is the length of indices.
  • Join the list to produce the output string. This takes O(n) time to build a string of length n.

The total time is O(n + m). This is optimal, because the problem requires building a string of length n, and you have to use all m indices in the list. If the indices are always distinct, then m <= n and the time is O(n).

kaya3
  • 47,440
  • 4
  • 68
  • 97