#2150
Find All Lonely Numbers in the Array
MediumArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a HashMap allows us to efficiently count occurrences of each number and then check for adjacent numbers in constant time. This significantly reduces the number of operations needed compared to the brute force approach.
⚙️
Algorithm
4 steps- 1Step 1: Create a frequency map to count occurrences of each number in the array.
- 2Step 2: Create a set from the array to allow O(1) lookups for adjacent numbers.
- 3Step 3: Iterate through the frequency map and for each number, check if it appears once and if its adjacent numbers are absent in the set.
- 4Step 4: Collect all such numbers into the result list.
solution.py9 lines
1def findLonelyNumbers(nums):
2 from collections import Counter
3 freq = Counter(nums)
4 num_set = set(nums)
5 lonely_numbers = []
6 for num in freq:
7 if freq[num] == 1 and (num - 1) not in num_set and (num + 1) not in num_set:
8 lonely_numbers.append(num)
9 return lonely_numbersℹ
Complexity note: The time complexity is O(n) because we traverse the array a couple of times (once for counting and once for checking conditions). The space complexity is O(n) due to the storage of the frequency map and the set.
- 1Lonely numbers must appear exactly once.
- 2Adjacent numbers must not be present in the array.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.