Write a method that takes two lists L1 and L2 of equal length and returns a new list where L1 is reordered to match the order of L2.
1Times asked
Jul 2026Last seen
Jul 2026First seen
š” Model Answer
The approach is to map each element of L2 to its index and then sort L1 using that mapping. In C#:
csharp
List<int> Reorder(List<int> l1, List<int> l2)
{
var indexMap = l2.Select((v, i) => new { v, i })
.ToDictionary(x => x.v, x => x.i);
return l1.OrderBy(x => indexMap[x]).ToList();
}This solution has O(n log n) time complexity because of the ordering operation and O(n) space for the dictionary. If the input lists are large and performance critical, you can avoid sorting by creating an output array and placing each element of L1 at the position indicated by the mapping, which runs in O(n) time.
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