Find All Lonely Numbers in the Array — LeetCode 2150 Python Solution

MediumArrayHash TableCounting
Problem
#2150
Pattern
Hash Map
Reading time
2 min

The problem

You are given an integer array nums. A number x is lonely when it appears only once, and no adjacent numbers (i.e.

Example

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.

Python solution

Python
class Solution:
    def findLonely(self, nums: List[int]) -> List[int]:
        cnt = Counter(nums)
        return [
            x for x, v in cnt.items() if v == 1 and cnt[x - 1] == 0 and cnt[x + 1] == 0
        ]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2150. Find All Lonely Numbers in the Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2150. Find All Lonely Numbers in the Array?
LeetCode 2150. Find All Lonely Numbers in the Array is rated Medium on LeetCode.
What is the time complexity of LeetCode 2150. Find All Lonely Numbers in the Array?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2150. Find All Lonely Numbers in the Array?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2150. Find All Lonely Numbers in the Array cover?
LeetCode 2150. Find All Lonely Numbers in the Array is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview