Check If N and Its Double Exist - Problem

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]

Return true if such indices exist, otherwise return false.

Input & Output

Example 1 — Basic Double Found
$ Input: arr = [10,2,5,3]
Output: true
💡 Note: We can find 10 and 5 where 10 == 2 * 5, so there exists i=0 and j=2 such that arr[i] == 2 * arr[j]
Example 2 — No Double Exists
$ Input: arr = [3,1,7,11]
Output: false
💡 Note: No element in the array is exactly double another element: 3≠2×1, 3≠2×7, 3≠2×11, and no other pairs work
Example 3 — Zero Edge Case
$ Input: arr = [0,0]
Output: true
💡 Note: We have two zeros, and 0 == 2 * 0, so arr[0] == 2 * arr[1] with different indices i=0, j=1

Constraints

  • 2 ≤ arr.length ≤ 500
  • -103 ≤ arr[i] ≤ 103

Visualization

Tap to expand
Check If N and Its Double Exist INPUT Array: arr 10 i=0 2 i=1 5 i=2 3 i=3 Find: arr[i] == 2 * arr[j] Match Found: arr[0]=10 == 2 * arr[2]=5 Input Values: arr = [10, 2, 5, 3] ALGORITHM STEPS 1 Initialize HashSet Create empty set to store visited numbers 2 Iterate Array For each element n, check conditions 3 Check Conditions If 2*n in set OR n/2 in set --> true 4 Add to Set Add current number to HashSet HashSet Progress: n=10: set={} check 20,5 n=2: set={10} check 4,1 n=5: set={10,2} 2*5=10 OK! FINAL RESULT true Match Confirmed: i=0, j=2 arr[0] = 2 * arr[2] 10 = 2 * 5 Output: true Pair Exists - OK Key Insight: Using a HashSet allows O(1) lookup time for checking if the double (2*n) or half (n/2) of the current element already exists. This reduces time complexity from O(n^2) brute force to O(n) linear time. We check both 2*n AND n/2 to handle both directions of the relationship. TutorialsPoint - Check If N and Its Double Exist | Hash Set Optimization
Asked in
Google 12 Amazon 8 Microsoft 6 Apple 4
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen