The Indian Engineer

Problem 1346 Check If N and Its Double Exist

Posted on 4 mins

Array Hash-Table Two-Pointers Binary-Search Sorting

Problem Statement

Link - Problem 1346

Question

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

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:

Solution

class Solution {
public:
    bool checkIfExist(vector<int>& arr) {
        unordered_map<int,int>check;
        for(auto num:arr){
            check[num]++;
        }
        for(auto num:arr){
            if(num!= 0 && check.find(num*2)!=check.end())
                return true;
            if(num == 0 && check[num]>1)
                return true;
        }
        return false;

    }
};

Complexity Analysis

| Algorithm     | Time Complexity | Space Complexity |
| ------------- | --------------- | ---------------- |
| Hash counting | O(n)            | O(n)             |

Explanation

Intial Thoughts

First, consider the nature of the problem which is to find two indices, i and j, with the given constraints. Since the array can be quite large, we need an efficient strategy. A key point is to think of the relationship arr[i] == 2 * arr[j] in terms of pairs of numbers. Is there an existing data structure that can efficiently store these pairs?

Intuitive Analysis

A crucial insight is to recognize that this problem can be solved using a dictionary-like data structure for storing numbers as keys. An intuitive explanation would be the concept of checking for an existing key in a dictionary before adding a new one. This approach is efficient because it leads us to the optimal solution. Think of the potential differences when applying the given condition based on whether the number is zero or not. What special considerations should be taken into account for zero?

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Easy difficulty.

Hints

Loop from i = 0 to arr.length, maintaining in a hashTable the array elements from [0, i - 1].

On each step of the loop check if we have seen the element 2 * arr[i] so far.

Also check if we have seen arr[i] / 2 in case arr[i] % 2 == 0.


Similar Questions:

Title URL Difficulty
Keep Multiplying Found Values by Two https://leetcode.com/problems/keep-multiplying-found-values-by-two Easy