Feature #4: Optimization by Replacement

Implementing the "Optimization by Replacement" feature for our "Language Compiler" project.


For this language compiler feature, we want to add some additional optimization to the source code. Let’s say we have identified token locations, indices, that could potentially be replaced for optimization. The token for each of those indices is also given as a list, sources. Another list, targets, holds the strings that each of the tokens in sources should be replaced with. If token sources[i] is present at location indices[i] in the input, it should be replaced with the token targets[i]. Note that sources[i] and targets[i] may not necessarily be the same length

Suppose that the line of code we are given as input is foo(input, i);. The possible replacement operations can be performed at the indices [0, 11]. Also, the sources are ["foo", "i"], and the targets array is ["foobar", "j+1"]. Considering the example inputs, we can see that both operations are valid because the source token can be found at their respective indices. After applying the replacement operations, the line of code will become foobar(input, j+1).

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.