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
Find All Lonely Numbers: [10,6,5,8] → [10,8]10658Count: 1Count: 1Count: 1Count: 19,11: None5,7: 5 exists4,6: 6 exists7,9: NoneLonely Definition: appears once AND no adjacent numbers (±1) exist✓ 10: appears once, no 9 or 11 in array✗ 6: appears once but 5 exists (adjacent)✗ 5: appears once but 6 exists (adjacent)✓ 8: appears once, no 7 or 9 in arrayResult: [10, 8]
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
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
34.2K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen