Skip to content

1416. Restore The Array 👍

Approach 1: Top-down

  • Time: $O(n\log k)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
 public:
  int numberOfArrays(string s, int k) {
    vector<int> mem(s.length(), -1);
    return numberOfArrays(s, 0, k, mem);
  }

 private:
  static constexpr int kMod = 1'000'000'007;

  // Returns the number of arrays to restore s[i..n) with k.
  int numberOfArrays(const string& s, int i, int k, vector<int>& mem) {
    if (i == s.length())
      return 1;  // an empty string ""
    if (s[i] == '0')
      return 0;  // a leading zero
    if (mem[i] != -1)
      return mem[i];

    int res = 0;
    long num = 0;

    for (int j = i; j < s.length(); ++j) {
      num = num * 10 + (s[j] - '0');
      if (num > k)
        break;
      res = (res + numberOfArrays(s, j + 1, k, mem)) % kMod;
    }

    return mem[i] = res;
  }
};

Approach 2: Bottom-up

  • Time: $O(n\log k)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int numberOfArrays(string s, int k) {
    constexpr int kMod = 1'000'000'007;
    const int n = s.length();
    // dp[i] := the number of arrays to restore s[i..n) with k
    vector<int> dp(n + 1);
    dp.back() = 1;  // an empty string ""

    for (int i = n - 1; i >= 0; --i) {
      if (s[i] == '0')
        continue;  // a leading zero
      long num = 0;
      for (int j = i; j < n; ++j) {
        num = num * 10 + (s[j] - '0');
        if (num > k)
          break;
        dp[i] = (dp[i] + dp[j + 1]) % kMod;
      }
    }

    return dp[0];
  }
};