I'm getting error while running this on leetcode - runtime-error

Question:
Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Code:
class Solution {
public int[] runningSum(int[] nums) {
int[] ans = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
ans[i] = nums[i] + nums[i+1];
}
return ans;
}
}
error:
java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at line 6, Solution.runningSum
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main

Related

Setting Base Cases for Recursive Function

class Solution {
//given a location on the matrix, this function recursively find the deepest possible depth, which is the length of a side of a found square
private int isSquare(int row_index, int col_index, int depth, char[][] matrix) {
int last_row = row_index + depth;
int last_col = col_index + depth;
if (row_index >= matrix.length || col_index >= matrix[0].length) {
return 0;
}
if (last_row >= matrix.length || last_col >= matrix[0].length) {
return 0;
}
for (int i = col_index; i < last_col; i++) {
if (matrix[row_index][i] != '1') {
return 0;
}
}
for (int i = row_index; i < last_row; i++ ) {
if (matrix[i][col_index] != '1') {
return 0;
}
}
return Math.max(depth, isSquare(row_index, col_index, depth + 1, matrix));
}
public int maximalSquare(char[][] matrix) {
int max = 0;
for (int row = 0; row < matrix.length; row ++) {
for (int col = 0; col <matrix[0].length; col ++) {
int curr_depth = isSquare(row, col, 1, matrix);
if (curr_depth > max) {
max = curr_depth;
}
}
};
return max * max;
}
}
Hi, I was working on LeetCode 221, and it seems like that my solution is not passing test cases with output 1, where the biggest square on the given matrix is just 1 x 1. To me it looks like those depth 1 cases are not passing the two for loops in function isSquare, which is supposed to catch 0s in the square.
I tried LC debugging tool but it did not help much, and my base cases seem fine to me. Please let me know what is going on here. For the problem, https://leetcode.com/problems/maximal-square/
One of the depth 1 test cases that I am failing is below.
Input:
[["0","1"],["1","0"]]
Output:
0
Expected:
1

What is causing the buffer overrun error in below code

Unable to figure out what is causing the buffer overflow in below code. I reckon it has to do with the vector but I am guarding against out of bounds access. Is there anything else that could be causing the overflow?
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum = 0;
bool canPartition = true;
vector<vector<int>> dp(nums.size(), vector<int>(sum / 2 + 1, -1));
sum = accumulate(nums.begin(),nums.end(),0);
if (sum % 2 != 0)
{
canPartition = false;
}
if (true == canPartition)
{
canPartition = canPartitionRecursive(nums, 0, sum/2, dp);
}
return canPartition;
}
bool canPartitionRecursive(vector<int>& nums, int index, int sum,
vector<vector<int>>& dp)
{
if (sum == 0)
{
return true;
}
if (index >= nums.size() || sum < 0)
{
return false;
}
if (dp[index][sum] != -1)
{
if (true == canPartitionRecursive(nums, index+1, sum - nums[index],dp))
{
dp[index][sum] = 1;
return true;
}
dp[index][sum] = canPartitionRecursive(nums, index + 1, sum, dp);
}
return dp[index][sum] = 1? true:false;
}
};
This looks like a transpositional error (all subvector will have size 1):
int sum = 0;
vector<vector<int>> dp(nums.size(), vector<int>(sum / 2 + 1, -1));
sum = accumulate(nums.begin(),nums.end(),0);
Perhaps calculation of sum should be moved before dp initialization?

Longest Increasing Subsequence Recursive version

