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 in Array INPUT nums = [10, 6, 5, 8] 10 idx 0 6 idx 1 5 idx 2 8 idx 3 Adjacent Numbers: 10: neighbors 9, 11 6: neighbors 5, 7 5: neighbors 4, 6 8: neighbors 7, 9 Lonely Condition: x appears once AND x-1, x+1 not in array ALGORITHM STEPS 1 Build Frequency Map Count occurrences of each num {10:1, 6:1, 5:1, 8:1} All numbers appear exactly once 2 Create Number Set For O(1) neighbor lookup numSet = {10, 6, 5, 8} 3 Check Each Number freq==1 AND no x-1, x+1 10: 9? NO 11? NO --> OK 6: 5? YES --> SKIP 5: 6? YES --> SKIP 8: 7? NO 9? NO --> OK 4 Collect Lonely Numbers Add passing numbers to result FINAL RESULT Lonely Numbers Found: 10 8 Why They're Lonely: 10: No 9 or 11 in array 8: No 7 or 9 in array Both appear only once! Output Array: [10, 8] OK - 2 lonely numbers found Key Insight: Using a Set for O(1) lookups allows checking adjacent numbers (x-1 and x+1) efficiently. Combined with a frequency map, we achieve O(n) time complexity in a single pass approach. Numbers 6 and 5 are adjacent to each other, so neither can be lonely regardless of frequency. TutorialsPoint - Find All Lonely Numbers in the Array | Single Pass with Set Approach
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