Given three lists: A, B and C of length n each. if any 3 three numbers (1 from each list), sum up to zero return true.I want to solve this with o(n)complexity.I have sorted the lists and I can think of creating either a hash map with sum of 2 linked lists or comparing 3 lists together[o(n*n*n)].Suggest some ways to improvise the methods to reduce complexity..I can’t think of any…Thanks in adv
Share
I do not think it is possible in
o(n²)(i.e. really better thann²), but it can be done inO(n²)(i.e. sth. liken²) as follows:First of all, reverse list
Bto obtainB'(takesO(n)time), a list whose items are sorted in descending order. First, we consider the problem of finding two elements in the listsAandB'that sum to any given number:We can do this like the following (Python code):
Run time of the above is
O(n). Additional space required isO(1)since we only have to store two pointers. Note that the above can be easily transformed such that it works with doubly linked lists.Then, overall we just have to do the following:
That results in running time
O(n²)and additional spaceO(1).