Geeksforgeeks Key pair

http://practice.geeksforgeeks.org/problem-page.php?pid=552

my code is getting

Runtime Error: dumped core

what does this error means?why it is showing in?
my code :

#include<bits/stdc++.h>

using namespace std;

int main()
{

long long int a,b,c,d,e,f,g,h=1;

cin>>a;

for(b=0;b<a;b++)

{

cin>>c>>d;

long long int arr[c];

bool arr2[c];

for(e=0;e<c;e++)

{

    cin>>arr[e];

    arr2[e] = 0;

}

sort(arr,arr+c);

long long int x=0;g=0;

for(f=0;f<c;f++)

{

    g = d - arr[f];// 4 6

    if(g>=0 && arr2[g]==1)

    {

        x++;

    }else

    arr2[arr[f]]=1;

}


if(x==0)

    cout<<"No\n";

else

    cout<<"Yes\n";    }}

Core dump? I believe that somewhere you are going out of index. Have a look at your array.

Also, this problem, provided that you are already using nested loop, shouldn’t require such complicated approach.

Can you explain that what are you trying to do here?

I think this test case would help you debug-

Compilation Successful
Input (stdin)
1
2 3
1 5
Your Output
Yes
Expected Output
No

EDIT- Fixed the error

You were going out of bounds (meaning array index out of range)

In your program, change bool arr2[c]; to bool arr2[1001];

you are doing “arr2[arr[f]]=1;”, where arr[f] can be from 1 to 1000, its necessary to your arr2 has indexing from 0 to 1000 to handle to worst cases.

if(g>=0 && arr2[g]==1)

At this line , you are accessing array out of bounds i.e. , also negative indexes .

Since ,if d<(any given no. in array)
then, g = d - arr[f]; will be give negative g
and arr[g] will access memory with negative indexes , which is INVALID

Also, bool arr2[1001];

1 Like

Lol. XD Yup. Negative indexes are also coming in his array. BTW, hes lucky geek for geek compiler threw an error, hackerrank compilers etc. don’t throw error, but assign a garbage value in this case…and the coder just pulls his hair in frustration XD

Thanks it worked!!

It will not access negative value in array as first it checks whether g>=0 and if it is false then it exits without checking second condition so no arr[g] wont access memory with negative index

1 Like

I am glad it helped you dear :slight_smile:

Please comment your code so we can better understand what is your thought process, its easier to debug
Once you starting commenting, you can even question yourself whether its correct or incorrect

thanx for highlighting

please check this code

import java.io.*;
import java.util.Scanner;

class KP
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int p=0;p< t;p++)
{
int n=sc.nextInt();	int x=sc.nextInt();
int a[]=new int[n];

	for(int i=0;i< n;i++)
	a[i]=sc.nextInt();

boolean flag=false;

	for(int i=0;i< n;i++)
	{
		for(int j=0;j< n;j++)
		{
		if(i!=j&&a[i]+a[j]==x)
		{
		flag=true;
		break;
		}
		}
	}

if(flag==true)
System.out.println("Yes");
else
System.out.println("No");
}
}
}

Fixed formatting.

Is this giving you an error? Or you just wish to show it to us?