LeetCode 2150: Find All Lonely Numbers in the Array Solution

Master LeetCode problem 2150 (Find All Lonely Numbers in the Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2150. Find All Lonely Numbers in the Array

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and keep track of the count of each element. Then, we iterate through the array again and check if the current element is a lonely number based on the conditions mentioned in the problem. If it is a lonely number, we add it to the result list.

Algorithm:

  1. Create a HashMap to store the count of each element in the array.
  2. Iterate through the array and update the count of each element in the HashMap.
  3. Iterate through the array again, and for each element:
    • Check if the current element is a lonely number by verifying that its count is 1 and its adjacent numbers are not present in the HashMap.
    • If it is a lonely number, add it to the result list.
  4. Return the result list.

Time Complexity: O(n) where n is the number of elements in the array. Space Complexity: O(n) for the HashMap to store the counts.

Solution Code

import java.util.*;

class Solution {
    public List<Integer> findLonelyNumbers(int[] nums) {
        List<Integer> result = new ArrayList<>();
        Map<Integer, Integer> countMap = new HashMap<>();
        
        for (int num : nums) {
            countMap.put(num, countMap.getOrDefault(num, 0) + 1);
        }
        
        for (int num : nums) {
            if (countMap.get(num) == 1 && !countMap.containsKey(num - 1) && !countMap.containsKey(num + 1)) {
                result.add(num);
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2150 (Find All Lonely Numbers in the Array)?

This page provides optimized solutions for LeetCode problem 2150 (Find All Lonely Numbers in the Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2150 (Find All Lonely Numbers in the Array)?

The time complexity for LeetCode 2150 (Find All Lonely Numbers in the Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2150 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2150 in Java, C++, or Python.

Back to LeetCode Solutions