Click here to Skip to main content
15,880,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
public class TimeAndSpaceComplexity_DuplicateInArray {
	public static int findDuplicate(int[] arr) {

        
        int n = arr.length-2;
        int sum = 0;
        for(int i : arr){
            sum+=i;
        }
        
        return (sum - ((n*(n+1))/2));
	}

}


This code however runs fine but i don't understand how

What I have tried:

I tried to find the duplicate other way but it shows TLE error
Posted
Updated 28-Jul-22 11:14am
v3
Comments
0x01AA 28-Jul-22 16:10pm    
And I don't get what your code has to do with finding repeated elements in an array ?
Zeeshan Ahmad Jul2022 28-Jul-22 16:41pm    
It's supposed to give me the repeated element in a array list and my teacher did it this way. I could not understand how
0x01AA 28-Jul-22 16:50pm    
Thank you. Therefor, most probably a lack of my knowledge. Sorry.
Zeeshan Ahmad Jul2022 28-Jul-22 16:57pm    
That's fine

1 solution

Quote:
I tried to find the duplicate other way

Your code is not related to the question, we can't guess where is your problem.
Quote:
it shows TLE error

TLE is 'Time Limit Exceeded', it is a message from challenges site, it says that your code takes too long to solve the problem, your algorithm is not enough efficient.

Show real code to get help fixing it.

[Update]
find duplicates in array and find complexity of the task are not the same thing.
This code can be simplified
Java
public class TimeAndSpaceComplexity_DuplicateInArray {
	public static int findDuplicate(int[] arr) {

        
        int n = arr.length-2;
        int sum = 0;
        for(int i : arr){
            sum+=i;
        }
        
        return (sum - ((n*(n+1))/2));
	}

}

The complexity is how many comparisons are done depending on array size.
 
Share this answer
 
v2
Comments
Zeeshan Ahmad Jul2022 28-Jul-22 16:57pm    
public class TimeAndSpaceComplexity_DuplicateInArray {
public static int findDuplicate(int[] arr) {


int n = arr.length-2;
int sum = 0;
for(int i : arr){
sum+=i;
}

return (sum - ((n*(n+1))/2));
}

}
This one works fine but I don't understand how
Patrice T 28-Jul-22 17:06pm    
Use Improve question to update your question.
So that everyone can pay attention to this information.
Zeeshan Ahmad Jul2022 28-Jul-22 17:18pm    
Done

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900