Skip to main content

2150. Find All Lonely Numbers in the Array

Problem Description​

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.

Examples​

Example 1:

Input: nums = [10,6,5,8]
Output: [10,8]
Explanation:
- 10 is a lonely number since it appears exactly once and 9 and 11 does not appear in nums.
- 8 is a lonely number since it appears exactly once and 7 and 9 does not appear in nums.
- 5 is not a lonely number since 6 appears in nums and vice versa.
Hence, the lonely numbers in nums are [10, 8].
Note that [8, 10] may also be returned.

Example 2:

Input: nums = [1,3,5,3]
Output: [1,5]
Explanation:
- 1 is a lonely number since it appears exactly once and 0 and 2 does not appear in nums.
- 5 is a lonely number since it appears exactly once and 4 and 6 does not appear in nums.
- 3 is not a lonely number since it appears twice.
Hence, the lonely numbers in nums are [1, 5].
Note that [5, 1] may also be returned.

Constraints​

  • 0 <= nums.length <= 10^5

Solution for 2150. Find All Lonely Numbers in the Array​

1. Count Frequencies​

  • Use a map (or dictionary) to count the frequency of each number in the array.

2. Identify Lonely Numbers​

  • Iterate through the map (or dictionary) to find numbers that appear exactly once and do not have adjacent numbers (num-1 and num+1) present in the map.

3. Return the Result​

  • Collect all such lonely numbers in a list and return the list.

Implementation​

Live Editor
function findLonely(nums) {
let ans = [];
let mp = {};

for (let i of nums) {
    mp[i] = (mp[i] || 0) + 1;
}

for (let key in mp) {
    if (mp[key] === 1) {
        if (mp.hasOwnProperty(key - 1) || mp.hasOwnProperty(Number(key) + 1)) {
            continue;
        } else {
            ans.push(Number(key));
        }
    }
}
return ans;
}
  const input  = [10,6,5,8]
  const output = findLonely(input)
  return (
    <div>
      <p>
        <b>Input: </b>
        {JSON.stringify(input)}
      </p>
      <p>
        <b>Output:</b> {output.toString()}
      </p>
    </div>
  );
}
Result
Loading...

Complexity Analysis​

  • Time Complexity: O(nlogn)O(nlogn)
  • Space Complexity: O(n) O(n)

Code in Different Languages​

Written by @hiteshgahanolia
class Solution {
findLonely(nums) {
let ans = [];
let mp = new Map();

for (let i of nums) {
mp.set(i, (mp.get(i) || 0) + 1);
}

for (let [key, value] of mp) {
if (value === 1) {
if (mp.has(key - 1) || mp.has(key + 1)) {
continue;
} else {
ans.push(key);
}
}
}
return ans;
}
}

References​