Skip to main content
Back to problems
#2150
Medium Algorithms

Find all lonely numbers in the array

Array Hash Table Counting
62.7% acceptance
Feb 25, 2026
704
67
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_lonely(nums: Vec<i32>) -> Vec<i32> {
    use std::collections::HashMap;
    let mut count: HashMap<i32, i32> = HashMap::new();
    for &n in &nums {
      *count.entry(n).or_insert(0) += 1;
    }
    let mut result = Vec::new();
    for (x, c) in &count {
      if *c == 1 && !count.contains_key(&(*x - 1)) && !count.contains_key(&(*x + 1)) {
        result.push(*x);
      }
    }
    result
  }
}