Back to challenges
Medium 0 solved 0% acceptance

Largest Adjacent-Digit Product

Take every contiguous window of span digits and multiply its digits.

What you'll learn

  • Examine every window of a fixed size
  • Multiply digits inside a window
  • Track the best product

Problem

Take every contiguous window of span digits and multiply its digits. Return the largest product. Leading zeros are ordinary digits; a window containing zero has product zero. Do not reorder or skip digits.

Implement largest_adjacent_digit_product(digits, span).

Input

digits: The digit sequence, including any leading zeros.

span: The exact number of adjacent digits in a window.

Output

Return the greatest product over all windows of this width.

Constraints

1 ≤ digit-string length ≤ 100,000. Characters are 0…9. 1 ≤ span ≤ min(18, length). All products fit signed 64-bit.

Examples

Example 1
Input:
span = 2
digits = "23405"

Expected output:
expected = 12
Input:
long long span = 2;
std::string digits = "23405";

Expected output:
long long expected = 12;
Input:
long span = 2;
string digits = "23405";

Expected output:
long expected = 12;

Explanation

The windows 23, 34, 40, and 05 have products 6, 12, 0, and 0. The largest is 12.

Example 2
Input:
span = 3
digits = "102"

Expected output:
expected = 0
Input:
long long span = 3;
std::string digits = "102";

Expected output:
long long expected = 0;
Input:
long span = 3;
string digits = "102";

Expected output:
long expected = 0;

Explanation

There is only one width-three window. It contains zero, so 1 × 0 × 2 = 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

A zero inside a window forces that product to zero, so only contiguous nonzero stretches can contribute to the maximum.

Hint 2

Use a sliding window or track products across runs of digits to avoid recomputing every span from scratch.

Hint 3

Watch the exact span requirement: leading zeros count as digits, and if span exceeds a nonzero block, the product is zero.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.