Skip to content

Instantly share code, notes, and snippets.

@rejoycesong
Last active April 7, 2020 19:11
Show Gist options
  • Save rejoycesong/fca710955aba9bc2d5fb393f143fd7e1 to your computer and use it in GitHub Desktop.
Save rejoycesong/fca710955aba9bc2d5fb393f143fd7e1 to your computer and use it in GitHub Desktop.
# no runtime given, but O(n)
class Solution:
def countElements(self, arr: List[int]) -> int:
seen = set(arr)
return sum([1 if n+1 in seen else 0 for n in arr])
# 28ms with reduce; also O(n)
class Solution:
def countElements(self, arr: List[int]) -> int:
seen = set(arr)
return reduce(lambda accumulated, x: accumulated + (1 if x+1 in seen else 0), arr, 0)
# this one seems the fastest; didn't know you can sum over a generator directly without an iterable
class Solution:
def countElements(self, arr: List[int]) -> int:
seen = set(arr)
return sum(1 if n+1 in seen else 0 for n in arr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment