Runtime Error: reference binding to null pointer of type 'int' (stl_vector.h), product of array except self - c++11

While solving a Product of array except self on leetcode , I encountered an error:
runtime error: reference binding to null pointer of type 'int' (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:9
Here is my code to the problem:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int leftarr[nums.size()];
int rightarr[nums.size()];
int n = nums.size();
int prod=1;
for(int i=0;i<n;++i){
prod *= nums[i];
leftarr[i]= prod;
}
prod=1;
for(int j=n-1;j>=0;--j){
prod *= nums[j];
rightarr[j]= prod;
}
vector<int> output;
output[0]= rightarr[n-1];
output[n-1]= leftarr[n-2];
for(int i=1;i<n-1;++i){
output.push_back(leftarr[i-1]*rightarr[i+1]);
}
return output;
}
};
My approach to solve this problem:
Take two arrays, leftarr and rightarr and store the cumulative left and right multiplication at respective index, then take output vector and multiply left and right multiplication and get the output.
So, could any one of you pls tell me why this error occurs and what is wrong with my code?

Related

How Can I fix the following Error in leetcode?

For the question:
Given an array of integers nums, return the number of good pairs.
A pair (i, j) is called good if nums[i] == nums[j] and i < j.
I wrote the following code:
int numIdenticalPairs(vector<int>& nums) {
int count[102];
for (int num : nums) {
count[num]++;
}
int totalCount = 0;
// Calculate total number of pairs possible
for (int i : count) {
totalCount += ((i) * (i-1))/2;
}
return totalCount;
}
I am getting following error help me fix it:
Line 21: Char 26: runtime error: signed integer overflow: -1844207608 * -1844207609 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:30:26
For this type of question, you need to give the constraints as well. Still, I'm trying from my experience.
In C++, the array you declare in the function/method without malloc or new, goes to in stack and keeps garbage values if you don't put anything. So, you need to initialize it first. Do this:
memset(count, 0, sizeof(count));
As I am not seeing any constraints here, if values of count[] is even near 10^5, you will get integer overflow in multiplication of i x (i-1) as well. So try this:
for (int i : count) {
totalCount += ((i) * ((long long)(i-1)))/2;
}
Hope, these will solve the problem.
Edit: Now I use Java for problem-solving. So there might be some error in syntax.

Count of subsetsum problem, how to debug where the solution is not working?

So I'm trying to solve this problem :
Given an array arr[] of integers and an integer sum, the task is to
count all subsets of the given array with a sum equal to a given sum.
Note: Answer can be very large, so, output answer modulo 10^9+7
Now this is the solution I'm trying out here:
class Solution{
private:
vector<vector<int>> t;
public:
Solution() {
t.resize(1001, vector<int> (1001,-1));
}
int perfectSum(int arr[], int n, int sum)
{
long long int result = fmod(sumrecursive(arr, n, sum),(pow(10,9)+7));
return result;
}
long long int sumrecursive(int arr[], int n, int sum){
if(sum==0){
return 1;
}
if(n==0){
return 0;
}
if(t[n][sum] != -1){
return t[n][sum];
}
if(arr[n-1]>sum){
return t[n][sum] = sumrecursive(arr, n-1, sum);
} else {
return t[n][sum] = sumrecursive(arr,n-1, sum-arr[n-1]) + sumrecursive(arr, n-1, sum);
}
}
};
Now this code is not working after some certain input:
I don't know on how to proceed in solving this problem at this point. Ideally according to the code I have written the input is within the grasp of the code and output should've been correct but unfortunately it is not the case. I wanted to ask if someone could spot on where the problem might be in the code or guide me on how to debug where the problem is in the code.
You are probably encountering integer overflow along the way.
You are taking the mod only right before ending the function, but your cache is of type int, so when placing too big numbers - you are losing some data due to overflow.

How do i Pass a set<int> var to a function?

