#Java Code optimization- running out of time
1 messages Ā· Page 1 of 1 (latest)
Here is an AI assisted attempt to answer your question š¤. Maybe it helps! In any case, a human is on the way š. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
In order to optimize the code and improve its performance, you can consider the following suggestions:
-
Use more efficient data structures: Instead of using ArrayLists, consider using more efficient data structures such as LinkedList or HashSet, depending on your specific requirements. These data structures can provide faster insertion and retrieval times.
-
Preallocate ArrayList capacity: If you know the expected size of your ArrayLists in advance, use the
ArrayList(int initialCapacity)constructor to preallocate memory for the lists. This can help avoid unnecessary resizing operations during insertion. -
Use enhanced for loop: Instead of using traditional for loops with index variables, use enhanced for loops (also known as "for-each" loops) when iterating over collections. This can provide better performance and cleaner code.
-
Avoid unnecessary object creation: Be mindful of creating unnecessary objects within loops or methods that are called frequently. For example, if you don't need to modify the elements in your ArrayLists, consider using an immutable collection like Collections.unmodifiableList() instead.
-
Consider parallel processing: If your code allows it, consider using parallel processing techniques such as Java 8's parallel streams or multi-threading to process the ArrayLists concurrently. This can help leverage multiple CPU cores and improve overall performance.
-
Profile your code: Use a profiler tool to identify any bottlenecks or areas of improvement in your code. Profiling will help you pinpoint specific methods or operations that are consuming excessive time or resources.
Remember that optimization is a trade-off between speed and readability/maintainability of the code. Make sure to measure and test the performance improvements after implementing these suggestions to ensure they have a positive impact on your specific use case.
I need help to optimise the code as this code is not passing the test cases, it is taking too long with larger data set.
Especially, I have 2 ArrayLists area and price which needs to be sent to a method (called isOutlier). However, before sending both the lists, I want to remove its first element and then send. In the second iteration, I want the first elements back in both the lists and this time I want to remove the second elements from both and then send. In the third iteration, I want the first two elements intact and I want to remove the third element and so on. That is why I have made a copy of the lists. But I think, making a copy in every iteration is using too much time.
Please please help me in optimising this code, the timer is running.
I have to submit this code
When
within 1 hour
Is this an interview screening?
Or a school assignment
Also I'm maybe 15 minutes from my laptop
there are 3 test hidden cases remaining which are not passing
school assignmnet
because of the optimisation, the compiler is stopping the code and I cant even see if the output is correct or not
rest 5 test cases have passed, so maybe if it is optimised
please help
So, u need what to be specific?
and try to code clean 
so given a list of 10 elements, the first loop you want elements 2-10, 2nd time 1, 3-10, 3th time 1,2,4-10, ... ?
yes exactly
I need to use some kind of efficient data structure for it
Sorry
Also, in general,(not only that removing number problem) the code needs to perform faster
just pass the index into the func and skip it
can u share me full code and ur input, so i can debug it out?
and see where it taking much time
that is the full code
there is no main func?
I dont have to edit the main part of the code, I can only edit the method
wait I'll share the question
A real estate agent is advising a seller on the price to ask for a home. To do this, the agent will look at homes that have sold in the area and base the valuation on this data. The only factors that will be considered are square footage and sale price.
The agent starts by removing any outliers from the list of comparable homes. To determine the outliers:
⢠Select the home to test.
⢠Create a list of prices of other homes of the same size. It will be called compList in the examples.
⢠If there are no other homes of the same size, the house being tested is not an butlier.
⢠Otherwise:
⢠Calculate the mean price, P[m], and the standard deviation, o, for the homes compList.
° If | price[i] - P[m ]/ > 3 * o, the house is an outlier.
so, when I select a home to test for outlier, I dont have to consider that home, that is why I need to remove it from the list
is there any link to check this problem online?
yes, input I'll give
yes
1 minute
this is the example
the logic of the code is correct, but all the copying and removing is making it slow
got it now
please help me optimise it then
give me some mins, lemme see if i can see anything
sure
you could use a stream, and filter it based on the index
let say, we got the outliers, then?
nvm, i will just optimize this part of urs
Based on the question it also sounds like you don't need to remove a single element, but rather fetch houses of the same size?
yes
that is what I'm doing in the isOuliers method
if there are 3 houses of 1200 area, of prices 15k, 16k and 17k respectively. When considering the first house, I need the 16k and 17k house. When considering the second house, i need the 15k and 17k house. but the problem is that prices are in different arraylist
I don't know but ur code is giving different output for same thing 
no, no it is working as intended
in the outliers method, it is only adding those houses as need, according to the example
need to find a better way of doing it
sorry for being nagging but please please hurry
you should use area.get(i).equals(currentArea) by the way. You're using Long and not long.
just optimizied a little, not much
I uploaded your attachments as Gist.
corrected
done the correction, but the code is still not passing the test case
š
I uploaded your attachments as Gist.
still exceeding the timeš
wow then, what u did after storing outliers?
should I send the second half of the question?

