Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Check if a number and its double exists in an array
When it is required to check if a number and its double exists in an array, we can iterate through the array and check if double of each element exists. Python provides multiple approaches to solve this problem efficiently.
Method 1: Using Nested Loops
This approach iterates through each element and checks if its double exists in the remaining elements ?
def check_double_exists(my_list):
for i in range(len(my_list)):
for j in (my_list[:i] + my_list[i+1:]):
if 2 * my_list[i] == j:
return True
return False
my_list = [67, 34, 89, 67, 90, 17, 23]
print("The list is:")
print(my_list)
if check_double_exists(my_list):
print("The double exists")
else:
print("The double does not exist")
The list is: [67, 34, 89, 67, 90, 17, 23] The double exists
Method 2: Using Set for O(1) Lookup
This optimized approach uses a set for constant-time lookups, making it more efficient ?
def check_double_exists_optimized(my_list):
seen = set()
for num in my_list:
if 2 * num in seen or num / 2 in seen:
return True
seen.add(num)
return False
my_list = [67, 34, 89, 67, 90, 17, 23]
print("The list is:")
print(my_list)
if check_double_exists_optimized(my_list):
print("The double exists")
else:
print("The double does not exist")
The list is: [67, 34, 89, 67, 90, 17, 23] The double exists
Method 3: Finding the Actual Pair
This approach returns the actual number and its double when found ?
def find_double_pair(my_list):
seen = set()
for num in my_list:
if 2 * num in seen:
return (num, 2 * num)
if num % 2 == 0 and num // 2 in seen:
return (num // 2, num)
seen.add(num)
return None
my_list = [67, 34, 89, 67, 90, 17, 23]
print("The list is:")
print(my_list)
pair = find_double_pair(my_list)
if pair:
print(f"Found pair: {pair[0]} and its double {pair[1]}")
else:
print("No double pair found")
The list is: [67, 34, 89, 67, 90, 17, 23] Found pair: 67 and its double 67
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Nested Loops | O(n²) | O(n) | Small arrays |
| Set Lookup | O(n) | O(n) | Large arrays |
| Find Pair | O(n) | O(n) | When you need the actual values |
Conclusion
Use the set-based approach for optimal performance with O(n) time complexity. The nested loop method works for small arrays, while the pair-finding method is useful when you need to identify the actual numbers involved.