The function dfs() in this program operates upon the set A & array C. The program works fine when set A and int C[MAX] are declared global. But when i try to use this program t number of times, the set A and C are initialized with previous test cases's values, which gives wrong output. How can i make this program to accept new values in A & C for every next case. Note: This program is intended to find if the graph with n number of nodes and m number of edges is bipartite or not.
#include <bits/stdc++.h>
using namespace std;
const int MAX=1000000; // maximum number of vertices
int dfs(int x,const set<int>& A,int C[]){
for(int y:A[x]){
if(C[y]==C[x])return 0;// this means the graph is not bipartite
if(C[y]==0){
if(C[x]==1) C[y]=2;
else C[y]=1;
dfs(y,A,C);
return 1;
}
}
}
int main(){
int t;
scanf("%d",&t);
while(t--)
{
set<int> A[MAX];// Here, i declare set<int> A and Int C[MAX] in local scope
int C[MAX];
// Passing set<int> A and int C[] to dfs()..
int res = dfs(i,A,int C);
}
If i change my code to something like above. I get the following error.
prog.cpp: In function 'int dfs(int, const std::set<int>&, int*)':
prog.cpp:8:16: error: no match for 'operator[]' (operand types are 'const std::set<int>' and 'int')
for(int y:A[x]){
According to the c++ doc, set - C++ Reference there is not such operator[] in std::set<>so your for(int y:A[x]) is wrong. You cannot call A[x].
I'd recommend to use an vector or some other container meeting your requirement instead of a std::set

Why does the sort not work?

the error is:
/usr/include/c++/4.8/bits/stl_algo.h:2159:29: error: invalid conversion from 'int' to 'const char*' [-fpermissive]
if (__comp(*__i, *__first))
I am passing 2 strings X and Y. Now the sort should compare XY and YX and then return the X if XY>YX or return Y. X and Y will have values like - 33 or 9999.
string Solution::largestNumber(const vector<int> &A) {
int i,n;
vector<string> B;
string str;
for(i=0; i<A.size(); i++)
{
B[i]=to_string(A[i]);
}
sort(A.begin(), A.end(),[](const string lhs, const string rhs){
return rhs+lhs < lhs+rhs;
});
for(i=0; i<A.size(); i++)
{
str+= to_string(A[i]);
}
return str;}
You are calling std::sort on a range from A which is a std::vector<int>, so the compare function should compare int-s.
You could fill B initially with 0,1, .... A.size()-1 then, given two indexes i1 and i2 to compare, construct the strings and compare them.
the error is: /usr/include/c++/4.8/bits/stl_algo.h:2159:29: error: invalid conversion from 'int' to 'const char*' [-fpermissive] if (__comp(*__i, *__first))
sort(A.begin(), A.end(),[](const string lhs, const string rhs){...});
Your sort comparator is expecting to compare two std::strings. The element type of A is int. You created B to be a conversion of A's elements to B's element type of std::string. Use B.
Other notes:
string Solution::largestNumber(const vector<int> &A) {
int i,n; // n???
// vector<string> B; // B is empty. Calling B[i] will cause a
// segfault for attempting to access memory
// out of bounds.
vector<string> B(A.size()); // Fix: pass in the size. Now creates B
// with size elements that can be accessed.
string str;
// Consider using algorithms like std::transform
for(i=0; i<A.size(); i++)
{
B[i]=to_string(A[i]); // You won't segfault here now.
}
// Corrected your sort.
sort(B.begin(), B.end(),[](const string lhs, const string rhs){
return rhs+lhs < lhs+rhs;
});
// Appending should be done on the sorted string vector. Consider using
// a ranged-based for loop here.
for(i=0; i<B.size(); i++)
{
str+= B[i];
}
return str;
}

What would be the datastructure in following scenario? (Stack with maximum)

Please note that there is no limitation of memory.
I need to insert int from 1 to 1000.
I can do the each of the following operations in constant order of time:
push():adds to the top
pop():removes the top element
getMax(): returns the max element
Please suggest me appropriate datastructure.
Since there is no limitation of memory, I will use 2 vectors - one for the actual data on the stack, and the other to keep track of the max at every state of the stack.
For simplicity sake I'm assuming this stack holds only +ve ints.
I know this doesn't have any error checking. But I am just providing the data structure idea here, not the full-fledged solution.
class StackWithMax
{
public:
StackWithMax() : top(-1), currentMax(0) { }
void push(int x);
int pop();
int getMax() { return m[top]; }
private:
vector<int> v; // to store the actual elements
vector<int> m; // to store the max element at each state
int top;
int currentMax;
};
void StackWithMax::push(int x)
{
v[++top] = x;
m[top] = max(x, currentMax);
}
int StackWithMax::pop()
{
int x = v[top--];
currentMax = m[top];
return x;
}
Use normal stack structure and additional array for counters
int c[1..1000] and variable int maxVal=0.
In code add actions after stack operations:
On push(x) -> c[x]++ ; maxVal = max(x,maxVal)
On pop():x -> c[x]-- ; if (c[x] == 0) { j=x; while(c[--j] == 0); maxVal = j; }
maxVal should have always maximum value.
Maybe I am wrong, this should have amortized computational complexity O(1).
It has been a long time since I have been analysing algorithms.

Resources