yup and how much time remains?
u used many streams to calc something, which can be done inside any prev loops
After removing outliers, The valuation is then calculated against the resulting list using the following:
If there are no houses in the list, use 1000 per square foot as the price.
⢠If there is only 1 house in the list, its square foot price is used.
⢠If there are 1 or more houses in the list with the exact square footage of the house to price, use the mean of those prices.
⢠If the required square footage is between the square footage of two houses in the list, interpolate the square foot price using the means of the closest higher, and
the required square footage is outside of the range of houses listed, extrapolate the price based on the means of the two square footage values that are closest to the home to value.In all cases, if the final price is less than 1000 or greater than 10^6, the price will be 103 and 106 , respectively. For any square footage, the square foot price is the mean of the prices at that square footage. Return an integer that represents the valuation of the seller's house.
For example, there are n = 6 houses with area = [1200, 1300, 1250, 1300, 1200,
2000], price = [12000, 24000, 14000, 22000, 13000, 30000] and the house to value has reqArea = 1500 square feet. The following table showsĀ theĀ testĀ for.The 1300 square foot houses are both outliers, so they are discarded. The new
arrays are area' = [1200, 1200, 1200, 2000] and price' = [12000, 14000, 13000,
30000]. Interpolate the price between the two house sizes remaining. The interpolated price is 13000 + (30000 - 13000)/(2000-1200) * (1500-1200)Ā =
19375.
newArea.contains(reqArea)
You used this which is itself O(N)
u could have used set to do it in O(1)
there can be many optimizations possible
Now, if i change it to a hashset, i need to change it everywhere 
this is the entire question
how O(1)?
for(long val: newArea) if((secondMax<val) && (val<max)) secondMax=val;
Same here, u are looping around for calc secondMax, which could be calc in O(1) above
please do itš
set finds element in O(1)
u used list, which takes O(N) to find an element
please do in setsš
the main area and price will remain in Arraylist
please optimise it as much as possible, the last three test cases are not passingš
do u have input of those cases?
I am trying, there is so much to do 
long closestMax=newArea.stream().filter(val->val>reqArea).min(Comparator.comparingLong(val->Math.abs(reqArea-val))).orElseThrow(NoSuchElementException::new);```
What is these two lines doing? can u explain it
ohh nearest ones
for interpolation, I need to find the closest minimum and closest maximum value. for example the area[] is [1000, 1200, 1400, 1700, 2000] and the required area is 1500. Then closest minimum will give 1400 and closest maximum will give 1700
I also have loop for closest min and max, but I thought streams was efficient
for(int i=0; i< n; i++){
long val=newArea.get(i);
// long difference= Math.abs(reqArea-val);
if ((val< reqArea)&&((Math.abs(reqArea-val))< Math.abs(reqArea-closestMin))){
closestMin=val;
}
else if ((val>reqArea)&&(Math.abs(reqArea-val))< Math.abs(reqArea-closestMax)){
closestMax=val;
Ā Ā Ā Ā Ā Ā Ā Ā }
you're also looping an awfull lot over newArea
so maybe see if you can optimize that a bit
you could also set up a map<Long, List<Long>> <= where the key is area, and the latter is the list of prices
Try this out, if not works, I have one more place to optimize
I uploaded your attachments as Gist.
give me 2 mins to implement and run the code
Also just a tip since I see a decent bit of min/maxing. As of Java 21 there's a Math.clamp function
I am still running java 17 lol 
can u give me constraints of the problem @obtuse oasis ??
is it more than 10^4 ?
I optimized it to run in O(N^2) now i guess, running it in lower complexing needs time to think then and its 2 am for me 
bro, then this will not work, we need to do in O(N) or O(NlogN)
I can do that, but I am not in my mind cause its midnight
nope 
if i can somehow make outlier check func to be O(1), its solved
but the Q is... how?
I tried my best to do it and you did a better job in 20 mins
need to do some maths
long sd= Math.round(Math.sqrt(complist.stream().mapToDouble(val->Math.pow(val-mean,2)).sum()/(complist.size())));
Can u optimize it somehow, i will try other looop
yes
i will reduce mean
private static long computeSd(List<Long> data) {
double sum = 0.0;
long mean = computeMean(data);
for (long val : data) {
sum = sum + Math.pow(val - mean, 2);
}
return Math.round(Math.sqrt(sum / data.size()));
}
instead of calling the mean method, passing the value of mean would be better
This is O(N)
yeah
what is distA and distB in this?
but its giving O(N) for one value of list right, so for N values, there will be O(N*N) time
right
and this also doesn't help size wise: long closestMin=newArea.stream().filter(val->val<reqArea).min(Comparator.comparingLong(val->Math.abs(reqArea-val))).orElseThrow(NoSuchElementException::new);
long closestMax=newArea.stream().filter(val->val>reqArea).min(Comparator.comparingLong(val->Math.abs(reqArea-val))).orElseThrow(NoSuchElementException::new);
but also a tad late for me to rewrite that section
but try to reduce the amount of times you loop through your collections, try to group a bit. And indeed some things could be sets/hashmaps
I'm trying to implement the code you sent last @crisp pike
and both distA and distB are not initialised, should I initialise them with MAX_VALUE?
i did that i guess
oh yeah, sorry
Map<Long, Integer> map = new HashMap<>();
Map<Long, Long> prices = new HashMap<>();
for(int i=0; i<size; ++i) {
map.put(area.get(i), map.getOrDefault(area.get(i), 0)+1);
prices.put(area.get(i), prices.getOrDefault(area.get(i), 0L) + price.get(i));
}
for(int i=0; i<size; ++i)
mean[i] = map.get(area.get(i)) == 1 ? 0 : Math.round((prices.get(area.get(i)) - price.get(i)) / (map.get(area.get(i))-1));```
Detected code, here are some useful tools:
I implemented and calc all mean in O(N) like this
now need to think about standard deviation
ok
this code failed 1 test case which was passing earlier
we are keeping the outlier method same?
where will this code go?
below distA and distB, but this is of no use if i can't find variance faster
my mind is not working 
pleaseš
are u sure, I did not changed any logic?
yes, you dont worry about logic, I will handle that, but please optimise the code
i am thinking of optimizing the sd
but
mean is working good, i checked but sd .................... howwww 
I dont knowš š
I'll have a look at the logic
I got where the logic wrong
if the homes are of exact same area, we have to take mean of that
else if(newArea.contains(reqArea)){
// int c=0;
// double sum=0;
// for(int i=0; i<n;i++){
// if(newArea.get(i)==reqArea){
// c++;
// sum+= (newPrice.get(i));
// }
// }
// return Math.max(1000, Math.min(1000000, Math.round(sum/c)));
Ā Ā Ā Ā //Ā }
this one
got that 1 test case back, but the three optimisation one's are still thereš š
@crisp pike
i am trying to think but its 2:30 am now -_-
please
please
please
only standard deviation for O(N) is left?
we are not making any changes to isOutlier method?
I am trying to come up with something
okay, I'm waiting
got an idea, lets test it
I uploaded your attachments as Gist.
let me try and run it
u can get that test case back
I don't think, there should be time problem now 
There can be a wrong answer, but not time limit if i am right, optimized it too much!
I even ask, why ur school assignment needs too much of cleansing of code?
if this gives tle, I am ded for sure
is there a 0L in the second line of first for loop of the program?
no no
wait
2 mins
I'm getting some small errors
let me run at altest once
please
this won't give u tle, maybe wrong answer if i changed any logic in between, that u can change, like i removed round from mean and sd, u can do that
wait
it says
method outlier cannot be aplied to given types
Oh i made a mistake
please stay up for 2 more mins
yes
wrong output
but no ttle
but idk anything about this code
how do i debug????
still 3 test cases remainingš
@crisp pike
help me 1 last time
there are 2 error in interpolation
@crisp pike
please help me one last time, i would have debug, but I dont understand the map part
or at least explain it to me, so I can debug
wait 5 mins
sure
One of the test cases failing is not hidden, its this one
the expected output is 30625, but the output is 31667
How do I find the complist ?
try this one
I uploaded your attachments as Gist.
this is right answer on my latest one
right on this one
fingers crossed
if it works or does not works, I am going to sleep 
wait for 2 mins
Correct?
yes
I will explain this code then tomorrow okay? I will go to sleep u know 
This is hackerrank 
you came in the form of an angel
I saw
Difficulty is that because of the optimisation
yes, logic, I had sorted
We implemented mean and variance in O(1) for every element like bruhh
Yup, ur logic was correct, I did not changed any logic.. nor i understand.. I just optimized lol 
š thank you so much
I am a student umm
In an Asian University
cool
I guess so lol
Well, thank you soooooooooooo much
U did not answer my Q tho?
Why ur school needs u to solve this hard prob?
stupid teacher is challenging
And are u in school for real? Or university?
Wait, which country u are from?
India
Wao bro š
š
U do this stuff in dps ?
what did you think?
I thought u are like some American guy but u are just local to me
we dont do, but for internal marks, teachers make us do weird things
where are you from?
in india
U should complain .. this is not a problem for school students
Jaipur, rajasthan
exactly !!
I think, I'll be the only one to do
yes
Good night then 
I will explain the code tomorrow, ping me again on this thread if I forget
Closed the thread.
hey @obtuse oasis
Hey
here it is
I uploaded your attachments as Gist.
So, lets see how i calculated mean without loop
at that time, i did many things lol, i need to see ur code first so i can see where i changed stuff lol
u did that hmm
I uploaded your attachments as Gist.
@obtuse oasis in the part, where u were calc mean in isOutlier function, u looped through array to add values in compList which are same as the currentArea and later sum them
So, what u are doing is... u were calc sum of all x num in the list... but not the x itself
x + x + x + x + ......... to (n-1) times
which can be calculated as x*(n-1) right?
So, using hashmap named "map" here, i store the freq count of an area, let say, i got from the hashmap thay currentArea came 7 times in the "area" list
In "prices" map, this includes, all the prices of that area came
but on "prices" map, any area will contains a list of prices from index 1, and at index 0, it contains all the sum of the total prices in this area
Map<Long, List<Long>> prices = new HashMap<>();
for(int i=0; i<size; ++i) {
map.put(area.get(i), map.getOrDefault(area.get(i), 0)+1);
if(prices.containsKey(area.get(i))) {
prices.get(area.get(i)).add(price.get(i));
prices.get(area.get(i)).set(0, prices.get(area.get(i)).get(0) + price.get(i));
}
else {
List<Long> list = new ArrayList<>();
list.add(price.get(i));
list.add(price.get(i));
prices.put(area.get(i), list);
}
}```
Detected code, here are some useful tools:
Here, i am updating frequency or count of an area in "map"
and prices also, if it contains, add the new price, also put the current sum of whole on index 0
if not contains, make a new list with price of that on index 1, and on index 0, sum of all the prices in that area
Now, lets take an example!
area -> price
12 -> 100
13 -> 200
12 -> 300
12 -> 400
14 -> 500
Map -> [12, 3], [13, 1], [14, 1]
Prices -> [12, [800, 100, 300, 400]], [13, [200, 200]], [14, [500, 500]]
did u understand how, these maps filled? @obtuse oasis
lets say, for area 12, we need to find mean, then
mean = map.get(12) == 1 ? 0 : (prices.get(12).get(0) - (price[12])) / (map.get(12)-1);
it means, if the map only has one 12, then it means there are no more 12 other than 12, so out compList is empty and mean is 0
and if there is, then,
mean = sumOfAllOther12 / cntOfAllOther12
where
cntOfAllOther12 = cntOfAll12 - cntOfThis12(1) = 3 - 1 = 2
Hence, mean[0] = 700 / 2 = 350
mean[2] = (800-300)/(3-1) = 250```
Detected code, here are some useful tools:
1 min, I'm still trying to understand
oki
I did not understand this, how is 800 there?
prices.get(area.get(i)).set(0, prices.get(area.get(i)).get(0) + price.get(i));
Using this, I am updating the sum of all prices for that area at index 0
oh okayyy, and the first element is the sum
yup!
the use of ternary operator here is so cool
okay understood till here
So, now we can find mean in O(1) for every element of the array right?
// if there is only one element, then mean is 0, so this can't be an outlier so, return false, no need to check standard deviation
if(map.get(currentArea) == 1)
return false;
// intializing sd and trev ( a variable which checks, if i traversed currentPrice or not, because we won't be adding it)
double sd = 0;
boolean trev = false;
// traversing in map for currentArea (starting with index 1, cause index 0 is sum, not a individual price)
for(int i = 1; i < prices.get(currentArea).size(); ++i) {
// if i found a match, then put trev to true and we won't be adding it to sd
if(prices.get(currentArea).get(i) == currentPrice && !trev) {
trev = true;
continue;
}
// standard deviation = summationOf(x - mean)^2 / n
sd += Math.pow((prices.get(currentArea).get(i) - mean[index]), 2);
}
// Later dividing with numberOfN, which is stored in map ( but we are not taking the one with currentPrice, so map value -1 )
sd /= (map.get(currentArea)-1);
// Now we can check condition for outlier, where mean[index] is already calculated
return (Math.abs(currentPrice-mean[index]) > (3*Math.sqrt(sd)));
}```
```summationOf(x - mean)^2/n = ((x1 - mean)^2 + (x2 - mean)^2 + ........ (xn - mean)^2) / n```
Detected code, here are some useful tools:
read this out
i change some things too, like u were looping around for calc max and min also second max, which i concluded in above loop
Oki understood !!
took some timeš
so much for just checking if its an outlier or not
yeah, but its optimized š

