We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
NOTE: Case 11 fails because the result is too large to be supported by a 32-bit integer. You'll need to set the return type to a 64-bit integer to get it to work.
With that being said, here's a solution I've made in Java 8 that passes all test cases...
List<Integer>perCountryCount=newArrayList<Integer>();boolean[]astronautsChecked=newboolean[n];//Create neighbor listList<List<Integer>>astronautNeighbors=newArrayList<List<Integer>>();for(inti=0;i<n;i++){astronautNeighbors.add(newArrayList<Integer>());}//Populate neighbor listfor(List<Integer>pair:astronaut){intfirst=pair.get(0);intsecond=pair.get(1);astronautNeighbors.get(first).add(second);astronautNeighbors.get(second).add(first);}//Now, perform DFS on the astronauts array and determine the number of countries as well as the number of astronauts for each countryfor(intj=0;j<n;j++){if(!astronautsChecked[j]){perCountryCount.add(dfs(j,astronautsChecked,astronautNeighbors));}}longpairs=0L;longrunningSum=0L;for(intk=0;k<perCountryCount.size();k++){pairs+=runningSum*(long)perCountryCount.get(k);runningSum+=(long)perCountryCount.get(k);}returnpairs;}publicstaticintdfs(inti,boolean[]astronautsChecked,List<List<Integer>>astronautNeighbors){astronautsChecked[i]=true;intnewCountryCount=1;List<Integer>neighbors=astronautNeighbors.get(i);for(intj:neighbors){if(!astronautsChecked[j]){newCountryCount+=dfs(j,astronautsChecked,astronautNeighbors);}}System.out.println(i+" "+newCountryCount);returnnewCountryCount;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Journey to the Moon
You are viewing a single comment's thread. Return to all comments →
NOTE: Case 11 fails because the result is too large to be supported by a 32-bit integer. You'll need to set the return type to a 64-bit integer to get it to work.
With that being said, here's a solution I've made in Java 8 that passes all test cases...