LeetCode Challenge: Counting Elements
Tags: computerscience, beginners, leetcode, problemsolving
Published: 2020-04-15 10:03:33

This is the last problem in Week 1 of the month-long LeetCode challenge.

Looks like this is the first of the 5 new questions that were promised to make things interesting.

# Problem
Given an integer array arr, count element x such that x + 1 is also in arr.

If there're duplicates in arr, count them separately.

__Example 1:__
```
Input: arr = [1,2,3]
Output: 2
Explanation: 1 and 2 are counted cause 2 and 3 are in arr.
```

__Example 2:__
```
Input: arr = [1,1,3,3,5,5,7,7]
Output: 0
Explanation: No numbers are counted, cause there's no 2, 4, 6, or 8 in arr.
```

__Example 3:__
```
Input: arr = [1,3,2,3,5,0]
Output: 3
Explanation: 0, 1 and 2 are counted cause 1, 2 and 3 are in arr.
```

__Example 4:__
```
Input: arr = [1,1,2,2]
Output: 2
Explanation: Two 1s are counted cause 2 is in arr.
```

__Constraints:__
```
1 <= arr.length <= 1000
0 <= arr[i] <= 1000
```

# Clarification
The first 3 test cases are kind of misleading because they don't really show what is actually expected from us. 

However, the last example gives some info.

From what we can observe, they're asking for the count of x in the array if x+1 also exists in the array.

# Approach 1: Space Optimized

![sasuke teleport](https://dev-to-uploads.s3.amazonaws.com/i/9hrhg91z0yfhzhz3npxd.gif)

If the array is sorted then x+1 will be right after x. But if there are multiple occurrences of x then the 1st x+1 will come after the last x.

So, we need to count the frequency of each x and if the next element is different we need to check if it is x+1 or not.

__Algorithm:__
1. Initialize variables count to store the final result and currCount to store the count of the current element that is being tracked.
2. Sort the array
3. Iterate through the array
4. If the current element is equal to the previous element then increment currCount
5. Else if the current element is 1 greater than the previous element then add currCount to count. Reset currCount.
6. Return count

__Code:__
```python
def approach1(arr):
    if len(arr) == 1:
        return 0
    
    arr = sorted(arr)
    count = 0
    currCount = 1
    
    for i in range(1, len(arr)):
        if arr[i] == arr[i-1]:
            currCount += 1
        else:
            if arr[i] == arr[i-1] + 1:
                count += currCount
            currCount = 1
    
    return count
```

__Complexity analysis:__
```
Time complexity: O(n*log(n)) 
Space complexity: O(1)
```

# Approach 2: Time Optimized

![minato fast](https://dev-to-uploads.s3.amazonaws.com/i/a52q37c79ryd0pv41fhy.gif)


Since we're dealing with counts we can use a hash map to maintain the count of each number and then easily check for the presence of the next number.

__Code:__
```python
def approach2(arr):
    count = 0
    freq = {}
    
    for num in arr:
        freq[num] = freq.get(num, 0) + 1
    
    for x in freq:
        if x+1 in freq:
            count += freq[x]
    
    return count
```

__Complexity analysis:__
```
Time complexity: O(n) 
Space complexity: O(n)
```

# Summary
Not many people talk about this but sometimes a programmer needs to consider the tradeoffs between space and time complexity of different solutions because not all situations have enough space to achieve optimal runtime complexity. The same applies the other way around.

As usual,
{% replit @13point5/Counting-elements %}