Largest product of contiguous digits in Python

Finding the largest product of contiguous digits is a common programming problem. Given a number and k, we need to find k consecutive digits that produce the maximum product.

Problem Statement

Given two numbers num and k, find the largest product of k contiguous digits in num. The number is guaranteed to have at least k digits.

For example, if num = 52689762 and k = 4, the output should be 3024 because the largest product of 4 consecutive digits is 8×9×7×6 = 3024.

Algorithm Steps

To solve this problem, we follow these steps:

  • Initialize largest to 0 to track the maximum product
  • While there are at least k digits remaining in the number:
    • Extract the last k digits
    • Calculate their product
    • Update the maximum product if current product is larger
    • Remove the last digit and continue
  • Return the largest product found

Implementation

class Solution:
    def solve(self, num, k):
        largest = 0
        
        # Continue while we have at least k digits
        while num // 10 ** (k - 1) > 0:
            # Get last k digits
            digits = num % 10 ** k
            product = 1
            
            # Calculate product of these k digits
            temp_digits = digits
            while temp_digits > 0:
                product *= temp_digits % 10
                if product == 0:
                    break
                temp_digits //= 10
            
            # Update maximum product
            largest = max(largest, product)
            
            # Remove last digit and continue
            num //= 10
        
        return largest

# Test the solution
solution = Solution()
num = 52689762
k = 4
result = solution.solve(num, k)
print(f"Largest product of {k} contiguous digits in {num}: {result}")
Largest product of 4 contiguous digits in 52689762: 3024

How It Works

Let's trace through the example with num = 52689762 and k = 4:

# Breaking down the number into 4-digit segments:
segments = [
    "9762",  # 9 × 7 × 6 × 2 = 756
    "8976",  # 8 × 9 × 7 × 6 = 3024 (maximum)
    "6897",  # 6 × 8 × 9 × 7 = 3024 (also maximum)
    "2689",  # 2 × 6 × 8 × 9 = 864
    "5268"   # 5 × 2 × 6 × 8 = 480
]

print("Checking each 4-digit segment:")
for i, segment in enumerate(segments):
    digits = [int(d) for d in segment]
    product = 1
    for d in digits:
        product *= d
    print(f"{segment}: {' × '.join(map(str, digits))} = {product}")
Checking each 4-digit segment:
9762: 9 × 7 × 6 × 2 = 756
8976: 8 × 9 × 7 × 6 = 3024
6897: 6 × 8 × 9 × 7 = 3024
2689: 2 × 6 × 8 × 9 = 864
5268: 5 × 2 × 6 × 8 = 480

Alternative String-Based Approach

Here's a simpler approach using string manipulation:

def largest_product_simple(num, k):
    num_str = str(num)
    max_product = 0
    
    # Check each possible k-digit substring
    for i in range(len(num_str) - k + 1):
        substring = num_str[i:i+k]
        product = 1
        
        for digit_char in substring:
            product *= int(digit_char)
        
        max_product = max(max_product, product)
    
    return max_product

# Test the alternative approach
num = 52689762
k = 4
result = largest_product_simple(num, k)
print(f"Result using string approach: {result}")
Result using string approach: 3024

Time Complexity

Both approaches have a time complexity of O(n×k), where n is the number of digits in the input number. The string-based approach is more intuitive and easier to understand.

Conclusion

The largest product of contiguous digits problem can be solved by examining all possible k-digit segments and tracking the maximum product. The string-based approach offers cleaner code, while the mathematical approach demonstrates advanced number manipulation techniques.

---
Updated on: 2026-03-25T10:27:59+05:30

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements