For each element x in the array, we need to check whether x + 1 also exists in the array. The straightforward approach is to scan through the entire array for each element to verify if its successor is present. While this works correctly, it requires a linear search for every element.
Algorithm
Initialize a counter to 0.
For each element x in the array, iterate through the array to check if x + 1 exists.
classSolution:defcountElements(self, arr: List[int])->int:
count =0for x in arr:if x +1in arr:
count +=1return count
Time & Space Complexity
Time complexity: O(N2)
Space complexity: O(1) constant space
Where N is the length of the input array arr.
2. Search with HashSet
Intuition
The brute force approach is slow because checking if x + 1 exists requires scanning the entire array. A hash set provides O(1) lookup time, so we can first store all elements in a set, then check for each element's successor in constant time.
Algorithm
Insert all elements from the array into a hash set.
Initialize a counter to 0.
For each element x in the array, check if x + 1 exists in the hash set.
classSolution:defcountElements(self, arr: List[int])->int:
hash_set =set(arr)
count =0for x in arr:if x +1in hash_set:
count +=1return count
Time & Space Complexity
Time complexity: O(N)
Space complexity: O(N)
Where N is the length of the input array arr.
3. Search with Sorted Array
Intuition
Sorting brings equal elements together and places consecutive values next to each other. After sorting, we can traverse the array once and track "runs" of identical values. When we encounter a new value that is exactly one more than the previous value, all elements in the previous run satisfy the condition.
Algorithm
Sort the array.
Initialize a counter and a run length tracker (starting at 1).
Iterate through the sorted array starting from index 1.
If the current element differs from the previous one:
If the current element equals the previous element plus 1, add the run length to the counter.
Reset the run length to 0.
Increment the run length for each element processed.
The overall space complexity is dependent on the space complexity of the sorting algorithm you're using. The space complexity of sorting algorithms built into programming languages are generally anywhere from O(N) to O(1).