1. Brute Force — String Concatenation & BigInt Multiplication
Intuition
Traverse both lists and accumulate all digits into strings. Multiply the strings using BigInteger or BigInt and take modulo 109 + 7.
Algorithm
- Step 1: Traverse
list1and append digits to strings1. - Step 2: Traverse
list2and append digits to strings2. - Step 3: Multiply BigInts:
(BigInt(s1) * BigInt(s2)) % 1000000007n. - Step 4: Return result.
#include <iostream>#include <string> using namespace std; struct Node { int data; Node* next; Node(int x) : data(x), next(nullptr) {}}; class Solution {public: long long multiplyTwoLists(Node* first, Node* second) { long long MOD = 1000000007; string s1 = "", s2 = ""; for (Node* c = first; c; c = c->next) s1 += to_string(c->data); for (Node* c = second; c; c = c->next) s2 += to_string(c->data); long long n1 = 0, n2 = 0; for (char ch : s1) n1 = (n1 * 10 + (ch - '0')) % MOD; for (char ch : s2) n2 = (n2 * 10 + (ch - '0')) % MOD; return (n1 * n2) % MOD; }}; int main() { Node* l1 = new Node(3); l1->next = new Node(2); Node* l2 = new Node(2); Solution sol; cout << "Brute Force Multiply: " << sol.multiplyTwoLists(l1, l2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N + M)— Builds strings of length N and M, then performs BigInt multiplication and modulo. - Space complexity:
O(N + M)— Allocates memory for digit strings and BigInt representations.
Why Brute Force Doesn't Scale:
Grade-school multiplication takes O(N * M) time, which for N, M = 105 requires 1010 operations (>10 seconds).
For N = 100,000 and M = 100,000, Horner's rule completes in <0.8ms.