1346. Check If N and Its Double Exist (Solution || Leetcode Easy || Java)

Palakkgoyal
2 min readOct 28, 2022

--

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

SOLUTION:

class Solution {
public boolean checkIfExist(int[] arr) {
Arrays.sort(arr);//first sort the array to apply binary search

for(int i = 0; i < arr.length; i++){//traverse on every element to check for its double

int start = 0;//range for inary search
int end = arr.length -1;


while(start <= end){//applying binary search
int mid = start + (end — start)/2;

if(arr[mid] == 2*arr[i] && mid != i){//if found answer return index and mid != 1 condition is necessary as if the element is 0, then without this condition we will return the same index
return true;
}
else if(arr[mid] > 2*arr[i]){
end = mid — 1;
}else{
start = mid + 1;
}
}

}

return false;//if not found such pair of double return false
}
}

Thank you for reading. If you have any queries, please let me know in the comment section.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet