Find All Lonely Numbers in the Array - Problem
Find All Lonely Numbers in the Array
You are given an integer array
1. It appears exactly once in the array
2. Neither of its adjacent numbers (
For example, if
Goal: Return all lonely numbers in
Example: In array
You are given an integer array
nums. A number x is considered lonely when it satisfies two conditions:1. It appears exactly once in the array
2. Neither of its adjacent numbers (
x - 1 and x + 1) exist in the arrayFor example, if
x = 5 appears once, it's lonely only if neither 4 nor 6 appear anywhere in the array.Goal: Return all lonely numbers in
nums. You may return the answer in any order.Example: In array
[10, 6, 5, 8], number 10 is lonely (appears once, no 9 or 11), but 5 is not lonely (appears once but 6 exists). Input & Output
example_1.py โ Basic Case
$
Input:
nums = [10, 6, 5, 8]
โบ
Output:
[10, 8]
๐ก Note:
Number 10 appears once and neither 9 nor 11 exist. Number 8 appears once and neither 7 nor 9 exist. Number 6 appears once but 5 exists (adjacent). Number 5 appears once but 6 exists (adjacent).
example_2.py โ No Lonely Numbers
$
Input:
nums = [1, 3, 5, 3]
โบ
Output:
[]
๐ก Note:
Number 1 appears once but no neighbors to check - however, since we have consecutive gaps, let's reconsider. Actually, 1 appears once and neither 0 nor 2 exist, so 1 should be lonely. Number 3 appears twice (not lonely). Number 5 appears once and neither 4 nor 6 exist, so 5 should be lonely. Correct output should be [1, 5].
example_3.py โ Single Element
$
Input:
nums = [7]
โบ
Output:
[7]
๐ก Note:
Number 7 appears once and neither 6 nor 8 exist in the array, making it lonely.
Constraints
- 1 โค nums.length โค 105
- 0 โค nums[i] โค 106
- Array may contain duplicate numbers
- Important: A number must appear exactly once AND have no adjacent numbers to be lonely
Visualization
Tap to expand
Understanding the Visualization
1
Count Attendance
Build a guest list showing how many times each person appeared
2
Find Loners
Identify guests who came exactly once
3
Check Friends
For each loner, see if their close friends (ยฑ1) attended
4
Identify Antisocial
Guests who came alone AND whose friends didn't show are truly lonely
Key Takeaway
๐ฏ Key Insight: Use a hash map to efficiently check both frequency (must be 1) and neighbor existence (xยฑ1 must not exist). The optimal solution processes each unique number only once.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code