• + 5 comments

    Java solution - passes 100% of test cases

    import java.util.Scanner;
    import java.util.Arrays;
    import java.util.HashMap;
    
    // Time Complexity: O(n log n) due to sorting
    public class Solution {
        public static void main(String[] args) {
            /* Save input */
            Scanner scan = new Scanner(System.in);
            int size = scan.nextInt();
            int [] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = scan.nextInt();
            }
            scan.close();
            
            /* Sort array: O(n log n) runtime */
            Arrays.sort(array);
            
            /* Calculate Mean */
            int total = 0;
            for (int num : array) {
                total += num;
            }
            double mean = (double) total / size;
            
            /* Calculate Median */
            double median;
            if (size % 2 == 0) {
                median = (array[size / 2 - 1] + array[size / 2]) / 2.0;
            } else {
                median = array[size / 2];
            }
            
            /* Calculate Mode - if there's a tie, choose the smaller number */
            HashMap<Integer, Integer> map = new HashMap<>();
            int maxOccurrences = 0;
            int mode = Integer.MAX_VALUE;
            for (int num : array) {
                map.merge(num, 1, Integer::sum);
                int occurrences = map.get(num);
                if (occurrences > maxOccurrences || (occurrences == maxOccurrences && num < mode)) {
                    maxOccurrences = occurrences;
                    mode = num;
                }
            }
    
            /* Print results */
            System.out.println(mean);
            System.out.println(median);
            System.out.println(mode);
        }
    }
    

    From my HackerRank Java solutions

    • + 3 comments

      i m unable to pass test case 3, can anyone help me?

      • + 0 comments

        Hi. Try posting your code in a new thread to reach a wider audience and for us to have the ability to see what's wrong. HackerRank solutions.

      • + 1 comment

        my code is also not able to pass test case 3,please help

        • + 0 comments

          Hi. Try posting your code in a new thread to reach a wider audience and for us to have the ability to see what's wrong. You can tag me in the post and I will take a look also.

          HackerRank solutions.

      • + 1 comment

        hi buddy here is the one of the easy code for you:

        import java.io.; import java.util.;

        public class Solution {

        public static void main(String[] args) {

        /*Take input from user*/
        Scanner sc = new Scanner(System.in);
        
        int n =0;
        n = sc.nextInt();
        
        int arr[] = new int[n];
        
        //////////////mean code starts here//////////////////
        int sum = 0;
        for(int i=0;i<n; i++)
        {
             arr[i] = sc.nextInt();
             sum += arr[i]; 
        }
        System.out.println((double)sum/n); 
        //////////////mean code ends here//////////////////
        
        
        //////////////median code starts here//////////////////
        Arrays.sort(arr);
        int val = arr.length/2;
        System.out.println((arr[val]+arr[val-1])/2.0); 
        //////////////median code ends here//////////////////
        
        
        //////////////mode code starts here//////////////////
        int maxValue=0;
        int maxCount=0;
        
        for(int i=0; i<n; ++i)
        {
            int count=0;
        
            for(int j=0; j<n; ++j)
            {
                if(arr[j] == arr[i])
                {
                    ++count;
                }
        
                if(count > maxCount)
                {
                    maxCount = count;
                    maxValue = arr[i];
                }
            }
        } 
        System.out.println(maxValue);
        

        //////////////mode code ends here//////////////////

        }

        }

        • + 0 comments
              // check mode, not necessary to use HashMap 
                      // or double for loops to calculate counts for each item;
              // assuming the first item would be the mode
                      int mode = arr[0];
              int max = 1;
              int appearance = 1;        
          
              for(int i=1; i<arr.length; i++){
          
                  if ( arr[i] == arr[i-1] ) {
                      appearance ++; 
          
                  } else {
                      appearance = 1; 
                  }
          
                  if( appearance > max ){
                      max = appearance; 
                      mode = arr[i]; 
                  }
          
              }
          
    • + 1 comment

      what is the use of map.merge(num,1,Integer::sum); can you help me please

      • + 1 comment

        That's a function that's part of HashMap, as shown here. If num does not exist as a key, it puts num as key, and 1 as a value into the HashMap.

        If on the other hand num already exists, then it just increments the value of num by 1.

        HackerRank solutions.

        • [deleted]
          + 2 comments

          other than hashmap there isnt any other code for mode calculation?

          • + 0 comments

            If the numbers are within a certain range, like 1 to 10, you can use a 10-element array.

            HackerRank solutions.

          • + 0 comments

            Yeah, I took advantage of the fact that I sorted the array to find the median.

            ` import java.util.Arrays;

            Arrays.sort(X); // X is our array of integers

                int mode = -1;
                int last = -1;
                int maxFreq = 0;
                int freq = 1;
                for (int x : X) {
                    if (x == last) {
                        freq++;
                    } else {
                        freq = 1;
                    }
            
                    // because numbers are sorted I only have to worry about strictly greater than.
                    if (freq > maxFreq) { 
                        maxFreq = freq;
                        mode = x;
                    }
            
                    last = x;
                }
            
    • + 0 comments

      Bro @rshaghoulian my Java solution does not run Test case 3 rest its working fine. As test data set is too huge i am not able to find the problem.

      Can you please review my code and tell me the possible error? Thanks in advance !

      import java.io.; import java.util.;

      public class Solution {

      public static void main(String[] args) {
          /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
          Scanner sc = new Scanner(System.in);
          int n = sc.nextInt();
          int []arr = new int[n];
          for(int i=0;i<n;i++){
              arr[i]=sc.nextInt();
          }
          sc.close();
          Arrays.sort(arr);
      
          //mean
          float sum=0;
          for(int i=0;i<n;i++){
              sum = sum + arr[i];
          }
          System.out.printf("%.1f",sum/n); System.out.println();
      
          //median
          int l=arr.length;
          if(l%2==1) {
              float med=arr[l/2];
              System.out.printf("%.1f",med);
          }else {
              int a=l/2;
              int b=a-1;
              double medd = (double)(arr[a]+arr[b])/2;
              System.out.printf("%.1f",medd);
          }
           System.out.println();
      
           //mode
          int mode=arr[0],max=0,count=0;
          HashMap<Integer, Integer> map = new HashMap<>();
      
          for(int i=0;i<l-1;i++) {
              if(arr[i]==arr[i+1]) {
                  count++;
                  map.put(arr[i], count);
              }
              else {
                  count=0;
              }
          }
          if(map.isEmpty())System.out.println(mode);
          else{
          for (int i : map.keySet()) {
              if(map.get(i)>max) {
                  max=map.get(i);
                  mode=i;
              }
          }
          System.out.println(mode);
          }
      
      }
      

      }

    • + 0 comments

      Thank YOU! I couldnt get the third test with mode to work till i used your hashmap! :) you rock