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 = 0 and j = 1

  • While j < len(nums):

    • If 3 * nums[i] == nums[j], return True

    • If 3 * nums[i] > nums[j], increment j

    • Otherwise, increment i

  • Return False if 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 = 6 vs 3 ? Move j forward

  • 3 * 2 = 6 vs 7 ? Move i forward

  • 3 * 3 = 9 vs 7 ? Move j forward

  • 3 * 3 = 9 vs 9 ? Found match! Return True

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.

Updated on: 2026-03-25T10:12:22+05:30

777 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements