DEV Community


Discussion on: Day- 2 Given an integer array arr, count element x such that x + 1 is also in arr.

philipstarkey profile image
Phil Starkey

I suspect using a collections.Counter dict would be beneficial. If you convert the input list to one of those you can then just iterate over the keys and check if dict[dict[key]+1] > 0, and if yes, add dict[key] to a running summation.

The loop would be O(N) and dictionary lookup is typically O(1), which I think would be faster than your algorithm above.

The question is whether the initial conversion of input data is performant, which I don't know! But from a practical point of view, collections.Counter is good to know about!

mridubhatnagar profile image
Mridu Bhatnagar Author

Hey Phil, thank you for suggesting the collections.Counter approach. I am yet to check out that module. But, yes I did read it somewhere it helps in achieving efficiency.

Also, with these, I am purposefully avoiding using libraries. :)