Interview Bootcamp

0% completed

Solution: Counting Elements (easy)

Problem Statement

Given a list of integers, determine the count of numbers for which there exists another number in the list that is greater by exactly one unit.

In other words, for each number x in the list, if x + 1 also exists in the list, then x is considered for the count.

Examples:

  1. Example 1:

    • Input: [4, 3, 1, 5, 6]
    • Expected Output: 3
    • Justification: The numbers 4, 3, and 5 have 5, 4, and 6 respectively in the list, which are greater by exactly one unit.
  2. Example 2:

    • Input: [7, 8, 9, 10]
    • Expected Output: 3

.....

.....

.....

Like the course? Get enrolled and start learning!
Ionut Enescu

Ionut Enescu

· 2 years ago

    public int countElements(int[] arr) {         int count = 0;         Set<Integer> mySet = new HashSet<>();         for (int i = 0; i < arr.length; i++) {             mySet.add(arr[i]);             if (mySet.contains(arr[i] + 1) || mySet.contains(arr[i] - 1)) {                 count++;             }         }         return count;     }