1346 - Check If N and Its Double Exist

Given an array arr of integers, check if there exist two indices i and j such that :

  • i != j
  • 0 <= i, j < arr.length
  • arr[i] == 2 * arr[j]

 Example 1:

Input: arr = [10,2,5,3]
Output: true
Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j]

Example 2:

Input: arr = [3,1,7,11]
Output: false
Explanation: There is no i and j that satisfy the conditions.

 Constraints:

  • 2 <= arr.length <= 500
  • -103 <= arr[i] <= 103

C++

  • class Solution {
    public:
        bool checkIfExist(vector<int>& arr) {
            unordered_map<int, int> m;
            int n = arr.size();
            for (int i = 0; i < n; ++i) m[arr[i]] = i;
            for (int i = 0; i < n; ++i)
                if (m.count(arr[i] * 2) && m[arr[i] * 2] != i)
                    return true;
            return false;
        }
    };

JAVA

  • class Solution {
        public boolean checkIfExist(int[] arr) {
            Map<Integer, Integer> m = new HashMap<>();
            int n = arr.length;
            for (int i = 0; i < n; ++i) {
                m.put(arr[i], i);
            }
            for (int i = 0; i < n; ++i) {
                if (m.containsKey(arr[i] << 1) && m.get(arr[i] << 1) != i) {
                    return true;
                }
            }
            return false;
        }
    }

PYTHON

  • class Solution:
        def checkIfExist(self, arr):
            m = {}
            n = len(arr)
            for i in range(n):
                m[arr[i]] = i
            for i in range(n):
                if arr[i] * 2 in m and m[arr[i] * 2] != i:
                    return True
            return False

Comments