-1

Here is my code, I wrote it on leetcode platform

const int N1 = 100+1;
const int N2 = 10e4+1;
class Solution {
public:
    bool cache[N1][N2];
    bool isSubsequence(string s, string t) {
        int n1 = s.size();
        int n2 = t.size();
        for(int i=0; i<=n1; i++) {
            for(int j=0; j<=n2; j++) {
                if(i == 0)
                    cache[i][j] = true;
                if(j == 0)
                    cache[i][j] = false;
                if(s[i-1] == t[j-1])
                    cache[i][j] = cache[i-1][j-1];
                else
                    cache[i][j] = cache[i][j-1];
            }
        }
        return cache[n1][n2];
    }
};

It gives following error, I don't know why. Please help. error image

Shubham Singh
  • 90
  • 1
  • 8
  • 5
    Check the accesses to "cache": you are probably exceeding the array bounds. Use nested vectors or write something custom to check the bounds. – Benedetto Aug 31 '20 at 08:02
  • 4
    `i` and `j` starts from 0 but you have `s[i-1]`. `cache` has the same issue. – Louis Go Aug 31 '20 at 08:02
  • 1
    Ok, thanks, I understood the mistake, I forgot to put else before if, otherwise it will go to index out of bounds. – Shubham Singh Aug 31 '20 at 08:14

2 Answers2

0

We don't have to cache anything for solving this problem, we can totally do that in constant memory.

This'd pass by looping through t with just one if statement:

// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);
    return 0;
}();

// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>

using ValueType = std::uint_fast16_t;

static const struct Solution {
    static const bool isSubsequence(
        const std::string source,
        const std::string target
    ) {
        const ValueType s_len = std::size(source);
        const ValueType t_len = std::size(target);
        ValueType s_index = 0;

        for (ValueType t_index = 0; t_index < t_len && s_index < s_len; ++t_index) {
            if (target[t_index] == source[s_index]) {
                ++s_index;
            }
        }

        return s_index == s_len;
    }
};
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    Yes i solved this way only. But storing cache was my first approach, after sometime I came to a solution similar to yours. – Shubham Singh Aug 31 '20 at 14:23
0

I solved this issue. Error was because of array index out of bounds. Here is the edit part:

if(i == 0)
   cache[i][j] = true;
else if(j == 0)
   cache[i][j] = false;
else if(s[i-1] == t[j-1])
   cache[i][j] = cache[i-1][j-1];
else
   cache[i][j] = cache[i][j-1];
};
Shubham Singh
  • 90
  • 1
  • 8