< Back

1426. Counting Elements

We have an integer array. For each integer, x, in the array, how many times does x + 1 appear? Count

To easily solve this, we use a set() to conduct a lookup in O(1) time, placing all values of the
input array into the set. Then, we just iterate through the entire list, checking each value, x. If
x + 1 is in the set we created, we increase the count.

The solution is as follows:

  class Solution:
      def countElements(self, arr: List[int]) -> int:
          set_arr = set(arr)
          count = 0

          for num in arr:
              if num + 1 in set_arr:
                  count += 1

          return count

_ Time Complexity:

  O(n) - We have to iterate through the entire input array.

_ Space Complexity:

  O(n) - We have to create a set to store the input array.