DEV Community

Cover image for LeetCode Challenge: Counting Elements
Bharath Sriraam R R
Bharath Sriraam R R

Posted on

1 1

LeetCode Challenge: Counting Elements

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

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:

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

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:

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,

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (1)

Collapse
 
rockzo77 profile image
Aman kumar •

This problem is explained very well. Such articles are really helpful.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay