Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

need to re-write my code in less than O(n2) complexity

I have an algorithm written which gives result.
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But it is too slow,

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        res=[]
        for i in range(len(nums)):
            first_val=nums[i]
            second_val=target - nums[i]
            for j in range(len(nums)):
                if i!=j:
                    
                    if nums[j]==second_val:
                        res.append(i)
                        res.append(j)
                        return res
        return res

Could anyone assist me in rewriting this algorithm in Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

>Solution :

In O(n) time complexity it can be done as below code.

logic is as, since there is solution pair in the given input, ie sum of these value make up to target, ie val1 + val2 = target, so we need to iterate through the list and search for val2 = target – val1, if we found it then return result.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        info = {}
        for i, v in enumerate(nums):
            if target-v not in info:
                info[v] = i
            else:
                return [info[target-v], i]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading