How can you replace the string 'english' with 'maths' in place, and vice versa, within a list?
💡 Model Answer
To swap 'english' with 'maths' in a list in place, iterate over the list and replace each occurrence. A simple approach uses a dictionary mapping and a for loop: lst = ['science', 'social', 'maths', 'english']; mapping = {'english': 'maths', 'maths': 'english'}; for i, val in enumerate(lst): if val in mapping: lst[i] = mapping[val]; After the loop, lst becomes ['science', 'social', 'english', 'maths']. This method runs in O(n) time and uses O(1) extra space, performing the swap directly on the original list without creating a new list. If you prefer not to use a mapping, you can also use a simple two‑pointer swap: find the indices of 'english' and 'maths' and exchange them. For example: idx_english = lst.index('english'); idx_maths = lst.index('maths'); lst[idx_english], lst[idx_maths] = lst[idx_maths], lst[idx_english]. This approach also runs in O(n) time and is straightforward when you know both values exist. In both cases, the list is modified in place, so no additional memory is allocated for a new list.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500