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
A number and its triple in Python
When working with lists of numbers, you might need to check if any number in the list is exactly triple another number. This problem can be solved efficiently using a two-pointer approach after sorting the list.
For example, if we have nums = [2, 3, 10, 7, 9], the output should be True because 9 is the triple of 3.
Algorithm Steps
To solve this problem, we follow these steps ?
Sort the list to enable two-pointer technique
Initialize two pointers:
i = 0andj = 1-
While
j < len(nums):If
3 * nums[i] == nums[j], returnTrueIf
3 * nums[i] > nums[j], incrementjOtherwise, increment
i
Return
Falseif no triple pair is found
Implementation
def check_triple_exists(nums):
"""Check if there exists a number and its triple in the list."""
if len(nums) < 2:
return False
nums.sort()
i = 0
j = 1
while j < len(nums):
if 3 * nums[i] == nums[j]:
return True
elif 3 * nums[i] > nums[j]:
j += 1
else:
i += 1
return False
# Test with example
nums = [2, 3, 10, 7, 9]
result = check_triple_exists(nums)
print(f"Input: {nums}")
print(f"Output: {result}")
Input: [2, 3, 10, 7, 9] Output: True
How It Works
After sorting [2, 3, 10, 7, 9] becomes [2, 3, 7, 9, 10]. The algorithm compares:
3 * 2 = 6vs3? Move j forward3 * 2 = 6vs7? Move i forward3 * 3 = 9vs7? Move j forward3 * 3 = 9vs9? Found match! ReturnTrue
Alternative Approaches
Using Set for O(n) Solution
def check_triple_with_set(nums):
"""Check using set for faster lookup."""
num_set = set(nums)
for num in nums:
if num * 3 in num_set:
return True
return False
# Test with example
nums = [2, 3, 10, 7, 9]
result = check_triple_with_set(nums)
print(f"Set approach result: {result}")
Set approach result: True
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Two Pointers | O(n log n) | O(1) | Memory-constrained scenarios |
| Set Lookup | O(n) | O(n) | Fast execution with extra memory |
Conclusion
Use the set approach for faster O(n) time complexity, or the two-pointer method for O(1) space complexity. Both effectively solve the triple number detection problem.