Traditional Longest Increasing Subsequence problem.
This is recursion version ( not DP version )
I realized that version1 code had a bug, so I changed it to version2.
I don't clearly understand why version2 works and version1 has a bug for input A0
Please see version 1 and version2 below:
static int lis1(int[] v) {
int maxLen = 1;
for(int i = 1; i < v.length; i++) {
List<Integer> w = new ArrayList<Integer>();
for( int j = 0; j < i; j++) {
if( v[j] < v[i] ) {
w.add(v[j]);
}
}
// it used to be the following one line which has bug for input A0
//cand = lis1(l2a(w)) + 1; // version1
// so I changed it to the following, but can't clearly understand why it works.
// without this part, it has but for input A0
int cand = 1; // version2
if(v[i-1] < v[i])
cand = lis1(l2a(w)) + 1;
else
cand = lis1(l2a(w));
maxLen = Math.max(maxLen, cand);
}
return maxLen;
}
public static void main(String[] args) {
int[] A0 = {3, 2, 5, 6}; // for this input version1 had a bug which printed out 4 ( instead of 3 )
int[] A1 = {1, 2, 3, 3, 2, 4, 6, 7}; // 6
int[] A2 = { 10, 22, 9, 33, 21, 50, 41, 60, 80 }; // 6
int[] A3 = { 5, 0, 4, 2, 3, 7, 1 }; // 4
int[] A4 = { 2, 7, 3, 4, 9, 8, 12 }; // 5
int[] A5 = {3, 4, 2, 5 }; // 3
Actually... neither of your version works. Try putting A0={3,2,7,6}, your v2 returns 2, obviously wrong.
As for v1, for v={3,2} the answer should be 1, right? Let's see what your code does. When index i=1, your w after inner for loop equals {}. Then you made a recursive call to w={}, which should've returned 0, but it returns 1. Why, because of your maxlen variable, which is wrongly initialized with 1. This error propagates to entire {3,2,5,6} and gives wrong answer.
v2 accidentally solves this problem because your if condition then fails (3<2), and it returns the previously returned 1.
Just delete entire version 2, correct maxlen initialization. And start outer loop for(int i = 1; i < v.length; i++) with i=0, else you will get 0 for single-element array.
static int lis1(int[] v) {
int maxLen = 0;
for(int i = 0; i < v.length; i++) {
List<Integer> w = new ArrayList<Integer>();
for( int j = 0; j < i; j++) {
if( v[j] < v[i] ) {
w.add(v[j]);
}
}
cand = lis1(l2a(w)) + 1; // version1
maxLen = Math.max(maxLen, cand);
}
return maxLen;
}

When using scanf/cin, program works fine in debug mode but gives runtime error

I'm trying to take to the following input:
1
4
47 2 4 43577
The part of my code that deals with this is:
for (scanf("%d", &t); t --; )
{
int count = 0;
scanf("%d",&n);
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
str = to_string(x);
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
However, with this I get a runtime error, which shows an access violation in the file free.c.
But, when I try to debug it, it runs well in the debug mode and gives the correct answer.
Also, when I output the variable x right after I input it, the program works well in runtime as well. This is shown in the following code, which runs fine in runtime as well:
for (scanf("%d", &t); t --; )
{
int count = 0;
scanf("%d",&n);
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
cout<<"A"<<i<<" is "<<x<<'\n';
str = to_string(x);
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
Any idea why this may be happening?
Some of the stackoverflow users are saying that the code runs fine. I'm using VS 2012. Can this be something that is compiler specific?
The complete code:
#include<iostream>
#include<conio.h>
#include<string>
#include<math.h>
using namespace std;
int get_count(string s, char x)
{
int count = 0;
int l = s.length();
for(int i = 0; i < l;i++)
{
if (s[i] == x)
count++;
}
return count;
}
void main()
{
int * f4 = new int;
int * f7 = new int;
string * back = new string;
int n = 0;
int t = 0;
string str;
for (scanf("%d", &t); t --; )
{
int count = 0;
scanf("%d",&n);
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
str = to_string(x);
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
for(int i = 0;i < n;i++)
{
for(int j = i; j < n;j++)
{
int c4 = 0;
int c7 = 0;
for(int k = i; k <= j;k++)
{
c4 += f4[k];
c7 += f7[k];
}
double value = pow((double)c4,(double)c7);
if(value <= (double)(j - i + 1)&&(c4!=2)&&(c7!=2))
{
count++;
//cout<<"yes"<<'\t';
}
}
}
cout<<"Ans: "<<count<<'\n';
}
//getch();
}
There are no other variable assignments apart from those in this code.
The exact error that I get with runtime is:
Unhandled exception at 0x7794E3BE (ntdll.dll) in Practice1.exe: 0xC0000005: Access violation reading location 0x38389246.
You did not include the "get_count" function. I think it has something to do with that function. I rewrote that function to return some number and I don't get that error. Try to assert that you are not attempting to use a null pointer in that function.
Works fine on my machine:
Here's what I changed
for (int i = 0, x; i < n; ++ i)
{
scanf("%d",&x);
stringstream ss;
ss << x;
str = ss.str();
f4[i] = get_count(str,'4');
f7[i] = get_count(str,'7');
}
Output:
1
4
47 2 4 43577
Ans: 5

Converting a decimal to a mixed-radix (base) number

How do you convert a decimal number to mixed radix notation?
I guess that given an input of an array of each of the bases, and the decimal number, it should output an array of the values of each column.
Pseudocode:
bases = [24, 60, 60]
input = 86462 #One day, 1 minute, 2 seconds
output = []
for base in reverse(bases)
output.prepend(input mod base)
input = input div base #div is integer division (round down)
Number -> set:
factors = [52,7,24,60,60,1000]
value = 662321
for i in n-1..0
res[i] = value mod factors[i]
value = value div factors[i]
And the reverse:
If you have the number like 32(52), 5(7), 7(24), 45(60), 15(60), 500(1000) and you want this converted to decimal:
Take number n, multiply it with the factor of n-1, continue for n-1..n=0
values = [32,5,7,45,15,500]
factors = [52,7,24,60,60,1000]
res = 0;
for i in 0..n-1
res = res * factors[i] + values[i]
And you have the number.
In Java you could do
public static int[] Number2MixedRadix(int[] base, int number) throws Exception {
//NB if the max number you want # a position is say 3 then the base# tha position
//in your base array should be 4 not 3
int[] RadixFigures = new int[base.length];
int[] PositionPowers = new int[base.length];
PositionPowers[base.length-1] = 1;
for (int k = base.length-2,pow = 1; k >-1; k--){
pow*=base[k+1];
PositionPowers[k]=pow;
}for (int k = 0; k<base.length; k++){
RadixFigures[k]=number/PositionPowers[k];
if(RadixFigures[k]>base[k])throw new Exception("RadixFigure#["+k+"] => ("+RadixFigures[k]+") is > base#["+k+"] => ("+base[k]+") | ( number is Illegal )");
number=number%PositionPowers[k];
}return RadixFigures;
}
Example
//e.g. mixed-radix base for 1day
int[] base = new int[]{1, 24, 60, 60};//max-day,max-hours,max-minutes,max-seconds
int[] MixedRadix = Number2MixedRadix(base, 19263);//19263 seconds
//this would give [0,5,21,3] => as per 0days 5hrs 21mins 3secs
Reversal
public static int MixedRadix2Number(int[] RadixFigures,int[] base) throws Exception {
if(RadixFigures.length!=base.length)throw new Exception("RadixFigures.length must be = base.length");
int number=0;
int[] PositionPowers = new int[base.length];
PositionPowers[base.length-1] = 1;
for (int k = base.length-2,pow = 1; k >-1; k--){
pow*=base[k+1];
PositionPowers[k]=pow;
}for (int k = 0; k<base.length; k++){
number+=(RadixFigures[k]*PositionPowers[k]);
if(RadixFigures[k]>base[k])throw new Exception("RadixFigure#["+k+"] => ("+RadixFigures[k]+") is > base#["+k+"] => ("+base[k]+") | ( number is Illegal )");
}return number;
}
I came up with a slightly different, and probably not as good method as the other ones here, but I thought I'd share anyway:
var theNumber = 313732097;
// ms s m h d
var bases = [1000, 60, 60, 24, 365];
var placeValues = []; // initialise an array
var currPlaceValue = 1;
for (var i = 0, l = bases.length; i < l; ++i) {
placeValues.push(currPlaceValue);
currPlaceValue *= bases[i];
}
console.log(placeValues);
// this isn't relevant for this specific problem, but might
// be useful in related problems.
var maxNumber = currPlaceValue - 1;
var output = new Array(placeValues.length);
for (var v = placeValues.length - 1; v >= 0; --v) {
output[v] = Math.floor(theNumber / placeValues[v]);
theNumber %= placeValues[v];
}
console.log(output);
// [97, 52, 8, 15, 3] --> 3 days, 15 hours, 8 minutes, 52 seconds, 97 milliseconds
I tried a few of the examples before and found an edge case they didn't cover, if you max out your scale you need to prepend the result from the last step
def intToMix(number,radix=[10]):
mixNum=[]
radix.reverse()
for i in range(0,len(radix)):
mixNum.append(number%radix[i])
number//=radix[i]
mixNum.append(number)
mixNum.reverse()
radix.reverse()
return mixNum
num=60*60*24*7
radix=[7,24,60,60]
tmp1=intToMix(num,radix)

Resources