Similar Problems

Similar Problems not available

Check If N And Its Double Exist - Leetcode Solution

Companies:

LeetCode:  Check If N And Its Double Exist Leetcode Solution

Difficulty: Easy

Topics: hash-table binary-search two-pointers array sorting  

Problem Statement:

Given an array of integers nums, check if there exists an element n such that there exists an element m in nums such that n = 2 * m.

Constraints:

1 <= nums.length <= 500 -10^3 <= nums[i] <= 10^3

Example 1: Input: nums = [10,2,5,3] Output: true Explanation: N is 10, and M is 5.

Example 2: Input: nums = [7,1,14,11] Output: true Explanation: N is 14, and M is 7.

Example 3: Input: nums = [3,1,7,11] Output: false Explanation: There is no such n and m in the array.

Solution:

This is a very simple problem, we just need to iterate over the given array, and for each number, we need to check if its double exists in the array or not. If it exists, we return true from the function, otherwise, we keep going.

Code:

Here is the Python code to solve this problem:

class Solution: def checkIfExist(self, nums: List[int]) -> bool: for i in range(len(nums)): if nums[i] * 2 in nums[:i] + nums[i+1:]: return True return False

Explanation:

We iterate over the given array using a for loop and check for each number if its double exists or not. We use the in operator to check if the number exists in the array or not. We add the nums[:i] and nums[i+1:] to exclude the ith index from the array while checking, because we don't want to compare a number with itself. If we find a number whose double exists in the array, we return True, otherwise, we return False at the end of the function.

Time Complexity:

The time complexity of this solution is O(n^2) because we are using a nested loop to check for each number if its double exists or not. In the worst case, we will have to check for each pair of numbers in the array.

Space Complexity:

The space complexity of this solution is O(1) because we are not using any extra space to solve this problem. We are just using the input array and some variables for looping and checking.

Check If N And Its Double Exist Solution Code

1