1

Problem is to return removed duplicated numbers in array. link

This is solution.

    dict1={}
    arr=[]
    for i in nums:
        if i not in dict1:
            dict1[i]=1
            arr.append(i)
    nums[:]=arr
    return len(nums)

This is my approach... Why is it not working?

    hash = {}
    for num in nums:
        if num in hash:
            nums.remove(num)
        hash[num] = num
    return len(nums)

I've been working on this problem more than 30 minutes :(

8
  • is it a function? Commented May 28, 2018 at 10:26
  • or 2 functions? Commented May 28, 2018 at 10:26
  • Just added return statement. And yes, these are two separate functions. Thanks! Commented May 28, 2018 at 10:30
  • How does for-loop work in Python when you remove elements on the fly? Commented May 28, 2018 at 10:33
  • @MBo - in general it screws things up in one or more ways. Commented May 28, 2018 at 10:34

1 Answer 1

3

From an algorithm point of view, the second one does not look good as the remove have a higher time complexity than the hash insertion and deletion. Therefore, the removal time is more than O(1). The first implementation uses an additional list. Also, instead of maintaining another array you can also do list (hash.keys ()) and return it.

Python list removal is O(n) for both average and amortized case (check https://wiki.python.org/moin/TimeComplexity?), but dict operation is O(1) in average case and O(n) amortized time. In this case I marking the elements in a dict and then returning the keys is a better idea.

Although, in this case I think using a set set to mark the unique items may be a better idea, as it will not only be faster, but also lighter on memory.

From the code point of view, do not modify a list which you are iterating through, unless you access and modify the list using index and take care of the list modification and index manipulation yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Need to study based on your answer. Thank you so much and I feel like I need to learn more from you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.