LeetCode #3756 — MEDIUM

Concatenate Non-Zero Digits and Multiply by Sum II

Move from brute-force thinking to an efficient approach using math strategy.

Solve on LeetCode
The Problem

Problem Statement

You are given a string s of length m consisting of digits. You are also given a 2D integer array queries, where queries[i] = [li, ri].

For each queries[i], extract the substring s[li..ri]. Then, perform the following:

  • Form a new integer x by concatenating all the non-zero digits from the substring in their original order. If there are no non-zero digits, x = 0.
  • Let sum be the sum of digits in x. The answer is x * sum.

Return an array of integers answer where answer[i] is the answer to the ith query.

Since the answers may be very large, return them modulo 109 + 7.

Example 1:

Input: s = "10203004", queries = [[0,7],[1,3],[4,6]]

Output: [12340, 4, 9]

Explanation:

  • s[0..7] = "10203004"
    • x = 1234
    • sum = 1 + 2 + 3 + 4 = 10
    • Therefore, answer is 1234 * 10 = 12340.
  • s[1..3] = "020"
    • x = 2
    • sum = 2
    • Therefore, the answer is 2 * 2 = 4.
  • s[4..6] = "300"
    • x = 3
    • sum = 3
    • Therefore, the answer is 3 * 3 = 9.

Example 2:

Input: s = "1000", queries = [[0,3],[1,1]]

Output: [1, 0]

Explanation:

  • s[0..3] = "1000"
    • x = 1
    • sum = 1
    • Therefore, the answer is 1 * 1 = 1.
  • s[1..1] = "0"
    • x = 0
    • sum = 0
    • Therefore, the answer is 0 * 0 = 0.

Example 3:

Input: s = "9876543210", queries = [[0,9]]

Output: [444444137]

Explanation:

  • s[0..9] = "9876543210"
    • x = 987654321
    • sum = 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 45
    • Therefore, the answer is 987654321 * 45 = 44444444445.
    • We return 44444444445 modulo (109 + 7) = 444444137.

Constraints:

  • 1 <= m == s.length <= 105
  • s consists of digits only.
  • 1 <= queries.length <= 105
  • queries[i] = [li, ri]
  • 0 <= li <= ri < m

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given a string s of length m consisting of digits. You are also given a 2D integer array queries, where queries[i] = [li, ri]. For each queries[i], extract the substring s[li..ri]. Then, perform the following: Form a new integer x by concatenating all the non-zero digits from the substring in their original order. If there are no non-zero digits, x = 0. Let sum be the sum of digits in x. The answer is x * sum. Return an array of integers answer where answer[i] is the answer to the ith query. Since the answers may be very large, return them modulo 109 + 7.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Math

Example 1

"10203004"
[[0,7],[1,3],[4,6]]

Example 2

"1000"
[[0,3],[1,1]]

Example 3

"9876543210"
[[0,9]]
Step 02

Core Insight

What unlocks the optimal approach

  • Track only nonzero digits: store their values and positions and keep a prefix sum for digit sums.
  • Also build prefix concatenation values <code>P</code>, <code>pow10</code>, and set <code>mod = 10<sup>9</sup>+7</code> so any compressed substring number is obtainable from prefixes.
  • Map each query <code>[l, r]</code> to the compressed list using precomputed mapping arrays (first nonzero at or after <code>i</code>
  • If the mapped range is empty return <code>0</code>; otherwise get <code>x</code> from <code>P</code>, get <code>sum</code> from the digit-prefix, and return <code>(x * sum) % mod</code>.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3756: Concatenate Non-Zero Digits and Multiply by Sum II
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3756: Concatenate Non-Zero Digits and Multiply by Sum II
// package main
// 
// // https://space.bilibili.com/206214
// const mod = 1_000_000_007
// const maxN = 100_001
// 
// var pow10 = [maxN]int{1}
// 
// func init() {
// 	// 预处理 10 的幂
// 	for i := 1; i < maxN; i++ {
// 		pow10[i] = pow10[i-1] * 10 % mod
// 	}
// }
// 
// func sumAndMultiply(s string, queries [][]int) []int {
// 	n := len(s)
// 	sumD := make([]int, n+1)       // s 的前缀和
// 	preNum := make([]int, n+1)     // s 的前缀对应的数字(模 mod)
// 	sumNonZero := make([]int, n+1) // s 的前缀中的非零数字个数
// 	for i, ch := range s {
// 		d := int(ch - '0')
// 		sumD[i+1] = sumD[i] + d
// 		preNum[i+1] = preNum[i]
// 		sumNonZero[i+1] = sumNonZero[i]
// 		if d > 0 {
// 			preNum[i+1] = (preNum[i]*10 + d) % mod
// 			sumNonZero[i+1]++
// 		}
// 	}
// 
// 	ans := make([]int, len(queries))
// 	for i, q := range queries {
// 		l, r := q[0], q[1]+1
// 		length := sumNonZero[r] - sumNonZero[l]
// 		x := preNum[r] - preNum[l]*pow10[length]%mod + mod // +mod 保证结果非负
// 		ans[i] = x * (sumD[r] - sumD[l]) % mod
// 	}
// 	return ans
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(log n)
Space
O(1)

Approach Breakdown

ITERATIVE
O(n) time
O(1) space

Simulate the process step by step — multiply n times, check each number up to n, or iterate through all possibilities. Each step is O(1), but doing it n times gives O(n). No extra space needed since we just track running state.

MATH INSIGHT
O(log n) time
O(1) space

Math problems often have a closed-form or O(log n) solution hidden behind an O(n) simulation. Modular arithmetic, fast exponentiation (repeated squaring), GCD (Euclidean algorithm), and number theory properties can dramatically reduce complexity.

Shortcut: Look for mathematical properties that eliminate iteration. Repeated squaring → O(log n). Modular arithmetic avoids overflow.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.