Find All Lonely Numbers in the Array - Problem
You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e. x + 1 and x - 1) appear in the array.
Return all lonely numbers in nums. You may return the answer in any order.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [10,6,5,8]
›
Output:
[10,8]
💡 Note:
10 appears once and neither 9 nor 11 exist. 8 appears once and neither 7 nor 9 exist. 6 and 5 have each other as neighbors.
Example 2 — With Duplicates
$
Input:
nums = [1,3,5,3]
›
Output:
[1,5]
💡 Note:
1 appears once with no neighbors (0,2 missing). 5 appears once with no neighbors (4,6 missing). 3 appears twice so it's not lonely.
Example 3 — No Lonely Numbers
$
Input:
nums = [1,2,3,4]
›
Output:
[]
💡 Note:
Each number has at least one adjacent neighbor: 1 has 2, 2 has 1&3, 3 has 2&4, 4 has 3.
Constraints
- 1 ≤ nums.length ≤ 105
- -105 ≤ nums[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [10,6,5,8] - check each number's loneliness
2
Lonely Check
Number x is lonely if: count(x)=1 AND x-1∉array AND x+1∉array
3
Result
Return all numbers meeting lonely criteria
Key Takeaway
🎯 Key Insight: A number is lonely only if it's unique AND isolated from its consecutive neighbors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code